inst.h 21 KB

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