inst.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. // Makes an instruction for a singleton. This exists to support simple
  115. // construction of all singletons by File.
  116. static auto MakeSingleton(InstKind kind) -> Inst {
  117. CARBON_CHECK(IsSingletonInstKind(kind));
  118. // Error uses a self-referential type so that it's not accidentally treated
  119. // as a normal type. Every other builtin is a type, including the
  120. // self-referential TypeType.
  121. auto type_id = kind == InstKind::ErrorInst ? ErrorInst::SingletonTypeId
  122. : TypeType::SingletonTypeId;
  123. return Inst(kind, type_id, InstId::NoneIndex, InstId::NoneIndex);
  124. }
  125. template <typename TypedInst>
  126. requires Internal::InstLikeType<TypedInst>
  127. // NOLINTNEXTLINE(google-explicit-constructor)
  128. Inst(TypedInst typed_inst)
  129. // kind_ is always overwritten below.
  130. : kind_(),
  131. type_id_(TypeId::None),
  132. arg0_(InstId::NoneIndex),
  133. arg1_(InstId::NoneIndex) {
  134. if constexpr (Internal::HasKindMemberAsField<TypedInst>) {
  135. kind_ = typed_inst.kind.AsInt();
  136. } else {
  137. kind_ = TypedInst::Kind.AsInt();
  138. }
  139. if constexpr (Internal::HasTypeIdMember<TypedInst>) {
  140. type_id_ = typed_inst.type_id;
  141. }
  142. using Info = Internal::InstLikeTypeInfo<TypedInst>;
  143. if constexpr (Info::NumArgs > 0) {
  144. arg0_ = ToRaw(Info::template Get<0>(typed_inst));
  145. }
  146. if constexpr (Info::NumArgs > 1) {
  147. arg1_ = ToRaw(Info::template Get<1>(typed_inst));
  148. }
  149. }
  150. // Returns whether this instruction has the specified type.
  151. template <typename TypedInst>
  152. requires Internal::InstLikeType<TypedInst>
  153. auto Is() const -> bool {
  154. return Internal::InstLikeTypeInfo<TypedInst>::IsKind(kind());
  155. }
  156. // Casts this instruction to the given typed instruction, which must match the
  157. // instruction's kind, and returns the typed instruction.
  158. template <typename TypedInst>
  159. requires Internal::InstLikeType<TypedInst>
  160. auto As() const -> TypedInst {
  161. using Info = Internal::InstLikeTypeInfo<TypedInst>;
  162. CARBON_CHECK(Is<TypedInst>(), "Casting inst {0} to wrong kind {1}", *this,
  163. Info::DebugName());
  164. auto build_with_type_id_onwards = [&](auto... type_id_onwards) {
  165. if constexpr (Internal::HasKindMemberAsField<TypedInst>) {
  166. return TypedInst{kind(), type_id_onwards...};
  167. } else {
  168. return TypedInst{type_id_onwards...};
  169. }
  170. };
  171. auto build_with_args = [&](auto... args) {
  172. if constexpr (Internal::HasTypeIdMember<TypedInst>) {
  173. return build_with_type_id_onwards(type_id(), args...);
  174. } else {
  175. return build_with_type_id_onwards(args...);
  176. }
  177. };
  178. if constexpr (Info::NumArgs == 0) {
  179. return build_with_args();
  180. } else if constexpr (Info::NumArgs == 1) {
  181. return build_with_args(
  182. FromRaw<typename Info::template ArgType<0>>(arg0_));
  183. } else if constexpr (Info::NumArgs == 2) {
  184. return build_with_args(
  185. FromRaw<typename Info::template ArgType<0>>(arg0_),
  186. FromRaw<typename Info::template ArgType<1>>(arg1_));
  187. }
  188. }
  189. // If this instruction is the given kind, returns a typed instruction,
  190. // otherwise returns nullopt.
  191. template <typename TypedInst>
  192. requires Internal::InstLikeType<TypedInst>
  193. auto TryAs() const -> std::optional<TypedInst> {
  194. if (Is<TypedInst>()) {
  195. return As<TypedInst>();
  196. } else {
  197. return std::nullopt;
  198. }
  199. }
  200. auto kind() const -> InstKind { return InstKind::FromInt(kind_); }
  201. // Gets the type of the value produced by evaluating this instruction.
  202. auto type_id() const -> TypeId { return type_id_; }
  203. // Gets the kinds of IDs used for arg0 and arg1 of the specified kind of
  204. // instruction.
  205. //
  206. // TODO: This would ideally live on InstKind, but can't be there for layering
  207. // reasons.
  208. static auto ArgKinds(InstKind kind) -> std::pair<IdKind, IdKind> {
  209. return ArgKindTable[kind.AsInt()];
  210. }
  211. // Gets the kinds of IDs used for arg0 and arg1 of this instruction.
  212. auto ArgKinds() const -> std::pair<IdKind, IdKind> {
  213. return ArgKinds(kind());
  214. }
  215. // Gets the first argument of the instruction. InvalidIndex if there is no
  216. // such argument.
  217. auto arg0() const -> int32_t { return arg0_; }
  218. // Gets the second argument of the instruction. InvalidIndex if there is no
  219. // such argument.
  220. auto arg1() const -> int32_t { return arg1_; }
  221. // Sets the type of this instruction.
  222. auto SetType(TypeId type_id) -> void { type_id_ = type_id; }
  223. // Sets the arguments of this instruction.
  224. auto SetArgs(int32_t arg0, int32_t arg1) {
  225. arg0_ = arg0;
  226. arg1_ = arg1;
  227. }
  228. // Convert a field to its raw representation, used as `arg0_` / `arg1_`.
  229. static constexpr auto ToRaw(AnyIdBase base) -> int32_t { return base.index; }
  230. static constexpr auto ToRaw(IntId id) -> int32_t { return id.AsRaw(); }
  231. // Convert a field from its raw representation.
  232. template <typename T>
  233. requires IdKind::Contains<T>
  234. static constexpr auto FromRaw(int32_t raw) -> T {
  235. return T(raw);
  236. }
  237. template <>
  238. constexpr auto FromRaw<IntId>(int32_t raw) -> IntId {
  239. return IntId::MakeRaw(raw);
  240. }
  241. auto Print(llvm::raw_ostream& out) const -> void;
  242. friend auto operator==(Inst lhs, Inst rhs) -> bool {
  243. return std::memcmp(&lhs, &rhs, sizeof(Inst)) == 0;
  244. }
  245. private:
  246. friend class InstTestHelper;
  247. // Table mapping instruction kinds to their argument kinds.
  248. static const std::pair<IdKind, IdKind> ArgKindTable[];
  249. // Raw constructor, used for testing.
  250. explicit Inst(InstKind kind, TypeId type_id, int32_t arg0, int32_t arg1)
  251. : Inst(kind.AsInt(), type_id, arg0, arg1) {}
  252. explicit Inst(int32_t kind, TypeId type_id, int32_t arg0, int32_t arg1)
  253. : kind_(kind), type_id_(type_id), arg0_(arg0), arg1_(arg1) {}
  254. int32_t kind_;
  255. TypeId type_id_;
  256. // Use `As` to access arg0 and arg1.
  257. int32_t arg0_;
  258. int32_t arg1_;
  259. };
  260. // TODO: This is currently 16 bytes because we sometimes have 2 arguments for a
  261. // pair of Insts. However, InstKind is 1 byte; if args were 3.5 bytes, we could
  262. // potentially shrink Inst by 4 bytes. This may be worth investigating further.
  263. // Note though that 16 bytes is an ideal size for registers, we may want more
  264. // flags, and 12 bytes would be a more marginal improvement.
  265. static_assert(sizeof(Inst) == 16, "Unexpected Inst size");
  266. // Instruction-like types can be printed by converting them to instructions.
  267. template <typename TypedInst>
  268. requires Internal::InstLikeType<TypedInst>
  269. inline auto operator<<(llvm::raw_ostream& out, TypedInst inst)
  270. -> llvm::raw_ostream& {
  271. Inst(inst).Print(out);
  272. return out;
  273. }
  274. // Associates a LocId and Inst in order to provide type-checking that the
  275. // TypedNodeId corresponds to the InstT.
  276. struct LocIdAndInst {
  277. // Constructs a LocIdAndInst with no associated location. This should be used
  278. // very sparingly: only when it doesn't make sense to store a location even
  279. // when the instruction kind usually has one, such as for instructions in the
  280. // constants block.
  281. template <typename InstT>
  282. static auto NoLoc(InstT inst) -> LocIdAndInst {
  283. return LocIdAndInst(LocId::None, inst, /*is_unchecked=*/true);
  284. }
  285. // Unsafely form a pair of a location and an instruction. Used in the cases
  286. // where we can't statically enforce the type matches.
  287. static auto UncheckedLoc(LocId loc_id, Inst inst) -> LocIdAndInst {
  288. return LocIdAndInst(loc_id, inst, /*is_unchecked=*/true);
  289. }
  290. // Construction for the common case with a typed node.
  291. template <typename InstT>
  292. requires(Internal::HasNodeId<InstT>)
  293. LocIdAndInst(decltype(InstT::Kind)::TypedNodeId node_id, InstT inst)
  294. : loc_id(node_id), inst(inst) {}
  295. // Construction for the case where the instruction can have any associated
  296. // node.
  297. template <typename InstT>
  298. requires(Internal::HasUntypedNodeId<InstT>)
  299. LocIdAndInst(SemIR::LocId loc_id, InstT inst) : loc_id(loc_id), inst(inst) {}
  300. LocId loc_id;
  301. Inst inst;
  302. private:
  303. // Note `is_unchecked` serves to disambiguate from public constructors.
  304. explicit LocIdAndInst(LocId loc_id, Inst inst, bool /*is_unchecked*/)
  305. : loc_id(loc_id), inst(inst) {}
  306. };
  307. // Provides a ValueStore wrapper for an API specific to instructions.
  308. class InstStore {
  309. public:
  310. // Adds an instruction to the instruction list, returning an ID to reference
  311. // the instruction. Note that this doesn't add the instruction to any
  312. // instruction block. Check::Context::AddInst or InstBlockStack::AddInst
  313. // should usually be used instead, to add the instruction to the current
  314. // block.
  315. auto AddInNoBlock(LocIdAndInst loc_id_and_inst) -> InstId {
  316. loc_ids_.push_back(loc_id_and_inst.loc_id);
  317. return values_.Add(loc_id_and_inst.inst);
  318. }
  319. // Returns the requested instruction.
  320. auto Get(InstId inst_id) const -> Inst { return values_.Get(inst_id); }
  321. // Returns the requested instruction and its location ID.
  322. auto GetWithLocId(InstId inst_id) const -> LocIdAndInst {
  323. return LocIdAndInst::UncheckedLoc(GetLocId(inst_id), Get(inst_id));
  324. }
  325. // Returns whether the requested instruction is the specified type.
  326. template <typename InstT>
  327. auto Is(InstId inst_id) const -> bool {
  328. return Get(inst_id).Is<InstT>();
  329. }
  330. // Returns the requested instruction, which is known to have the specified
  331. // type.
  332. template <typename InstT>
  333. auto GetAs(InstId inst_id) const -> InstT {
  334. return Get(inst_id).As<InstT>();
  335. }
  336. // Returns the requested instruction as the specified type, if it is of that
  337. // type.
  338. template <typename InstT>
  339. auto TryGetAs(InstId inst_id) const -> std::optional<InstT> {
  340. return Get(inst_id).TryAs<InstT>();
  341. }
  342. // Returns the requested instruction as the specified type, if it is valid and
  343. // of that type. Otherwise returns nullopt.
  344. template <typename InstT>
  345. auto TryGetAsIfValid(InstId inst_id) const -> std::optional<InstT> {
  346. if (!inst_id.has_value()) {
  347. return std::nullopt;
  348. }
  349. return TryGetAs<InstT>(inst_id);
  350. }
  351. auto GetLocId(InstId inst_id) const -> LocId {
  352. CARBON_CHECK(inst_id.index >= 0, "{0}", inst_id.index);
  353. CARBON_CHECK(inst_id.index < (int)loc_ids_.size(), "{0} {1}", inst_id.index,
  354. loc_ids_.size());
  355. return loc_ids_[inst_id.index];
  356. }
  357. // Overwrites a given instruction with a new value.
  358. auto Set(InstId inst_id, Inst inst) -> void { values_.Get(inst_id) = inst; }
  359. // Overwrites a given instruction's location with a new value.
  360. auto SetLocId(InstId inst_id, LocId loc_id) -> void {
  361. loc_ids_[inst_id.index] = loc_id;
  362. }
  363. // Overwrites a given instruction and location ID with a new value.
  364. auto SetLocIdAndInst(InstId inst_id, LocIdAndInst loc_id_and_inst) -> void {
  365. Set(inst_id, loc_id_and_inst.inst);
  366. SetLocId(inst_id, loc_id_and_inst.loc_id);
  367. }
  368. // Reserves space.
  369. auto Reserve(size_t size) -> void {
  370. loc_ids_.reserve(size);
  371. values_.Reserve(size);
  372. }
  373. // Collects memory usage of members.
  374. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  375. -> void {
  376. mem_usage.Collect(MemUsage::ConcatLabel(label, "loc_ids_"), loc_ids_);
  377. mem_usage.Collect(MemUsage::ConcatLabel(label, "values_"), values_);
  378. }
  379. auto array_ref() const -> llvm::ArrayRef<Inst> { return values_.array_ref(); }
  380. auto size() const -> int { return values_.size(); }
  381. private:
  382. llvm::SmallVector<LocId> loc_ids_;
  383. ValueStore<InstId> values_;
  384. };
  385. // Adapts BlockValueStore for instruction blocks.
  386. class InstBlockStore : public BlockValueStore<InstBlockId> {
  387. public:
  388. using BaseType = BlockValueStore<InstBlockId>;
  389. using BaseType::AddDefaultValue;
  390. using BaseType::AddUninitialized;
  391. explicit InstBlockStore(llvm::BumpPtrAllocator& allocator)
  392. : BaseType(allocator) {
  393. auto exports_id = AddDefaultValue();
  394. CARBON_CHECK(exports_id == InstBlockId::Exports);
  395. auto import_refs_id = AddDefaultValue();
  396. CARBON_CHECK(import_refs_id == InstBlockId::ImportRefs);
  397. auto global_init_id = AddDefaultValue();
  398. CARBON_CHECK(global_init_id == InstBlockId::GlobalInit);
  399. }
  400. auto Set(InstBlockId block_id, llvm::ArrayRef<InstId> content) -> void {
  401. CARBON_CHECK(block_id != InstBlockId::Unreachable);
  402. BlockValueStore<InstBlockId>::SetContent(block_id, content);
  403. }
  404. // Returns the contents of the specified block, or an empty array if the block
  405. // is invalid.
  406. auto GetOrEmpty(InstBlockId block_id) const -> llvm::ArrayRef<InstId> {
  407. return block_id.has_value() ? Get(block_id) : llvm::ArrayRef<InstId>();
  408. }
  409. };
  410. // See common/hashing.h.
  411. inline auto CarbonHashValue(const Inst& value, uint64_t seed) -> HashCode {
  412. Hasher hasher(seed);
  413. hasher.HashRaw(value);
  414. return static_cast<HashCode>(hasher);
  415. }
  416. } // namespace Carbon::SemIR
  417. #endif // CARBON_TOOLCHAIN_SEM_IR_INST_H_