ids.h 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  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_IDS_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_IDS_H_
  6. #include <limits>
  7. #include "common/check.h"
  8. #include "common/ostream.h"
  9. #include "llvm/ADT/APFloat.h"
  10. #include "toolchain/base/index_base.h"
  11. #include "toolchain/base/value_ids.h"
  12. #include "toolchain/diagnostics/emitter.h"
  13. #include "toolchain/parse/node_ids.h"
  14. namespace Carbon::SemIR {
  15. // TODO: This is in use, but not here.
  16. class File;
  17. // The ID of an `Inst`.
  18. struct InstId : public IdBase<InstId> {
  19. static constexpr llvm::StringLiteral Label = "inst";
  20. // The maximum ID, inclusive.
  21. static constexpr int Max = std::numeric_limits<int32_t>::max();
  22. // Represents the result of a name lookup that is temporarily disallowed
  23. // because the name is currently being initialized.
  24. static const InstId InitTombstone;
  25. // A placeholder used in the `ImplWitness` table of instructions for members
  26. // of the impl. These are replaced as values are seen for the witness table in
  27. // the impl declaration or definition. This is distinct from `None` for
  28. // debugging purposes.
  29. static const InstId ImplWitnessTablePlaceholder;
  30. using IdBase::IdBase;
  31. auto Print(llvm::raw_ostream& out) const -> void;
  32. };
  33. inline constexpr InstId InstId::InitTombstone = InstId(NoneIndex - 1);
  34. inline constexpr InstId InstId::ImplWitnessTablePlaceholder =
  35. InstId(NoneIndex - 2);
  36. // An InstId whose value is a type. The fact it's a type must be validated
  37. // before construction, and this allows that validation to be represented in the
  38. // type system.
  39. struct TypeInstId : public InstId {
  40. static const TypeInstId None;
  41. using InstId::InstId;
  42. static constexpr auto UnsafeMake(InstId id) -> TypeInstId {
  43. return TypeInstId(UnsafeCtor(), id);
  44. }
  45. private:
  46. struct UnsafeCtor {};
  47. explicit constexpr TypeInstId(UnsafeCtor /*unsafe*/, InstId id)
  48. : InstId(id) {}
  49. };
  50. inline constexpr TypeInstId TypeInstId::None =
  51. TypeInstId::UnsafeMake(InstId::None);
  52. // An InstId whose type is known to be T. The fact it's a type must be validated
  53. // before construction, and this allows that validation to be represented in the
  54. // type system.
  55. //
  56. // Unlike TypeInstId, this type can *not* be an operand in instructions, since
  57. // being a template prevents it from being used in non-generic contexts such as
  58. // switches.
  59. template <typename T>
  60. struct KnownInstId : public InstId {
  61. static const KnownInstId None;
  62. using InstId::InstId;
  63. static constexpr auto UnsafeMake(InstId id) -> KnownInstId {
  64. return KnownInstId(UnsafeCtor(), id);
  65. }
  66. private:
  67. struct UnsafeCtor {};
  68. explicit constexpr KnownInstId(UnsafeCtor /*unsafe*/, InstId id)
  69. : InstId(id) {}
  70. };
  71. template <typename T>
  72. inline constexpr KnownInstId<T> KnownInstId<T>::None =
  73. KnownInstId<T>::UnsafeMake(InstId::None);
  74. // An ID of an instruction that is referenced absolutely by another instruction.
  75. // This should only be used as the type of a field within a typed instruction
  76. // class.
  77. //
  78. // When a typed instruction has a field of this type, that field represents an
  79. // absolute reference to another instruction that typically resides in a
  80. // different entity. This behaves in most respects like an InstId field, but
  81. // substitution into the typed instruction leaves the field unchanged rather
  82. // than substituting into it.
  83. class AbsoluteInstId : public InstId {
  84. public:
  85. static constexpr llvm::StringLiteral Label = "absolute_inst";
  86. // Support implicit conversion from InstId so that InstId and AbsoluteInstId
  87. // have the same interface.
  88. explicit(false) constexpr AbsoluteInstId(InstId inst_id) : InstId(inst_id) {}
  89. using InstId::InstId;
  90. };
  91. // An ID of an instruction that is used as the destination of an initializing
  92. // expression. This should only be used as the type of a field within a typed
  93. // instruction class.
  94. //
  95. // This behaves in most respects like an InstId field, but constant evaluation
  96. // of an instruction with a destination field will not evaluate this field, and
  97. // substitution will not substitute into it.
  98. //
  99. // TODO: Decide on how substitution should handle this. Multiple instructions
  100. // can refer to the same destination, so these don't have the tree structure
  101. // that substitution expects, but we might need to substitute into the result of
  102. // an instruction.
  103. class DestInstId : public InstId {
  104. public:
  105. static constexpr llvm::StringLiteral Label = "dest_inst";
  106. // Support implicit conversion from InstId so that InstId and DestInstId
  107. // have the same interface.
  108. explicit(false) constexpr DestInstId(InstId inst_id) : InstId(inst_id) {}
  109. using InstId::InstId;
  110. };
  111. // An ID of an instruction that is referenced as a meta-operand of an action.
  112. // This should only be used as the type of a field within a typed instruction
  113. // class.
  114. //
  115. // This is used to model cases where an action's operand is not the value
  116. // produced by another instruction, but is the other instruction itself. This is
  117. // common for actions representing template instantiation.
  118. //
  119. // This behaves in most respects like an InstId field, but evaluation of the
  120. // instruction that has this field will not fail if the instruction does not
  121. // have a constant value. If the instruction has a constant value, it will still
  122. // be replaced by its constant value during evaluation like normal, but if it
  123. // has a non-constant value, the field is left unchanged by evaluation.
  124. class MetaInstId : public InstId {
  125. public:
  126. static constexpr llvm::StringLiteral Label = "meta_inst";
  127. // Support implicit conversion from InstId so that InstId and MetaInstId
  128. // have the same interface.
  129. explicit(false) constexpr MetaInstId(InstId inst_id) : InstId(inst_id) {}
  130. using InstId::InstId;
  131. };
  132. // The ID of a constant value of an expression. An expression is either:
  133. //
  134. // - a concrete constant, whose value does not depend on any generic parameters,
  135. // such as `42` or `i32*` or `("hello", "world")`, or
  136. // - a symbolic constant, whose value includes a generic parameter, such as
  137. // `Vector(T*)`, or
  138. // - a runtime expression, such as `Print("hello")`.
  139. //
  140. // Concrete constants are a thin wrapper around the instruction ID of the
  141. // constant instruction that defines the constant. Symbolic constants are an
  142. // index into a separate table of `SymbolicConstant`s maintained by the constant
  143. // value store.
  144. //
  145. // IdTags for ConstantIds are slightly complex, and you need to know if the
  146. // constant is concrete or symbolic to know its tag:
  147. // - Concrete ConstantIds use the tag of the store of InstIds.
  148. // - Symbolic ConstantIds use the tag of the store of internal SymbolicIds.
  149. struct ConstantId : public IdBase<ConstantId> {
  150. static constexpr llvm::StringLiteral Label = "constant";
  151. // An ID for an expression that is not constant.
  152. static const ConstantId NotConstant;
  153. // Returns the constant ID corresponding to a concrete constant, which should
  154. // either be in the `constants` block in the file or should be known to be
  155. // unique.
  156. static constexpr auto ForConcreteConstant(InstId const_id) -> ConstantId {
  157. return ConstantId(const_id.index);
  158. }
  159. using IdBase::IdBase;
  160. // Returns whether this represents a constant. Requires has_value.
  161. constexpr auto is_constant() const -> bool {
  162. CARBON_DCHECK(has_value());
  163. return *this != ConstantId::NotConstant;
  164. }
  165. // Returns whether this represents a symbolic constant. Requires has_value.
  166. constexpr auto is_symbolic() const -> bool {
  167. CARBON_DCHECK(has_value());
  168. return index <= FirstSymbolicId;
  169. }
  170. // Returns whether this represents a concrete constant. Requires has_value.
  171. constexpr auto is_concrete() const -> bool {
  172. CARBON_DCHECK(has_value());
  173. return index >= 0;
  174. }
  175. // Prints this ID to the given output stream. `disambiguate` indicates whether
  176. // concrete constants should be wrapped with "concrete_constant(...)" so that
  177. // they aren't printed the same as an InstId. This can be set to false if
  178. // there is no risk of ambiguity.
  179. auto Print(llvm::raw_ostream& out, bool disambiguate = true) const -> void;
  180. private:
  181. friend class ConstantValueStore;
  182. // For Dump.
  183. friend auto MakeSymbolicConstantId(int id) -> ConstantId;
  184. // A symbolic constant.
  185. struct SymbolicId : public IdBase<SymbolicId> {
  186. static constexpr llvm::StringLiteral Label = "symbolic_constant";
  187. using IdBase::IdBase;
  188. };
  189. // Returns the constant ID corresponding to a symbolic constant index.
  190. static constexpr auto ForSymbolicConstantId(SymbolicId symbolic_id)
  191. -> ConstantId {
  192. return ConstantId(FirstSymbolicId - symbolic_id.index);
  193. }
  194. // TODO: C++23 makes std::abs constexpr, but until then we mirror std::abs
  195. // logic here. LLVM should still optimize this.
  196. static constexpr auto Abs(int32_t i) -> int32_t { return i > 0 ? i : -i; }
  197. // Returns the instruction that describes this concrete constant value.
  198. // Requires `is_concrete()`. Use `ConstantValueStore::GetInstId` to get the
  199. // instruction ID of a `ConstantId`.
  200. constexpr auto concrete_inst_id() const -> InstId {
  201. CARBON_DCHECK(is_concrete());
  202. return InstId(index);
  203. }
  204. // Returns the symbolic constant index that describes this symbolic constant
  205. // value. Requires `is_symbolic()`.
  206. constexpr auto symbolic_id() const -> SymbolicId {
  207. CARBON_DCHECK(is_symbolic());
  208. return SymbolicId(FirstSymbolicId - index);
  209. }
  210. static constexpr int32_t NotConstantIndex = NoneIndex - 1;
  211. static constexpr int32_t FirstSymbolicId = NoneIndex - 2;
  212. };
  213. inline constexpr ConstantId ConstantId::NotConstant =
  214. ConstantId(NotConstantIndex);
  215. // The ID of a `EntityName`.
  216. struct EntityNameId : public IdBase<EntityNameId> {
  217. static constexpr llvm::StringLiteral Label = "entity_name";
  218. using IdBase::IdBase;
  219. };
  220. // The ID of a C++ global variable.
  221. struct CppGlobalVarId : public IdBase<CppGlobalVarId> {
  222. static constexpr llvm::StringLiteral Label = "cpp_global_var";
  223. using IdBase::IdBase;
  224. };
  225. // The index of a compile-time binding. This is the de Bruijn level for the
  226. // binding -- that is, this is the number of other compile time bindings whose
  227. // scope encloses this binding.
  228. struct CompileTimeBindIndex : public IndexBase<CompileTimeBindIndex> {
  229. static constexpr llvm::StringLiteral Label = "comp_time_bind";
  230. using IndexBase::IndexBase;
  231. };
  232. // The index of a `Call` parameter in a function. These are allocated
  233. // sequentially, left-to-right, to the function parameters that will have
  234. // arguments passed to them at runtime. In a `Call` instruction, a runtime
  235. // argument will have the position in the argument list corresponding to its
  236. // `Call` parameter index.
  237. struct CallParamIndex : public IndexBase<CallParamIndex> {
  238. static constexpr llvm::StringLiteral Label = "call_param";
  239. using IndexBase::IndexBase;
  240. };
  241. // The ID of a C++ overload set.
  242. struct CppOverloadSetId : public IdBase<CppOverloadSetId> {
  243. static constexpr llvm::StringLiteral Label = "cpp_overload_set";
  244. using IdBase::IdBase;
  245. };
  246. // The ID of a function.
  247. struct FunctionId : public IdBase<FunctionId> {
  248. static constexpr llvm::StringLiteral Label = "function";
  249. using IdBase::IdBase;
  250. };
  251. // The ID of an IR within the set of all IRs being evaluated in the current
  252. // check execution.
  253. struct CheckIRId : public IdBase<CheckIRId> {
  254. static constexpr llvm::StringLiteral Label = "check_ir";
  255. // Used when referring to the imported C++.
  256. static const CheckIRId Cpp;
  257. using IdBase::IdBase;
  258. auto Print(llvm::raw_ostream& out) const -> void;
  259. };
  260. inline constexpr CheckIRId CheckIRId::Cpp = CheckIRId(NoneIndex - 1);
  261. // The ID of a `Class`.
  262. struct ClassId : public IdBase<ClassId> {
  263. static constexpr llvm::StringLiteral Label = "class";
  264. using IdBase::IdBase;
  265. };
  266. // The ID of a `Vtable`.
  267. struct VtableId : public IdBase<VtableId> {
  268. static constexpr llvm::StringLiteral Label = "vtable";
  269. using IdBase::IdBase;
  270. };
  271. // The ID of an `Interface`.
  272. struct InterfaceId : public IdBase<InterfaceId> {
  273. static constexpr llvm::StringLiteral Label = "interface";
  274. using IdBase::IdBase;
  275. };
  276. // The ID of a `NamedConstraint`.
  277. struct NamedConstraintId : public IdBase<NamedConstraintId> {
  278. static constexpr llvm::StringLiteral Label = "constraint";
  279. using IdBase::IdBase;
  280. };
  281. // The ID of an `AssociatedConstant`.
  282. struct AssociatedConstantId : public IdBase<AssociatedConstantId> {
  283. static constexpr llvm::StringLiteral Label = "assoc_const";
  284. using IdBase::IdBase;
  285. };
  286. // The ID of a `FacetTypeInfo`.
  287. struct FacetTypeId : public IdBase<FacetTypeId> {
  288. static constexpr llvm::StringLiteral Label = "facet_type";
  289. using DiagnosticType = Diagnostics::TypeInfo<std::string>;
  290. using IdBase::IdBase;
  291. };
  292. // The ID of an resolved facet type value.
  293. struct IdentifiedFacetTypeId : public IdBase<IdentifiedFacetTypeId> {
  294. static constexpr llvm::StringLiteral Label = "identified_facet_type";
  295. using IdBase::IdBase;
  296. };
  297. // The ID of an `Impl`.
  298. struct ImplId : public IdBase<ImplId> {
  299. using DiagnosticType = Diagnostics::TypeInfo<std::string>;
  300. static constexpr llvm::StringLiteral Label = "impl";
  301. using IdBase::IdBase;
  302. };
  303. // The ID of a `Generic`.
  304. struct GenericId : public IdBase<GenericId> {
  305. static constexpr llvm::StringLiteral Label = "generic";
  306. using IdBase::IdBase;
  307. };
  308. // The ID of a `Specific`, which is the result of specifying the generic
  309. // arguments for a generic.
  310. struct SpecificId : public IdBase<SpecificId> {
  311. using DiagnosticType = Diagnostics::TypeInfo<std::string>;
  312. static constexpr llvm::StringLiteral Label = "specific";
  313. using IdBase::IdBase;
  314. };
  315. // The ID of a `SpecificInterface`, which is an interface and a specific pair.
  316. struct SpecificInterfaceId : public IdBase<SpecificInterfaceId> {
  317. using DiagnosticType = Diagnostics::TypeInfo<std::string>;
  318. static constexpr llvm::StringLiteral Label = "specific_interface";
  319. using IdBase::IdBase;
  320. };
  321. // The index of an instruction that depends on generic parameters within a
  322. // region of a generic. A corresponding specific version of the instruction can
  323. // be found in each specific corresponding to that generic. This is a pair of a
  324. // region and an index, stored in 32 bits.
  325. struct GenericInstIndex : public IndexBase<GenericInstIndex> {
  326. // Where the value is first used within the generic.
  327. enum Region : uint8_t {
  328. // In the declaration.
  329. Declaration,
  330. // In the definition.
  331. Definition,
  332. };
  333. // An index with no value.
  334. static const GenericInstIndex None;
  335. explicit constexpr GenericInstIndex(Region region, int32_t index)
  336. : IndexBase(region == Declaration ? index
  337. : FirstDefinitionIndex - index) {
  338. CARBON_CHECK(index >= 0);
  339. }
  340. // Returns the index of the instruction within the region.
  341. auto index() const -> int32_t {
  342. CARBON_CHECK(has_value());
  343. return IndexBase::index >= 0 ? IndexBase::index
  344. : FirstDefinitionIndex - IndexBase::index;
  345. }
  346. // Returns the region within which this instruction was first used.
  347. auto region() const -> Region {
  348. CARBON_CHECK(has_value());
  349. return IndexBase::index >= 0 ? Declaration : Definition;
  350. }
  351. auto Print(llvm::raw_ostream& out) const -> void;
  352. private:
  353. static constexpr auto MakeNone() -> GenericInstIndex {
  354. GenericInstIndex result(Declaration, 0);
  355. result.IndexBase::index = NoneIndex;
  356. return result;
  357. }
  358. static constexpr int32_t FirstDefinitionIndex = NoneIndex - 1;
  359. };
  360. inline constexpr GenericInstIndex GenericInstIndex::None =
  361. GenericInstIndex::MakeNone();
  362. // The ID of an `ImportIR` within the set of imported IRs, both direct and
  363. // indirect.
  364. struct ImportIRId : public IdBase<ImportIRId> {
  365. static constexpr llvm::StringLiteral Label = "import_ir";
  366. // The implicit `api` import, for an `impl` file. A null entry is added if
  367. // there is none, as in an `api`, in which case this ID should not show up in
  368. // instructions.
  369. static const ImportIRId ApiForImpl;
  370. // The `Cpp` import. A null entry is added if there is none, in which case
  371. // this ID should not show up in instructions.
  372. static const ImportIRId Cpp;
  373. using IdBase::IdBase;
  374. auto Print(llvm::raw_ostream& out) const -> void;
  375. };
  376. inline constexpr ImportIRId ImportIRId::ApiForImpl = ImportIRId(0);
  377. inline constexpr ImportIRId ImportIRId::Cpp = ImportIRId(ApiForImpl.index + 1);
  378. // The ID of a `ClangDecl`.
  379. //
  380. // These IDs are importantly distinct from the `inst_id` associated with each
  381. // declaration. These form a dense range of IDs that is used to reference the
  382. // AST node pointers without storing those pointers directly into SemIR and
  383. // needing space to hold a full pointer. We can't avoid having these IDs without
  384. // embedding pointers directly into the storage of SemIR as part of an
  385. // instruction.
  386. struct ClangDeclId : public IdBase<ClangDeclId> {
  387. static constexpr llvm::StringLiteral Label = "clang_decl_id";
  388. using IdBase::IdBase;
  389. };
  390. // A boolean value.
  391. struct BoolValue : public IdBase<BoolValue> {
  392. // Not used by `Print`, but for `IdKind`.
  393. static constexpr llvm::StringLiteral Label = "bool";
  394. static const BoolValue False;
  395. static const BoolValue True;
  396. // Returns the `BoolValue` corresponding to `b`.
  397. static constexpr auto From(bool b) -> BoolValue { return b ? True : False; }
  398. // Returns the `bool` corresponding to this `BoolValue`.
  399. constexpr auto ToBool() -> bool {
  400. CARBON_CHECK(*this == False || *this == True, "Invalid bool value {0}",
  401. index);
  402. return *this != False;
  403. }
  404. using IdBase::IdBase;
  405. auto Print(llvm::raw_ostream& out) const -> void;
  406. };
  407. inline constexpr BoolValue BoolValue::False = BoolValue(0);
  408. inline constexpr BoolValue BoolValue::True = BoolValue(1);
  409. // A character literal value as a unicode codepoint.
  410. struct CharId : public IdBase<CharId> {
  411. // Not used by `Print`, but for `IdKind`.
  412. static constexpr llvm::StringLiteral Label = "";
  413. using IdBase::IdBase;
  414. auto Print(llvm::raw_ostream& out) const -> void;
  415. };
  416. // An integer kind value -- either "signed" or "unsigned".
  417. //
  418. // This might eventually capture any other properties of an integer type that
  419. // affect its semantics, such as overflow behavior.
  420. struct IntKind : public IdBase<IntKind> {
  421. // Not used by `Print`, but for `IdKind`.
  422. static constexpr llvm::StringLiteral Label = "int_kind";
  423. static const IntKind Unsigned;
  424. static const IntKind Signed;
  425. using IdBase::IdBase;
  426. // Returns whether this type is signed.
  427. constexpr auto is_signed() -> bool { return *this == Signed; }
  428. auto Print(llvm::raw_ostream& out) const -> void;
  429. };
  430. inline constexpr IntKind IntKind::Unsigned = IntKind(0);
  431. inline constexpr IntKind IntKind::Signed = IntKind(1);
  432. // A float kind value. This describes the semantics of the floating-point type.
  433. // This represents very similar information to the bit-width, but is more
  434. // precise. In particular, there is in general more than one floating-point type
  435. // with a given bit-width, and while only one such type can be named with the
  436. // `fN` notation, the others should still be modeled as `FloatType`s.
  437. struct FloatKind : public IdBase<FloatKind> {
  438. // Not used by `Print`, but for `IdKind`.
  439. static constexpr llvm::StringLiteral Label = "float_kind";
  440. // An explicitly absent kind. Used when the kind has not been determined.
  441. static const FloatKind None;
  442. // Supported IEEE-754 interchange formats. These correspond to Carbon `fN`
  443. // type literal syntax.
  444. static const FloatKind Binary16;
  445. static const FloatKind Binary32;
  446. static const FloatKind Binary64;
  447. static const FloatKind Binary128;
  448. // Note, binary256 is not supported by LLVM and hence not by us.
  449. // Other formats supported by LLVM. Support for these may be
  450. // target-dependent.
  451. // TODO: Add a mechanism to use these types from Carbon code.
  452. static const FloatKind BFloat16;
  453. static const FloatKind X87Float80;
  454. static const FloatKind PPCFloat128;
  455. using IdBase::IdBase;
  456. auto Print(llvm::raw_ostream& out) const -> void;
  457. // Query the LLVM semantics model associated with this kind of floating-point
  458. // type. This kind must be concrete.
  459. auto Semantics() const -> const llvm::fltSemantics&;
  460. };
  461. inline constexpr FloatKind FloatKind::None = FloatKind(NoneIndex);
  462. inline constexpr FloatKind FloatKind::Binary16 = FloatKind(0);
  463. inline constexpr FloatKind FloatKind::Binary32 = FloatKind(1);
  464. inline constexpr FloatKind FloatKind::Binary64 = FloatKind(2);
  465. inline constexpr FloatKind FloatKind::Binary128 = FloatKind(3);
  466. inline constexpr FloatKind FloatKind::BFloat16 = FloatKind(4);
  467. inline constexpr FloatKind FloatKind::X87Float80 = FloatKind(5);
  468. inline constexpr FloatKind FloatKind::PPCFloat128 = FloatKind(6);
  469. // An X-macro for special names. Uses should look like:
  470. //
  471. // #define CARBON_SPECIAL_NAME_ID_FOR_XYZ(Name) ...
  472. // CARBON_SPECIAL_NAME_ID(CARBON_SPECIAL_NAME_ID_FOR_XYZ)
  473. // #undef CARBON_SPECIAL_NAME_ID_FOR_XYZ
  474. #define CARBON_SPECIAL_NAME_ID(X) \
  475. /* The name of `base`. */ \
  476. X(Base) \
  477. /* The name of the discriminant field (if any) in a choice. */ \
  478. X(ChoiceDiscriminant) \
  479. /* The name of the package `Core`. */ \
  480. X(Core) \
  481. /* The name of the package `Cpp`. */ \
  482. X(Cpp) \
  483. /* The name of imported C++ destructors. */ \
  484. X(CppDestructor) \
  485. /* The name of imported C++ operator functions */ \
  486. X(CppOperator) \
  487. /* The name of the default package `Main`. */ \
  488. X(MainPackage) \
  489. /* The name of `package`. */ \
  490. X(PackageKeyword) \
  491. /* The name of `.Self`. */ \
  492. X(PeriodSelf) \
  493. /* The name of the return slot in a function. */ \
  494. X(ReturnSlot) \
  495. /* The name of `Self`. */ \
  496. X(SelfType) \
  497. /* The name of `self`. */ \
  498. X(SelfValue) \
  499. /* The name of `_`. */ \
  500. X(Underscore) \
  501. /* The name of `vptr`. */ \
  502. X(Vptr)
  503. // The ID of a name. A name is either a string or a special name such as
  504. // `self`, `Self`, or `base`.
  505. struct NameId : public IdBase<NameId> {
  506. static constexpr llvm::StringLiteral Label = "name";
  507. // names().GetFormatted() is used for diagnostics.
  508. using DiagnosticType = Diagnostics::TypeInfo<std::string>;
  509. // An enum of special names.
  510. enum class SpecialNameId : uint8_t {
  511. #define CARBON_SPECIAL_NAME_ID_FOR_ENUM(Name) Name,
  512. CARBON_SPECIAL_NAME_ID(CARBON_SPECIAL_NAME_ID_FOR_ENUM)
  513. #undef CARBON_SPECIAL_NAME_ID_FOR_ENUM
  514. };
  515. // For each SpecialNameId, provide a matching `NameId` instance for
  516. // convenience.
  517. #define CARBON_SPECIAL_NAME_ID_FOR_DECL(Name) static const NameId Name;
  518. CARBON_SPECIAL_NAME_ID(CARBON_SPECIAL_NAME_ID_FOR_DECL)
  519. #undef CARBON_SPECIAL_NAME_ID_FOR_DECL
  520. // The number of non-index (<0) that exist, and will need storage in name
  521. // lookup.
  522. static const int NonIndexValueCount;
  523. // Returns the NameId corresponding to a particular IdentifierId.
  524. static auto ForIdentifier(IdentifierId id) -> NameId;
  525. // Returns the NameId corresponding to a particular PackageNameId. This is the
  526. // name that is declared when the package is imported.
  527. static auto ForPackageName(PackageNameId id) -> NameId;
  528. using IdBase::IdBase;
  529. // Returns the IdentifierId corresponding to this NameId, or `None` if this is
  530. // a special name.
  531. auto AsIdentifierId() const -> IdentifierId {
  532. return index >= 0 ? IdentifierId(index) : IdentifierId::None;
  533. }
  534. // Expose special names for `switch`.
  535. constexpr auto AsSpecialNameId() const -> std::optional<SpecialNameId> {
  536. if (index >= NoneIndex) {
  537. return std::nullopt;
  538. }
  539. return static_cast<SpecialNameId>(NoneIndex - 1 - index);
  540. }
  541. auto Print(llvm::raw_ostream& out) const -> void;
  542. };
  543. // Define the special `static const NameId` values.
  544. #define CARBON_SPECIAL_NAME_ID_FOR_DEF(Name) \
  545. inline constexpr NameId NameId::Name = \
  546. NameId(NoneIndex - 1 - static_cast<int>(NameId::SpecialNameId::Name));
  547. CARBON_SPECIAL_NAME_ID(CARBON_SPECIAL_NAME_ID_FOR_DEF)
  548. #undef CARBON_SPECIAL_NAME_ID_FOR_DEF
  549. // Count non-index values, including `None` and special names.
  550. #define CARBON_SPECIAL_NAME_ID_FOR_COUNT(...) +1
  551. inline constexpr int NameId::NonIndexValueCount =
  552. 1 CARBON_SPECIAL_NAME_ID(CARBON_SPECIAL_NAME_ID_FOR_COUNT);
  553. #undef CARBON_SPECIAL_NAME_ID_FOR_COUNT
  554. // The ID of a `NameScope`.
  555. struct NameScopeId : public IdBase<NameScopeId> {
  556. static constexpr llvm::StringLiteral Label = "name_scope";
  557. // The package (or file) name scope, guaranteed to be the first added.
  558. static const NameScopeId Package;
  559. using IdBase::IdBase;
  560. };
  561. inline constexpr NameScopeId NameScopeId::Package = NameScopeId(0);
  562. // The ID of an `InstId` block.
  563. struct InstBlockId : public IdBase<InstBlockId> {
  564. static constexpr llvm::StringLiteral Label = "inst_block";
  565. // The canonical empty block, reused to avoid allocating empty vectors. Always
  566. // the 0-index block.
  567. static const InstBlockId Empty;
  568. // Exported instructions. Empty until the File is fully checked; intermediate
  569. // state is in the Check::Context.
  570. static const InstBlockId Exports;
  571. // Instructions produced through import logic. Empty until the File is fully
  572. // checked; intermediate state is in the Check::Context.
  573. static const InstBlockId Imports;
  574. // Global declaration initialization instructions. Empty if none are present.
  575. // Otherwise, __global_init function will be generated and this block will
  576. // be inserted into it.
  577. static const InstBlockId GlobalInit;
  578. // An ID for unreachable code.
  579. static const InstBlockId Unreachable;
  580. using IdBase::IdBase;
  581. auto Print(llvm::raw_ostream& out) const -> void;
  582. };
  583. inline constexpr InstBlockId InstBlockId::Empty = InstBlockId(0);
  584. inline constexpr InstBlockId InstBlockId::Exports = InstBlockId(1);
  585. inline constexpr InstBlockId InstBlockId::Imports = InstBlockId(2);
  586. inline constexpr InstBlockId InstBlockId::GlobalInit = InstBlockId(3);
  587. inline constexpr InstBlockId InstBlockId::Unreachable =
  588. InstBlockId(NoneIndex - 1);
  589. // Contains either an `InstBlockId` value, an error value, or
  590. // `InstBlockId::None`.
  591. //
  592. // Error values are treated as values, though they are not representable as an
  593. // `InstBlockId` (unlike for the singleton error `InstId`).
  594. class InstBlockIdOrError {
  595. public:
  596. explicit(false) InstBlockIdOrError(InstBlockId inst_block_id)
  597. : InstBlockIdOrError(inst_block_id, false) {}
  598. static auto MakeError() -> InstBlockIdOrError {
  599. return {InstBlockId::None, true};
  600. }
  601. // Returns whether this class contains either an InstBlockId (other than
  602. // `None`) or an error.
  603. //
  604. // An error is treated as a value (as same for the singleton error `InstId`),
  605. // but it can not actually be materialized as an error value outside of this
  606. // class.
  607. auto has_value() const -> bool {
  608. return has_error_value() || inst_block_id_.has_value();
  609. }
  610. // Returns whether this class contains an error value.
  611. auto has_error_value() const -> bool { return error_; }
  612. // Returns the id of a non-empty inst block, or `None` if `has_value()` is
  613. // false.
  614. //
  615. // Only valid to call if `has_error_value()` is false.
  616. auto inst_block_id() const -> InstBlockId {
  617. CARBON_CHECK(!has_error_value());
  618. return inst_block_id_;
  619. }
  620. private:
  621. InstBlockIdOrError(InstBlockId inst_block_id, bool error)
  622. : inst_block_id_(inst_block_id), error_(error) {}
  623. InstBlockId inst_block_id_;
  624. bool error_;
  625. };
  626. // An ID of an instruction block that is referenced absolutely by an
  627. // instruction. This should only be used as the type of a field within a typed
  628. // instruction class. See AbsoluteInstId.
  629. class AbsoluteInstBlockId : public InstBlockId {
  630. public:
  631. // Support implicit conversion from InstBlockId so that InstBlockId and
  632. // AbsoluteInstBlockId have the same interface.
  633. explicit(false) constexpr AbsoluteInstBlockId(InstBlockId inst_block_id)
  634. : InstBlockId(inst_block_id) {}
  635. using InstBlockId::InstBlockId;
  636. };
  637. // An ID of an instruction block that is used as the declaration block within a
  638. // declaration instruction. This is a block that is nested within the
  639. // instruction, but doesn't contribute to its value. Such blocks are not
  640. // included in the fingerprint of the declaration. This should only be used as
  641. // the type of a field within a typed instruction class.
  642. class DeclInstBlockId : public InstBlockId {
  643. public:
  644. // Support implicit conversion from InstBlockId so that InstBlockId and
  645. // DeclInstBlockId have the same interface.
  646. explicit(false) constexpr DeclInstBlockId(InstBlockId inst_block_id)
  647. : InstBlockId(inst_block_id) {}
  648. using InstBlockId::InstBlockId;
  649. };
  650. // An ID of an instruction block that is used as a label in a branch instruction
  651. // or similar. This is a block that is not nested within the instruction, but
  652. // instead exists elsewhere in the enclosing executable region. This should
  653. // only be used as the type of a field within a typed instruction class.
  654. class LabelId : public InstBlockId {
  655. public:
  656. // Support implicit conversion from InstBlockId so that InstBlockId and
  657. // LabelId have the same interface.
  658. explicit(false) constexpr LabelId(InstBlockId inst_block_id)
  659. : InstBlockId(inst_block_id) {}
  660. using InstBlockId::InstBlockId;
  661. };
  662. // The ID of an `ExprRegion`.
  663. // TODO: Move this out of sem_ir and into check, if we don't wind up using it
  664. // in the SemIR for expression patterns.
  665. struct ExprRegionId : public IdBase<ExprRegionId> {
  666. static constexpr llvm::StringLiteral Label = "region";
  667. using IdBase::IdBase;
  668. };
  669. // The ID of a `StructTypeField` block.
  670. struct StructTypeFieldsId : public IdBase<StructTypeFieldsId> {
  671. static constexpr llvm::StringLiteral Label = "struct_type_fields";
  672. // The canonical empty block, reused to avoid allocating empty vectors. Always
  673. // the 0-index block.
  674. static const StructTypeFieldsId Empty;
  675. using IdBase::IdBase;
  676. auto Print(llvm::raw_ostream& out) const -> void;
  677. };
  678. inline constexpr StructTypeFieldsId StructTypeFieldsId::Empty =
  679. StructTypeFieldsId(0);
  680. // The ID of a `CustomLayout` block.
  681. struct CustomLayoutId : public IdBase<CustomLayoutId> {
  682. static constexpr llvm::StringLiteral Label = "custom_layout";
  683. // The canonical empty block. This is never used, but needed by
  684. // BlockValueStore.
  685. static const CustomLayoutId Empty;
  686. // The index in a custom layout of the overall size field.
  687. static constexpr int SizeIndex = 0;
  688. // The index in a custom layout of the overall alignment field.
  689. static constexpr int AlignIndex = 1;
  690. // The index in a custom layout of the offset of the first struct field.
  691. static constexpr int FirstFieldIndex = 2;
  692. using IdBase::IdBase;
  693. auto Print(llvm::raw_ostream& out) const -> void;
  694. };
  695. inline constexpr CustomLayoutId CustomLayoutId::Empty = CustomLayoutId(0);
  696. // The ID of a type.
  697. struct TypeId : public IdBase<TypeId> {
  698. static constexpr llvm::StringLiteral Label = "type";
  699. // `StringifyConstantInst` is used for diagnostics. However, where possible,
  700. // an `InstId` describing how the type was written should be preferred, using
  701. // `InstIdAsType` or `TypeOfInstId` as the diagnostic argument type.
  702. using DiagnosticType = Diagnostics::TypeInfo<std::string>;
  703. using IdBase::IdBase;
  704. // Returns the ID of the type corresponding to the constant `const_id`, which
  705. // must be of type `type`. As an exception, the type `Error` is of type
  706. // `Error`.
  707. static constexpr auto ForTypeConstant(ConstantId const_id) -> TypeId {
  708. return TypeId(const_id.index);
  709. }
  710. // Returns the constant ID that defines the type.
  711. auto AsConstantId() const -> ConstantId { return ConstantId(index); }
  712. // Returns whether this represents a symbolic type. Requires has_value.
  713. auto is_symbolic() const -> bool { return AsConstantId().is_symbolic(); }
  714. // Returns whether this represents a concrete type. Requires has_value.
  715. auto is_concrete() const -> bool { return AsConstantId().is_concrete(); }
  716. auto Print(llvm::raw_ostream& out) const -> void;
  717. };
  718. // The ID of a `clang::SourceLocation`.
  719. struct ClangSourceLocId : public IdBase<ClangSourceLocId> {
  720. static constexpr llvm::StringLiteral Label = "clang_source_loc";
  721. using IdBase::IdBase;
  722. };
  723. // An index for element access, for structs, tuples, and classes.
  724. struct ElementIndex : public IndexBase<ElementIndex> {
  725. static constexpr llvm::StringLiteral Label = "element";
  726. using IndexBase::IndexBase;
  727. };
  728. // The ID of a library name. This is either a string literal or `default`.
  729. struct LibraryNameId : public IdBase<LibraryNameId> {
  730. static constexpr llvm::StringLiteral Label = "library_name";
  731. using DiagnosticType = Diagnostics::TypeInfo<std::string>;
  732. // The name of `default`.
  733. static const LibraryNameId Default;
  734. // Track cases where the library name was set, but has been diagnosed and
  735. // shouldn't be used anymore.
  736. static const LibraryNameId Error;
  737. // Returns the LibraryNameId for a library name as a string literal.
  738. static auto ForStringLiteralValueId(StringLiteralValueId id) -> LibraryNameId;
  739. using IdBase::IdBase;
  740. // Converts a LibraryNameId back to a string literal.
  741. auto AsStringLiteralValueId() const -> StringLiteralValueId {
  742. CARBON_CHECK(index >= NoneIndex, "{0} must be handled directly", *this);
  743. return StringLiteralValueId(index);
  744. }
  745. auto Print(llvm::raw_ostream& out) const -> void;
  746. };
  747. inline constexpr LibraryNameId LibraryNameId::Default =
  748. LibraryNameId(NoneIndex - 1);
  749. inline constexpr LibraryNameId LibraryNameId::Error =
  750. LibraryNameId(NoneIndex - 2);
  751. // The ID of an `ImportIRInst`.
  752. struct ImportIRInstId : public IdBase<ImportIRInstId> {
  753. static constexpr llvm::StringLiteral Label = "import_ir_inst";
  754. // The maximum ID, non-inclusive. This is constrained to fit inside LocId.
  755. static constexpr int Max =
  756. -(std::numeric_limits<int32_t>::min() + 2 * Parse::NodeId::Max + 1);
  757. constexpr explicit ImportIRInstId(int32_t index) : IdBase(index) {
  758. CARBON_DCHECK(index < Max, "Index out of range: {0}", index);
  759. }
  760. };
  761. // The ID of a `RequireImpls`.
  762. struct RequireImplsId : public IdBase<RequireImplsId> {
  763. static constexpr llvm::StringLiteral Label = "require";
  764. using IdBase::IdBase;
  765. };
  766. // The ID of a `RequireImplsId` block.
  767. struct RequireImplsBlockId : public IdBase<RequireImplsBlockId> {
  768. static constexpr llvm::StringLiteral Label = "require_block";
  769. // The canonical empty block, reused to avoid allocating empty vectors. Always
  770. // the 0-index block.
  771. static const RequireImplsBlockId Empty;
  772. using IdBase::IdBase;
  773. auto Print(llvm::raw_ostream& out) const -> void;
  774. };
  775. inline constexpr RequireImplsBlockId RequireImplsBlockId::Empty =
  776. RequireImplsBlockId(0);
  777. // A SemIR location used as the location of instructions. This contains either a
  778. // InstId, NodeId, ImportIRInstId, or None. The intent is that any of these can
  779. // indicate the source of an instruction, and also be used to associate a line
  780. // in diagnostics.
  781. //
  782. // The structure is:
  783. // - None: The standard NoneIndex for all Id types, -1.
  784. // - InstId: Positive values including zero; a full 31 bits.
  785. // - [0, 1 << 31)
  786. // - NodeId: Negative values starting after None; the 24 bit NodeId range.
  787. // - [-2, -2 - (1 << 24))
  788. // - Desugared NodeId: Another 24 bit NodeId range.
  789. // - [-2 - (1 << 24), -2 - (1 << 25))
  790. // - ImportIRInstId: Remaining negative values; after NodeId, fills out negative
  791. // values.
  792. // - [-2 - (1 << 25), -(1 << 31)]
  793. //
  794. // For desugaring, use `InstStore::GetLocIdForDesugaring()`.
  795. struct LocId : public IdBase<LocId> {
  796. // The contained index kind.
  797. enum class Kind {
  798. None,
  799. ImportIRInstId,
  800. InstId,
  801. NodeId,
  802. };
  803. static constexpr llvm::StringLiteral Label = "loc";
  804. using IdBase::IdBase;
  805. explicit(false) constexpr LocId(ImportIRInstId import_ir_inst_id)
  806. : IdBase(import_ir_inst_id.has_value()
  807. ? FirstImportIRInstId - import_ir_inst_id.index
  808. : NoneIndex) {}
  809. explicit constexpr LocId(InstId inst_id) : IdBase(inst_id.index) {}
  810. explicit(false) constexpr LocId(Parse::NoneNodeId /*none*/)
  811. : IdBase(NoneIndex) {}
  812. explicit(false) constexpr LocId(Parse::NodeId node_id)
  813. : IdBase(FirstNodeId - node_id.index) {}
  814. // Forms an equivalent LocId for a desugared location. Prefer calling
  815. // `InstStore::GetLocIdForDesugaring`.
  816. auto AsDesugared() const -> LocId {
  817. // This should only be called for NodeId or ImportIRInstId (i.e. canonical
  818. // locations), but we only set the flag for NodeId.
  819. CARBON_CHECK(kind() != Kind::InstId, "Use InstStore::GetDesugaredLocId");
  820. if (index <= FirstNodeId && index > FirstDesugaredNodeId) {
  821. return LocId(index - Parse::NodeId::Max);
  822. }
  823. return *this;
  824. }
  825. // Returns the kind of the `LocId`.
  826. auto kind() const -> Kind {
  827. if (!has_value()) {
  828. return Kind::None;
  829. }
  830. if (index >= 0) {
  831. return Kind::InstId;
  832. }
  833. if (index <= FirstImportIRInstId) {
  834. return Kind::ImportIRInstId;
  835. }
  836. return Kind::NodeId;
  837. }
  838. // Returns true if the location corresponds to desugared instructions.
  839. // Requires a non-`InstId` location.
  840. auto is_desugared() const -> bool {
  841. return index <= FirstDesugaredNodeId && index > FirstImportIRInstId;
  842. }
  843. // Returns the equivalent `ImportIRInstId` when `kind()` matches or is `None`.
  844. // Note that the returned `ImportIRInstId` only identifies a location; it is
  845. // not correct to interpret it as the instruction from which another
  846. // instruction was imported. Use `InstStore::GetImportSource` for that.
  847. auto import_ir_inst_id() const -> ImportIRInstId {
  848. if (!has_value()) {
  849. return ImportIRInstId::None;
  850. }
  851. CARBON_CHECK(kind() == Kind::ImportIRInstId, "{0}", index);
  852. return ImportIRInstId(FirstImportIRInstId - index);
  853. }
  854. // Returns the equivalent `InstId` when `kind()` matches or is `None`.
  855. auto inst_id() const -> InstId {
  856. CARBON_CHECK(kind() == Kind::None || kind() == Kind::InstId, "{0}", index);
  857. return InstId(index);
  858. }
  859. // Returns the equivalent `NodeId` when `kind()` matches or is `None`.
  860. auto node_id() const -> Parse::NodeId {
  861. if (!has_value()) {
  862. return Parse::NodeId::None;
  863. }
  864. CARBON_CHECK(kind() == Kind::NodeId, "{0}", index);
  865. if (index <= FirstDesugaredNodeId) {
  866. return Parse::NodeId(FirstDesugaredNodeId - index);
  867. } else {
  868. return Parse::NodeId(FirstNodeId - index);
  869. }
  870. }
  871. auto Print(llvm::raw_ostream& out) const -> void;
  872. private:
  873. // The value of the 0 index for each of `NodeId` and `ImportIRInstId`.
  874. static constexpr int32_t FirstNodeId = NoneIndex - 1;
  875. static constexpr int32_t FirstDesugaredNodeId =
  876. FirstNodeId - Parse::NodeId::Max;
  877. static constexpr int32_t FirstImportIRInstId =
  878. FirstDesugaredNodeId - Parse::NodeId::Max;
  879. };
  880. // Polymorphic id for fields in `Any[...]` typed instruction category. Used for
  881. // fields where the specific instruction structs have different field types in
  882. // that position or do not have a field in that position at all. Allows
  883. // conversion with `Inst::As<>` from the specific typed instruction to the
  884. // `Any[...]` instruction category.
  885. //
  886. // This type participates in `Inst::FromRaw` in order to convert from specific
  887. // instructions to an `Any[...]` instruction category:
  888. // - In the case the specific instruction has a field of some `IdKind` in the
  889. // same position, the `Any[...]` type will hold its raw value in the
  890. // `AnyRawId` field.
  891. // - In the case the specific instruction has no field in the same position, the
  892. // `Any[...]` type will hold a default constructed `AnyRawId` with a `None`
  893. // value.
  894. struct AnyRawId : public AnyIdBase {
  895. // For IdKind.
  896. static constexpr llvm::StringLiteral Label = "any_raw";
  897. constexpr explicit AnyRawId() : AnyIdBase(AnyIdBase::NoneIndex) {}
  898. constexpr explicit AnyRawId(int32_t id) : AnyIdBase(id) {}
  899. };
  900. } // namespace Carbon::SemIR
  901. #endif // CARBON_TOOLCHAIN_SEM_IR_IDS_H_