ids.h 34 KB

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