inst.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_TOOLCHAIN_SEM_IR_INST_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_INST_H_
  6. #include <concepts>
  7. #include <cstdint>
  8. #include "common/check.h"
  9. #include "common/hashing.h"
  10. #include "common/ostream.h"
  11. #include "common/raw_string_ostream.h"
  12. #include "common/struct_reflection.h"
  13. #include "toolchain/base/index_base.h"
  14. #include "toolchain/base/int.h"
  15. #include "toolchain/base/value_store.h"
  16. #include "toolchain/sem_ir/block_value_store.h"
  17. #include "toolchain/sem_ir/id_kind.h"
  18. #include "toolchain/sem_ir/inst_kind.h"
  19. #include "toolchain/sem_ir/singleton_insts.h"
  20. #include "toolchain/sem_ir/typed_insts.h"
  21. namespace Carbon::SemIR {
  22. // InstLikeTypeInfo is an implementation detail, and not public API.
  23. namespace Internal {
  24. // Information about an instruction-like type, which is a type that an Inst can
  25. // be converted to and from. The `Enabled` parameter is used to check
  26. // requirements on the type in the specializations of this template.
  27. template <typename InstLikeType>
  28. struct InstLikeTypeInfo;
  29. // A helper base class for instruction-like types that are structs.
  30. template <typename InstLikeType>
  31. struct InstLikeTypeInfoBase {
  32. // A corresponding std::tuple<...> type.
  33. using Tuple =
  34. decltype(StructReflection::AsTuple(std::declval<InstLikeType>()));
  35. static constexpr int FirstArgField =
  36. HasKindMemberAsField<InstLikeType> + HasTypeIdMember<InstLikeType>;
  37. static constexpr int NumArgs = std::tuple_size_v<Tuple> - FirstArgField;
  38. static_assert(NumArgs <= 2,
  39. "Unsupported: typed inst has more than two data fields");
  40. template <int N>
  41. using ArgType = std::tuple_element_t<FirstArgField + N, Tuple>;
  42. template <int N>
  43. static auto Get(InstLikeType inst) -> ArgType<N> {
  44. return std::get<FirstArgField + N>(StructReflection::AsTuple(inst));
  45. }
  46. };
  47. // A particular type of instruction is instruction-like.
  48. template <typename TypedInst>
  49. requires std::same_as<const InstKind::Definition<
  50. typename decltype(TypedInst::Kind)::TypedNodeId>,
  51. decltype(TypedInst::Kind)>
  52. struct InstLikeTypeInfo<TypedInst> : InstLikeTypeInfoBase<TypedInst> {
  53. static_assert(!HasKindMemberAsField<TypedInst>,
  54. "Instruction type should not have a kind field");
  55. static auto GetKind(TypedInst /*inst*/) -> InstKind {
  56. return TypedInst::Kind;
  57. }
  58. static auto IsKind(InstKind kind) -> bool { return kind == TypedInst::Kind; }
  59. // A name that can be streamed to an llvm::raw_ostream.
  60. static auto DebugName() -> InstKind { return TypedInst::Kind; }
  61. };
  62. // An instruction category is instruction-like.
  63. template <typename InstCat>
  64. requires std::same_as<const InstKind&, decltype(InstCat::Kinds[0])>
  65. struct InstLikeTypeInfo<InstCat> : InstLikeTypeInfoBase<InstCat> {
  66. static_assert(HasKindMemberAsField<InstCat>,
  67. "Instruction category should have a kind field");
  68. static auto GetKind(InstCat cat) -> InstKind { return cat.kind; }
  69. static auto IsKind(InstKind kind) -> bool {
  70. for (InstKind k : InstCat::Kinds) {
  71. if (k == kind) {
  72. return true;
  73. }
  74. }
  75. return false;
  76. }
  77. // A name that can be streamed to an llvm::raw_ostream.
  78. static auto DebugName() -> std::string {
  79. RawStringOstream out;
  80. out << "{";
  81. llvm::ListSeparator sep;
  82. for (auto kind : InstCat::Kinds) {
  83. out << sep << kind;
  84. }
  85. out << "}";
  86. return out.TakeStr();
  87. }
  88. };
  89. // A type is InstLike if InstLikeTypeInfo is defined for it.
  90. template <typename T>
  91. concept InstLikeType = requires { sizeof(InstLikeTypeInfo<T>); };
  92. } // namespace Internal
  93. // A type-erased representation of a SemIR instruction, that may be constructed
  94. // from the specific kinds of instruction defined in `typed_insts.h`. This
  95. // provides access to common fields present on most or all kinds of
  96. // instructions:
  97. //
  98. // - `kind` for run-time logic when the input Kind is unknown.
  99. // - `type_id` for quick type checking.
  100. //
  101. // In addition, kind-specific data can be accessed by casting to the specific
  102. // kind of instruction:
  103. //
  104. // - Use `inst.kind()` or `Is<InstLikeType>` to determine what kind of
  105. // instruction it is.
  106. // - Cast to a specific type using `inst.As<InstLikeType>()`
  107. // - Using the wrong kind in `inst.As<InstLikeType>()` is a programming error,
  108. // and will CHECK-fail in debug modes (opt may too, but it's not an API
  109. // guarantee).
  110. // - Use `inst.TryAs<InstLikeType>()` to safely access type-specific instruction
  111. // data where the instruction's kind is not known.
  112. class Inst : public Printable<Inst> {
  113. public:
  114. // Associates an argument (arg0 or arg1) with its IdKind.
  115. class ArgAndKind {
  116. public:
  117. explicit ArgAndKind(IdKind kind, int32_t value)
  118. : kind_(kind), value_(value) {}
  119. // Converts to `IdT`, validating the `kind` matches.
  120. template <typename IdT>
  121. auto As() const -> IdT {
  122. CARBON_DCHECK(kind_ == IdKind::For<IdT>);
  123. return IdT(value_);
  124. }
  125. // Converts to `IdT`, returning nullopt if the kind is incorrect.
  126. template <typename IdT>
  127. auto TryAs() const -> std::optional<IdT> {
  128. if (kind_ != IdKind::For<IdT>) {
  129. return std::nullopt;
  130. }
  131. return IdT(value_);
  132. }
  133. auto kind() const -> IdKind { return kind_; }
  134. auto value() const -> int32_t { return value_; }
  135. private:
  136. IdKind kind_;
  137. int32_t value_;
  138. };
  139. // Makes an instruction for a singleton. This exists to support simple
  140. // construction of all singletons by File.
  141. static auto MakeSingleton(InstKind kind) -> Inst {
  142. CARBON_CHECK(IsSingletonInstKind(kind));
  143. // Error uses a self-referential type so that it's not accidentally treated
  144. // as a normal type. Every other builtin is a type, including the
  145. // self-referential TypeType.
  146. auto type_id =
  147. kind == InstKind::ErrorInst ? ErrorInst::TypeId : TypeType::TypeId;
  148. return Inst(kind, type_id, InstId::NoneIndex, InstId::NoneIndex);
  149. }
  150. template <typename TypedInst>
  151. requires Internal::InstLikeType<TypedInst>
  152. // NOLINTNEXTLINE(google-explicit-constructor)
  153. Inst(TypedInst typed_inst)
  154. // kind_ is always overwritten below.
  155. : kind_(),
  156. type_id_(TypeId::None),
  157. arg0_(InstId::NoneIndex),
  158. arg1_(InstId::NoneIndex) {
  159. if constexpr (Internal::HasKindMemberAsField<TypedInst>) {
  160. kind_ = typed_inst.kind.AsInt();
  161. } else {
  162. kind_ = TypedInst::Kind.AsInt();
  163. }
  164. if constexpr (Internal::HasTypeIdMember<TypedInst>) {
  165. type_id_ = typed_inst.type_id;
  166. }
  167. using Info = Internal::InstLikeTypeInfo<TypedInst>;
  168. if constexpr (Info::NumArgs > 0) {
  169. arg0_ = ToRaw(Info::template Get<0>(typed_inst));
  170. }
  171. if constexpr (Info::NumArgs > 1) {
  172. arg1_ = ToRaw(Info::template Get<1>(typed_inst));
  173. }
  174. }
  175. // Returns whether this instruction has the specified type.
  176. template <typename TypedInst>
  177. requires Internal::InstLikeType<TypedInst>
  178. auto Is() const -> bool {
  179. return Internal::InstLikeTypeInfo<TypedInst>::IsKind(kind());
  180. }
  181. // Casts this instruction to the given typed instruction, which must match the
  182. // instruction's kind, and returns the typed instruction.
  183. template <typename TypedInst>
  184. requires Internal::InstLikeType<TypedInst>
  185. auto As() const -> TypedInst {
  186. using Info = Internal::InstLikeTypeInfo<TypedInst>;
  187. CARBON_CHECK(Is<TypedInst>(), "Casting inst {0} to wrong kind {1}", *this,
  188. Info::DebugName());
  189. auto build_with_type_id_onwards = [&](auto... type_id_onwards) {
  190. if constexpr (Internal::HasKindMemberAsField<TypedInst>) {
  191. return TypedInst{kind(), type_id_onwards...};
  192. } else {
  193. return TypedInst{type_id_onwards...};
  194. }
  195. };
  196. auto build_with_args = [&](auto... args) {
  197. if constexpr (Internal::HasTypeIdMember<TypedInst>) {
  198. return build_with_type_id_onwards(type_id(), args...);
  199. } else {
  200. return build_with_type_id_onwards(args...);
  201. }
  202. };
  203. if constexpr (Info::NumArgs == 0) {
  204. return build_with_args();
  205. } else if constexpr (Info::NumArgs == 1) {
  206. return build_with_args(
  207. FromRaw<typename Info::template ArgType<0>>(arg0_));
  208. } else if constexpr (Info::NumArgs == 2) {
  209. return build_with_args(
  210. FromRaw<typename Info::template ArgType<0>>(arg0_),
  211. FromRaw<typename Info::template ArgType<1>>(arg1_));
  212. }
  213. }
  214. // If this instruction is the given kind, returns a typed instruction,
  215. // otherwise returns nullopt.
  216. template <typename TypedInst>
  217. requires Internal::InstLikeType<TypedInst>
  218. auto TryAs() const -> std::optional<TypedInst> {
  219. if (Is<TypedInst>()) {
  220. return As<TypedInst>();
  221. } else {
  222. return std::nullopt;
  223. }
  224. }
  225. auto kind() const -> InstKind { return InstKind::FromInt(kind_); }
  226. // Gets the type of the value produced by evaluating this instruction.
  227. auto type_id() const -> TypeId { return type_id_; }
  228. // Gets the first argument of the instruction. NoneIndex if there is no such
  229. // argument.
  230. auto arg0() const -> int32_t { return arg0_; }
  231. // Gets the second argument of the instruction. NoneIndex if there is no such
  232. // argument.
  233. auto arg1() const -> int32_t { return arg1_; }
  234. // Returns arguments with their IdKind.
  235. auto arg0_and_kind() const -> ArgAndKind {
  236. return ArgAndKind(ArgKindTable[kind_].first, arg0_);
  237. }
  238. auto arg1_and_kind() const -> ArgAndKind {
  239. return ArgAndKind(ArgKindTable[kind_].second, arg1_);
  240. }
  241. // Sets the type of this instruction.
  242. auto SetType(TypeId type_id) -> void { type_id_ = type_id; }
  243. // Sets the arguments of this instruction.
  244. auto SetArgs(int32_t arg0, int32_t arg1) -> void {
  245. arg0_ = arg0;
  246. arg1_ = arg1;
  247. }
  248. // Convert a field to its raw representation, used as `arg0_` / `arg1_`.
  249. static constexpr auto ToRaw(AnyIdBase base) -> int32_t { return base.index; }
  250. static constexpr auto ToRaw(IntId id) -> int32_t { return id.AsRaw(); }
  251. // Convert a field from its raw representation.
  252. template <typename T>
  253. requires IdKind::Contains<T>
  254. static constexpr auto FromRaw(int32_t raw) -> T {
  255. return T(raw);
  256. }
  257. template <>
  258. constexpr auto FromRaw<IntId>(int32_t raw) -> IntId {
  259. return IntId::MakeRaw(raw);
  260. }
  261. auto Print(llvm::raw_ostream& out) const -> void;
  262. friend auto operator==(Inst lhs, Inst rhs) -> bool {
  263. return std::memcmp(&lhs, &rhs, sizeof(Inst)) == 0;
  264. }
  265. private:
  266. friend class InstTestHelper;
  267. // Table mapping instruction kinds to their argument kinds.
  268. //
  269. // TODO: ArgKindTable would ideally live on InstKind, but can't be there for
  270. // layering reasons.
  271. static const std::pair<IdKind, IdKind> ArgKindTable[];
  272. // Raw constructor, used for testing.
  273. explicit Inst(InstKind kind, TypeId type_id, int32_t arg0, int32_t arg1)
  274. : Inst(kind.AsInt(), type_id, arg0, arg1) {}
  275. explicit constexpr Inst(int32_t kind, TypeId type_id, int32_t arg0,
  276. int32_t arg1)
  277. : kind_(kind), type_id_(type_id), arg0_(arg0), arg1_(arg1) {}
  278. int32_t kind_;
  279. TypeId type_id_;
  280. // Use `As` to access arg0 and arg1.
  281. int32_t arg0_;
  282. int32_t arg1_;
  283. };
  284. // TODO: This is currently 16 bytes because we sometimes have 2 arguments for a
  285. // pair of Insts. However, InstKind is 1 byte; if args were 3.5 bytes, we could
  286. // potentially shrink Inst by 4 bytes. This may be worth investigating further.
  287. // Note though that 16 bytes is an ideal size for registers, we may want more
  288. // flags, and 12 bytes would be a more marginal improvement.
  289. static_assert(sizeof(Inst) == 16, "Unexpected Inst size");
  290. // Instruction-like types can be printed by converting them to instructions.
  291. template <typename TypedInst>
  292. requires Internal::InstLikeType<TypedInst>
  293. inline auto operator<<(llvm::raw_ostream& out, TypedInst inst)
  294. -> llvm::raw_ostream& {
  295. Inst(inst).Print(out);
  296. return out;
  297. }
  298. // Associates a LocId and Inst in order to provide type-checking that the
  299. // TypedNodeId corresponds to the InstT.
  300. struct LocIdAndInst {
  301. // Constructs a LocIdAndInst with no associated location. This should be used
  302. // very sparingly: only when it doesn't make sense to store a location even
  303. // when the instruction kind usually has one, such as for instructions in the
  304. // constants block.
  305. template <typename InstT>
  306. static auto NoLoc(InstT inst) -> LocIdAndInst {
  307. return LocIdAndInst(LocId::None, inst, /*is_unchecked=*/true);
  308. }
  309. // Unsafely form a pair of a location and an instruction. Used in the cases
  310. // where we can't statically enforce the type matches.
  311. static auto UncheckedLoc(LocId loc_id, Inst inst) -> LocIdAndInst {
  312. return LocIdAndInst(loc_id, inst, /*is_unchecked=*/true);
  313. }
  314. // Construction for the common case with a typed node.
  315. template <typename InstT>
  316. requires(Internal::HasNodeId<InstT>)
  317. LocIdAndInst(decltype(InstT::Kind)::TypedNodeId node_id, InstT inst)
  318. : loc_id(node_id), inst(inst) {}
  319. // Construction for the case where the instruction can have any associated
  320. // node.
  321. template <typename InstT>
  322. requires(Internal::HasUntypedNodeId<InstT>)
  323. LocIdAndInst(LocId loc_id, InstT inst) : loc_id(loc_id), inst(inst) {}
  324. LocId loc_id;
  325. Inst inst;
  326. private:
  327. // Note `is_unchecked` serves to disambiguate from public constructors.
  328. explicit LocIdAndInst(LocId loc_id, Inst inst, bool /*is_unchecked*/)
  329. : loc_id(loc_id), inst(inst) {}
  330. };
  331. // Provides a ValueStore wrapper for an API specific to instructions.
  332. class InstStore {
  333. public:
  334. explicit InstStore(File* file) : file_(file) {}
  335. // Adds an instruction to the instruction list, returning an ID to reference
  336. // the instruction. Note that this doesn't add the instruction to any
  337. // instruction block. Check::Context::AddInst or InstBlockStack::AddInst
  338. // should usually be used instead, to add the instruction to the current
  339. // block.
  340. auto AddInNoBlock(LocIdAndInst loc_id_and_inst) -> InstId {
  341. loc_ids_.push_back(loc_id_and_inst.loc_id);
  342. return values_.Add(loc_id_and_inst.inst);
  343. }
  344. // Returns the requested instruction. The returned instruction always has an
  345. // unattached type, even if an attached type is stored for it.
  346. auto Get(InstId inst_id) const -> Inst {
  347. Inst result = values_.Get(inst_id);
  348. auto type_id = result.type_id();
  349. if (type_id.has_value() && type_id.is_symbolic()) {
  350. result.SetType(GetUnattachedType(type_id));
  351. }
  352. return result;
  353. }
  354. // Returns the requested instruction, preserving its attached type.
  355. auto GetWithAttachedType(InstId inst_id) const -> Inst {
  356. return values_.Get(inst_id);
  357. }
  358. // Returns the type of the instruction as an attached type.
  359. auto GetAttachedType(InstId inst_id) const -> TypeId {
  360. return GetWithAttachedType(inst_id).type_id();
  361. }
  362. // Returns the requested instruction and its location ID.
  363. auto GetWithLocId(InstId inst_id) const -> LocIdAndInst {
  364. return LocIdAndInst::UncheckedLoc(LocId(inst_id), Get(inst_id));
  365. }
  366. // Returns whether the requested instruction is the specified type.
  367. template <typename InstT>
  368. auto Is(InstId inst_id) const -> bool {
  369. return Get(inst_id).Is<InstT>();
  370. }
  371. // Returns the requested instruction, which is known to have the specified
  372. // type.
  373. template <typename InstT>
  374. auto GetAs(InstId inst_id) const -> InstT {
  375. return Get(inst_id).As<InstT>();
  376. }
  377. // Returns the requested instruction as the specified type, if it is of that
  378. // type.
  379. template <typename InstT>
  380. auto TryGetAs(InstId inst_id) const -> std::optional<InstT> {
  381. return Get(inst_id).TryAs<InstT>();
  382. }
  383. // Returns the requested instruction as the specified type, if it is valid and
  384. // of that type. Otherwise returns nullopt.
  385. template <typename InstT>
  386. auto TryGetAsIfValid(InstId inst_id) const -> std::optional<InstT> {
  387. if (!inst_id.has_value()) {
  388. return std::nullopt;
  389. }
  390. return TryGetAs<InstT>(inst_id);
  391. }
  392. // Attempts to convert the given instruction to the type that contains
  393. // `member`. If it can be converted, the instruction ID and instruction are
  394. // replaced by the unwrapped value of that member, and the converted wrapper
  395. // instruction and its ID are returned. Otherwise returns {nullopt, None}.
  396. template <typename InstT, typename InstIdT>
  397. requires std::derived_from<InstIdT, InstId>
  398. auto TryUnwrap(Inst& inst, InstId& inst_id, InstIdT InstT::*member) const
  399. -> std::pair<std::optional<InstT>, InstId> {
  400. if (auto wrapped_inst = inst.TryAs<InstT>()) {
  401. auto wrapped_inst_id = inst_id;
  402. inst_id = (*wrapped_inst).*member;
  403. inst = Get(inst_id);
  404. return {wrapped_inst, wrapped_inst_id};
  405. }
  406. return {std::nullopt, InstId::None};
  407. }
  408. // Returns a resolved LocId, which will point to a parse node, an import, or
  409. // be None.
  410. //
  411. // Unresolved LocIds can be backed by an InstId which may or may not have a
  412. // value after being resolved, so this operation needs to be done before using
  413. // most operations on LocId.
  414. auto GetCanonicalLocId(LocId loc_id) const -> LocId {
  415. while (loc_id.kind() == LocId::Kind::InstId) {
  416. auto inst_id = loc_id.inst_id();
  417. CARBON_CHECK(inst_id.index >= 0, "{0}", inst_id.index);
  418. CARBON_CHECK(static_cast<size_t>(inst_id.index) < loc_ids_.size(),
  419. "{0} {1}", inst_id.index, loc_ids_.size());
  420. loc_id = loc_ids_[inst_id.index];
  421. }
  422. return loc_id;
  423. }
  424. // Gets the resolved LocId for an instruction. InstId can directly construct
  425. // an unresolved LocId. This skips that step when a resolved LocId is needed.
  426. auto GetCanonicalLocId(InstId inst_id) const -> LocId {
  427. CARBON_CHECK(inst_id.index >= 0, "{0}", inst_id.index);
  428. CARBON_CHECK(inst_id.index < (int)loc_ids_.size(), "{0} {1}", inst_id.index,
  429. loc_ids_.size());
  430. auto loc_id = loc_ids_[inst_id.index];
  431. return GetCanonicalLocId(loc_id);
  432. }
  433. // Overwrites a given instruction with a new value.
  434. auto Set(InstId inst_id, Inst inst) -> void { values_.Get(inst_id) = inst; }
  435. // Overwrites a given instruction's location with a new value.
  436. auto SetLocId(InstId inst_id, LocId loc_id) -> void {
  437. loc_ids_[inst_id.index] = loc_id;
  438. }
  439. // Overwrites a given instruction and location ID with a new value.
  440. auto SetLocIdAndInst(InstId inst_id, LocIdAndInst loc_id_and_inst) -> void {
  441. Set(inst_id, loc_id_and_inst.inst);
  442. SetLocId(inst_id, loc_id_and_inst.loc_id);
  443. }
  444. // Reserves space.
  445. auto Reserve(size_t size) -> void {
  446. loc_ids_.reserve(size);
  447. values_.Reserve(size);
  448. }
  449. // Collects memory usage of members.
  450. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  451. -> void {
  452. mem_usage.Collect(MemUsage::ConcatLabel(label, "loc_ids_"), loc_ids_);
  453. mem_usage.Collect(MemUsage::ConcatLabel(label, "values_"), values_);
  454. }
  455. auto array_ref() const -> llvm::ArrayRef<Inst> { return values_.array_ref(); }
  456. auto size() const -> int { return values_.size(); }
  457. auto enumerate() const -> auto { return values_.enumerate(); }
  458. private:
  459. // Given a symbolic type, get the corresponding unattached type.
  460. auto GetUnattachedType(TypeId type_id) const -> TypeId;
  461. File* file_;
  462. llvm::SmallVector<LocId> loc_ids_;
  463. ValueStore<InstId> values_;
  464. };
  465. // Adapts BlockValueStore for instruction blocks.
  466. class InstBlockStore : public BlockValueStore<InstBlockId> {
  467. public:
  468. using BaseType = BlockValueStore<InstBlockId>;
  469. explicit InstBlockStore(llvm::BumpPtrAllocator& allocator)
  470. : BaseType(allocator) {
  471. auto exports_id = AddPlaceholder();
  472. CARBON_CHECK(exports_id == InstBlockId::Exports);
  473. auto import_refs_id = AddPlaceholder();
  474. CARBON_CHECK(import_refs_id == InstBlockId::ImportRefs);
  475. auto global_init_id = AddPlaceholder();
  476. CARBON_CHECK(global_init_id == InstBlockId::GlobalInit);
  477. }
  478. // Adds an uninitialized block of the given size. The caller is expected to
  479. // modify values.
  480. auto AddUninitialized(size_t size) -> InstBlockId {
  481. return values().Add(AllocateUninitialized(size));
  482. }
  483. // Reserves and returns a block ID. The contents of the block should be
  484. // specified by calling ReplacePlaceholder.
  485. auto AddPlaceholder() -> InstBlockId {
  486. return values().Add(llvm::MutableArrayRef<ElementType>());
  487. }
  488. // Sets the contents of a placeholder block to the given content.
  489. auto ReplacePlaceholder(InstBlockId block_id, llvm::ArrayRef<InstId> content)
  490. -> void {
  491. CARBON_CHECK(block_id != InstBlockId::Empty);
  492. CARBON_CHECK(Get(block_id).empty(),
  493. "inst block content set more than once");
  494. values().Get(block_id) = AllocateCopy(content);
  495. }
  496. // Returns the contents of the specified block, or an empty array if the block
  497. // is invalid.
  498. auto GetOrEmpty(InstBlockId block_id) const -> llvm::ArrayRef<InstId> {
  499. return block_id.has_value() ? Get(block_id) : llvm::ArrayRef<InstId>();
  500. }
  501. };
  502. // See common/hashing.h.
  503. inline auto CarbonHashValue(const Inst& value, uint64_t seed) -> HashCode {
  504. Hasher hasher(seed);
  505. hasher.HashRaw(value);
  506. return static_cast<HashCode>(hasher);
  507. }
  508. } // namespace Carbon::SemIR
  509. #endif // CARBON_TOOLCHAIN_SEM_IR_INST_H_