ids.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  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 "common/check.h"
  7. #include "common/ostream.h"
  8. #include "toolchain/base/index_base.h"
  9. #include "toolchain/base/value_store.h"
  10. #include "toolchain/diagnostics/diagnostic_emitter.h"
  11. #include "toolchain/parse/node_ids.h"
  12. #include "toolchain/sem_ir/builtin_inst_kind.h"
  13. namespace Carbon::SemIR {
  14. // Forward declare indexed types, for integration with ValueStore.
  15. class File;
  16. class Inst;
  17. struct EntityName;
  18. struct Class;
  19. struct Function;
  20. struct Generic;
  21. struct Specific;
  22. struct ImportIR;
  23. struct ImportIRInst;
  24. struct Interface;
  25. struct Impl;
  26. struct NameScope;
  27. struct TypeInfo;
  28. // The ID of an instruction.
  29. struct InstId : public IdBase, public Printable<InstId> {
  30. using ValueType = Inst;
  31. // An explicitly invalid ID.
  32. static const InstId Invalid;
  33. // BuiltinInst IDs.
  34. #define CARBON_SEM_IR_BUILTIN_INST_KIND_NAME(Name) \
  35. static const InstId Builtin##Name;
  36. #include "toolchain/sem_ir/builtin_inst_kind.def"
  37. // The namespace for a `package` expression.
  38. static const InstId PackageNamespace;
  39. // Returns the instruction ID for a builtin. This relies on File guarantees
  40. // for builtin placement.
  41. static constexpr auto ForBuiltin(BuiltinInstKind kind) -> InstId {
  42. return InstId(kind.AsInt());
  43. }
  44. using IdBase::IdBase;
  45. // Returns true if the instruction is a builtin. Requires is_valid.
  46. auto is_builtin() const -> bool {
  47. CARBON_CHECK(is_valid());
  48. return index < BuiltinInstKind::ValidCount;
  49. }
  50. // Returns the BuiltinInstKind. Requires is_builtin.
  51. auto builtin_inst_kind() const -> BuiltinInstKind {
  52. CARBON_CHECK(is_builtin());
  53. return BuiltinInstKind::FromInt(index);
  54. }
  55. auto Print(llvm::raw_ostream& out) const -> void {
  56. out << "inst";
  57. if (!is_valid()) {
  58. IdBase::Print(out);
  59. } else if (is_builtin()) {
  60. out << builtin_inst_kind();
  61. } else {
  62. // Use the `+` as a small reminder that this is a delta, rather than an
  63. // absolute index.
  64. out << "+" << index - BuiltinInstKind::ValidCount;
  65. }
  66. }
  67. };
  68. constexpr InstId InstId::Invalid = InstId(InvalidIndex);
  69. #define CARBON_SEM_IR_BUILTIN_INST_KIND_NAME(Name) \
  70. constexpr InstId InstId::Builtin##Name = \
  71. InstId::ForBuiltin(BuiltinInstKind::Name);
  72. #include "toolchain/sem_ir/builtin_inst_kind.def"
  73. // The package namespace will be the instruction after builtins.
  74. constexpr InstId InstId::PackageNamespace = InstId(BuiltinInstKind::ValidCount);
  75. // The ID of a constant value of an expression. An expression is either:
  76. //
  77. // - a template constant, with an immediate value, such as `42` or `i32*` or
  78. // `("hello", "world")`, or
  79. // - a symbolic constant, whose value includes a symbolic parameter, such as
  80. // `Vector(T*)`, or
  81. // - a runtime expression, such as `Print("hello")`.
  82. //
  83. // Template constants are a thin wrapper around the instruction ID of the
  84. // constant instruction that defines the constant. Symbolic constants are an
  85. // index into a separate table of `SymbolicConstant`s maintained by the constant
  86. // value store.
  87. struct ConstantId : public IdBase, public Printable<ConstantId> {
  88. // An ID for an expression that is not constant.
  89. static const ConstantId NotConstant;
  90. // An ID for an expression whose phase cannot be determined because it
  91. // contains an error. This is always modeled as a template constant.
  92. static const ConstantId Error;
  93. // An explicitly invalid ID.
  94. static const ConstantId Invalid;
  95. // Returns the constant ID corresponding to a template constant, which should
  96. // either be in the `constants` block in the file or should be known to be
  97. // unique.
  98. static constexpr auto ForTemplateConstant(InstId const_id) -> ConstantId {
  99. return ConstantId(const_id.index);
  100. }
  101. // Returns the constant ID corresponding to a symbolic constant index.
  102. static constexpr auto ForSymbolicConstantIndex(int32_t symbolic_index)
  103. -> ConstantId {
  104. return ConstantId(FirstSymbolicIndex - symbolic_index);
  105. }
  106. using IdBase::IdBase;
  107. // Returns whether this represents a constant. Requires is_valid.
  108. auto is_constant() const -> bool {
  109. CARBON_DCHECK(is_valid());
  110. return *this != ConstantId::NotConstant;
  111. }
  112. // Returns whether this represents a symbolic constant. Requires is_valid.
  113. auto is_symbolic() const -> bool {
  114. CARBON_DCHECK(is_valid());
  115. return index <= FirstSymbolicIndex;
  116. }
  117. // Returns whether this represents a template constant. Requires is_valid.
  118. auto is_template() const -> bool {
  119. CARBON_DCHECK(is_valid());
  120. return index >= 0;
  121. }
  122. // Prints this ID to the given output stream. `disambiguate` indicates whether
  123. // template constants should be wrapped with "templateConstant(...)" so that
  124. // they aren't printed the same as an InstId. This can be set to false if
  125. // there is no risk of ambiguity.
  126. auto Print(llvm::raw_ostream& out, bool disambiguate = true) const -> void {
  127. if (!is_valid()) {
  128. IdBase::Print(out);
  129. } else if (is_template()) {
  130. if (disambiguate) {
  131. out << "templateConstant(";
  132. }
  133. out << template_inst_id();
  134. if (disambiguate) {
  135. out << ")";
  136. }
  137. } else if (is_symbolic()) {
  138. out << "symbolicConstant" << symbolic_index();
  139. } else {
  140. out << "runtime";
  141. }
  142. }
  143. private:
  144. friend class ConstantValueStore;
  145. // TODO: C++23 makes std::abs constexpr, but until then we mirror std::abs
  146. // logic here. LLVM should still optimize this.
  147. static constexpr auto Abs(int32_t i) -> int32_t { return i > 0 ? i : -i; }
  148. // Returns the instruction that describes this template constant value.
  149. // Requires `is_template()`. Use `ConstantValueStore::GetInstId` to get the
  150. // instruction ID of a `ConstantId`.
  151. constexpr auto template_inst_id() const -> InstId {
  152. CARBON_DCHECK(is_template());
  153. return InstId(index);
  154. }
  155. // Returns the symbolic constant index that describes this symbolic constant
  156. // value. Requires `is_symbolic()`.
  157. constexpr auto symbolic_index() const -> int32_t {
  158. CARBON_DCHECK(is_symbolic());
  159. return FirstSymbolicIndex - index;
  160. }
  161. static constexpr int32_t NotConstantIndex = InvalidIndex - 1;
  162. static constexpr int32_t FirstSymbolicIndex = InvalidIndex - 2;
  163. };
  164. constexpr ConstantId ConstantId::NotConstant = ConstantId(NotConstantIndex);
  165. constexpr ConstantId ConstantId::Error =
  166. ConstantId::ForTemplateConstant(InstId::BuiltinError);
  167. constexpr ConstantId ConstantId::Invalid = ConstantId(InvalidIndex);
  168. // The ID of a EntityName.
  169. struct EntityNameId : public IdBase, public Printable<EntityNameId> {
  170. using ValueType = EntityName;
  171. // An explicitly invalid ID.
  172. static const EntityNameId Invalid;
  173. using IdBase::IdBase;
  174. auto Print(llvm::raw_ostream& out) const -> void {
  175. out << "entity_name";
  176. IdBase::Print(out);
  177. }
  178. };
  179. constexpr EntityNameId EntityNameId::Invalid = EntityNameId(InvalidIndex);
  180. // The index of a compile-time binding. This is the de Bruijn level for the
  181. // binding -- that is, this is the number of other compile time bindings whose
  182. // scope encloses this binding.
  183. struct CompileTimeBindIndex : public IndexBase,
  184. public Printable<CompileTimeBindIndex> {
  185. // An explicitly invalid index.
  186. static const CompileTimeBindIndex Invalid;
  187. using IndexBase::IndexBase;
  188. auto Print(llvm::raw_ostream& out) const -> void {
  189. out << "comp_time_bind";
  190. IndexBase::Print(out);
  191. }
  192. };
  193. constexpr CompileTimeBindIndex CompileTimeBindIndex::Invalid =
  194. CompileTimeBindIndex(InvalidIndex);
  195. // The ID of a function.
  196. struct FunctionId : public IdBase, public Printable<FunctionId> {
  197. using ValueType = Function;
  198. // An explicitly invalid ID.
  199. static const FunctionId Invalid;
  200. using IdBase::IdBase;
  201. auto Print(llvm::raw_ostream& out) const -> void {
  202. out << "function";
  203. IdBase::Print(out);
  204. }
  205. };
  206. constexpr FunctionId FunctionId::Invalid = FunctionId(InvalidIndex);
  207. // The ID of an IR within the set of all IRs being evaluated in the current
  208. // check execution.
  209. struct CheckIRId : public IdBase, public Printable<CheckIRId> {
  210. using IdBase::IdBase;
  211. auto Print(llvm::raw_ostream& out) const -> void {
  212. out << "check_ir";
  213. IdBase::Print(out);
  214. }
  215. };
  216. // The ID of a class.
  217. struct ClassId : public IdBase, public Printable<ClassId> {
  218. using ValueType = Class;
  219. // An explicitly invalid ID.
  220. static const ClassId Invalid;
  221. using IdBase::IdBase;
  222. auto Print(llvm::raw_ostream& out) const -> void {
  223. out << "class";
  224. IdBase::Print(out);
  225. }
  226. };
  227. constexpr ClassId ClassId::Invalid = ClassId(InvalidIndex);
  228. // The ID of an interface.
  229. struct InterfaceId : public IdBase, public Printable<InterfaceId> {
  230. using ValueType = Interface;
  231. // An explicitly invalid ID.
  232. static const InterfaceId Invalid;
  233. using IdBase::IdBase;
  234. auto Print(llvm::raw_ostream& out) const -> void {
  235. out << "interface";
  236. IdBase::Print(out);
  237. }
  238. };
  239. constexpr InterfaceId InterfaceId::Invalid = InterfaceId(InvalidIndex);
  240. // The ID of an impl.
  241. struct ImplId : public IdBase, public Printable<ImplId> {
  242. using ValueType = Impl;
  243. // An explicitly invalid ID.
  244. static const ImplId Invalid;
  245. using IdBase::IdBase;
  246. auto Print(llvm::raw_ostream& out) const -> void {
  247. out << "impl";
  248. IdBase::Print(out);
  249. }
  250. };
  251. constexpr ImplId ImplId::Invalid = ImplId(InvalidIndex);
  252. // The ID of a generic.
  253. struct GenericId : public IdBase, public Printable<GenericId> {
  254. using ValueType = Generic;
  255. // An explicitly invalid ID.
  256. static const GenericId Invalid;
  257. using IdBase::IdBase;
  258. auto Print(llvm::raw_ostream& out) const -> void {
  259. out << "generic";
  260. IdBase::Print(out);
  261. }
  262. };
  263. constexpr GenericId GenericId::Invalid = GenericId(InvalidIndex);
  264. // The ID of a specific, which is the result of specifying the generic arguments
  265. // for a generic.
  266. struct SpecificId : public IdBase, public Printable<SpecificId> {
  267. using ValueType = Specific;
  268. // An explicitly invalid ID. This is typically used to represent a non-generic
  269. // entity.
  270. static const SpecificId Invalid;
  271. using IdBase::IdBase;
  272. auto Print(llvm::raw_ostream& out) const -> void {
  273. out << "specific";
  274. IdBase::Print(out);
  275. }
  276. };
  277. constexpr SpecificId SpecificId::Invalid = SpecificId(InvalidIndex);
  278. // The index of an instruction that depends on generic parameters within a
  279. // region of a generic. A corresponding specific version of the instruction can
  280. // be found in each specific corresponding to that generic. This is a pair of a
  281. // region and an index, stored in 32 bits.
  282. struct GenericInstIndex : public IndexBase, public Printable<GenericInstIndex> {
  283. // Where the value is first used within the generic.
  284. enum Region : uint8_t {
  285. // In the declaration.
  286. Declaration,
  287. // In the definition.
  288. Definition,
  289. };
  290. // An explicitly invalid index.
  291. static const GenericInstIndex Invalid;
  292. explicit constexpr GenericInstIndex(Region region, int32_t index)
  293. : IndexBase(region == Declaration ? index
  294. : FirstDefinitionIndex - index) {
  295. CARBON_CHECK(index >= 0);
  296. }
  297. // Returns the index of the instruction within the region.
  298. auto index() const -> int32_t {
  299. CARBON_CHECK(is_valid());
  300. return IndexBase::index >= 0 ? IndexBase::index
  301. : FirstDefinitionIndex - IndexBase::index;
  302. }
  303. // Returns the region within which this instruction was first used.
  304. auto region() const -> Region {
  305. CARBON_CHECK(is_valid());
  306. return IndexBase::index >= 0 ? Declaration : Definition;
  307. }
  308. auto Print(llvm::raw_ostream& out) const -> void {
  309. out << "genericInst";
  310. if (is_valid()) {
  311. out << (region() == Declaration ? "InDecl" : "InDef") << index();
  312. } else {
  313. out << "<invalid>";
  314. }
  315. }
  316. private:
  317. static constexpr auto MakeInvalid() -> GenericInstIndex {
  318. GenericInstIndex result(Declaration, 0);
  319. result.IndexBase::index = InvalidIndex;
  320. return result;
  321. }
  322. static constexpr int32_t FirstDefinitionIndex = InvalidIndex - 1;
  323. };
  324. constexpr GenericInstIndex GenericInstIndex::Invalid =
  325. GenericInstIndex::MakeInvalid();
  326. // The ID of an IR within the set of imported IRs, both direct and indirect.
  327. struct ImportIRId : public IdBase, public Printable<ImportIRId> {
  328. using ValueType = ImportIR;
  329. // An explicitly invalid ID.
  330. static const ImportIRId Invalid;
  331. // The implicit `api` import, for an `impl` file. A null entry is added if
  332. // there is none, as in an `api`, in which case this ID should not show up in
  333. // instructions.
  334. static const ImportIRId ApiForImpl;
  335. using IdBase::IdBase;
  336. auto Print(llvm::raw_ostream& out) const -> void {
  337. out << "ir";
  338. IdBase::Print(out);
  339. }
  340. };
  341. constexpr ImportIRId ImportIRId::Invalid = ImportIRId(InvalidIndex);
  342. constexpr ImportIRId ImportIRId::ApiForImpl = ImportIRId(0);
  343. // A boolean value.
  344. struct BoolValue : public IdBase, public Printable<BoolValue> {
  345. static const BoolValue False;
  346. static const BoolValue True;
  347. // Returns the `BoolValue` corresponding to `b`.
  348. static constexpr auto From(bool b) -> BoolValue { return b ? True : False; }
  349. // Returns the `bool` corresponding to this `BoolValue`.
  350. constexpr auto ToBool() -> bool {
  351. CARBON_CHECK(*this == False || *this == True, "Invalid bool value {0}",
  352. index);
  353. return *this != False;
  354. }
  355. using IdBase::IdBase;
  356. auto Print(llvm::raw_ostream& out) const -> void {
  357. if (*this == False) {
  358. out << "false";
  359. } else if (*this == True) {
  360. out << "true";
  361. } else {
  362. CARBON_FATAL("Invalid bool value {0}", index);
  363. }
  364. }
  365. };
  366. constexpr BoolValue BoolValue::False = BoolValue(0);
  367. constexpr BoolValue BoolValue::True = BoolValue(1);
  368. // An integer kind value -- either "signed" or "unsigned".
  369. //
  370. // This might eventually capture any other properties of an integer type that
  371. // affect its semantics, such as overflow behavior.
  372. struct IntKind : public IdBase, public Printable<IntKind> {
  373. static const IntKind Unsigned;
  374. static const IntKind Signed;
  375. using IdBase::IdBase;
  376. // Returns whether this type is signed.
  377. constexpr auto is_signed() -> bool { return *this == Signed; }
  378. auto Print(llvm::raw_ostream& out) const -> void {
  379. if (*this == Unsigned) {
  380. out << "unsigned";
  381. } else if (*this == Signed) {
  382. out << "signed";
  383. } else {
  384. CARBON_FATAL("Invalid int kind value {0}", index);
  385. }
  386. }
  387. };
  388. constexpr IntKind IntKind::Unsigned = IntKind(0);
  389. constexpr IntKind IntKind::Signed = IntKind(1);
  390. // A float kind value
  391. struct FloatKind : public IdBase, public Printable<FloatKind> {
  392. using IdBase::IdBase;
  393. auto Print(llvm::raw_ostream& out) const -> void { out << "float"; }
  394. };
  395. // The ID of a name. A name is either a string or a special name such as
  396. // `self`, `Self`, or `base`.
  397. struct NameId : public IdBase, public Printable<NameId> {
  398. // names().GetFormatted() is used for diagnostics.
  399. using DiagnosticType = DiagnosticTypeInfo<std::string>;
  400. // An explicitly invalid ID.
  401. static const NameId Invalid;
  402. // The name of `self`.
  403. static const NameId SelfValue;
  404. // The name of `Self`.
  405. static const NameId SelfType;
  406. // The name of the return slot in a function.
  407. static const NameId ReturnSlot;
  408. // The name of `package`.
  409. static const NameId PackageNamespace;
  410. // The name of `base`.
  411. static const NameId Base;
  412. // The number of non-index (<0) that exist, and will need storage in name
  413. // lookup.
  414. static const int NonIndexValueCount;
  415. // Returns the NameId corresponding to a particular IdentifierId.
  416. static auto ForIdentifier(IdentifierId id) -> NameId {
  417. if (id.index >= 0) {
  418. return NameId(id.index);
  419. } else if (!id.is_valid()) {
  420. return NameId::Invalid;
  421. } else {
  422. CARBON_FATAL("Unexpected identifier ID {0}", id);
  423. }
  424. }
  425. using IdBase::IdBase;
  426. // Returns the IdentifierId corresponding to this NameId, or an invalid
  427. // IdentifierId if this is a special name.
  428. auto AsIdentifierId() const -> IdentifierId {
  429. return index >= 0 ? IdentifierId(index) : IdentifierId::Invalid;
  430. }
  431. auto Print(llvm::raw_ostream& out) const -> void {
  432. out << "name";
  433. if (*this == SelfValue) {
  434. out << "SelfValue";
  435. } else if (*this == SelfType) {
  436. out << "SelfType";
  437. } else if (*this == ReturnSlot) {
  438. out << "ReturnSlot";
  439. } else if (*this == PackageNamespace) {
  440. out << "PackageNamespace";
  441. } else if (*this == Base) {
  442. out << "Base";
  443. } else {
  444. CARBON_CHECK(!is_valid() || index >= 0, "Unknown index {0}", index);
  445. IdBase::Print(out);
  446. }
  447. }
  448. };
  449. constexpr NameId NameId::Invalid = NameId(InvalidIndex);
  450. constexpr NameId NameId::SelfValue = NameId(InvalidIndex - 1);
  451. constexpr NameId NameId::SelfType = NameId(InvalidIndex - 2);
  452. constexpr NameId NameId::ReturnSlot = NameId(InvalidIndex - 3);
  453. constexpr NameId NameId::PackageNamespace = NameId(InvalidIndex - 4);
  454. constexpr NameId NameId::Base = NameId(InvalidIndex - 5);
  455. constexpr int NameId::NonIndexValueCount = 6;
  456. // Enforce the link between SpecialValueCount and the last special value.
  457. static_assert(NameId::NonIndexValueCount == -NameId::Base.index);
  458. // The ID of a name scope.
  459. struct NameScopeId : public IdBase, public Printable<NameScopeId> {
  460. using ValueType = NameScope;
  461. // An explicitly invalid ID.
  462. static const NameScopeId Invalid;
  463. // The package (or file) name scope, guaranteed to be the first added.
  464. static const NameScopeId Package;
  465. using IdBase::IdBase;
  466. auto Print(llvm::raw_ostream& out) const -> void {
  467. out << "name_scope";
  468. IdBase::Print(out);
  469. }
  470. };
  471. constexpr NameScopeId NameScopeId::Invalid = NameScopeId(InvalidIndex);
  472. constexpr NameScopeId NameScopeId::Package = NameScopeId(0);
  473. // The ID of an instruction block.
  474. struct InstBlockId : public IdBase, public Printable<InstBlockId> {
  475. using ElementType = InstId;
  476. using ValueType = llvm::MutableArrayRef<ElementType>;
  477. // The canonical empty block, reused to avoid allocating empty vectors. Always
  478. // the 0-index block.
  479. static const InstBlockId Empty;
  480. // Exported instructions. Empty until the File is fully checked; intermediate
  481. // state is in the Check::Context.
  482. static const InstBlockId Exports;
  483. // ImportRef instructions. Empty until the File is fully checked; intermediate
  484. // state is in the Check::Context.
  485. static const InstBlockId ImportRefs;
  486. // Global declaration initialization instructions. Empty if none are present.
  487. // Otherwise, __global_init function will be generated and this block will
  488. // be inserted into it.
  489. static const InstBlockId GlobalInit;
  490. // An explicitly invalid ID.
  491. static const InstBlockId Invalid;
  492. // An ID for unreachable code.
  493. static const InstBlockId Unreachable;
  494. using IdBase::IdBase;
  495. auto Print(llvm::raw_ostream& out) const -> void {
  496. if (*this == Unreachable) {
  497. out << "unreachable";
  498. } else if (*this == Empty) {
  499. out << "empty";
  500. } else if (*this == Exports) {
  501. out << "exports";
  502. } else if (*this == ImportRefs) {
  503. out << "import_refs";
  504. } else if (*this == GlobalInit) {
  505. out << "global_init";
  506. } else {
  507. out << "block";
  508. IdBase::Print(out);
  509. }
  510. }
  511. };
  512. constexpr InstBlockId InstBlockId::Empty = InstBlockId(0);
  513. constexpr InstBlockId InstBlockId::Exports = InstBlockId(1);
  514. constexpr InstBlockId InstBlockId::ImportRefs = InstBlockId(2);
  515. constexpr InstBlockId InstBlockId::GlobalInit = InstBlockId(3);
  516. constexpr InstBlockId InstBlockId::Invalid = InstBlockId(InvalidIndex);
  517. constexpr InstBlockId InstBlockId::Unreachable = InstBlockId(InvalidIndex - 1);
  518. // The ID of a type.
  519. struct TypeId : public IdBase, public Printable<TypeId> {
  520. // StringifyType() is used for diagnostics.
  521. using DiagnosticType = DiagnosticTypeInfo<std::string>;
  522. // The builtin TypeType.
  523. static const TypeId TypeType;
  524. // The builtin Error.
  525. static const TypeId Error;
  526. // An explicitly invalid ID.
  527. static const TypeId Invalid;
  528. using IdBase::IdBase;
  529. // Returns the ID of the type corresponding to the constant `const_id`, which
  530. // must be of type `type`. As an exception, the type `Error` is of type
  531. // `Error`.
  532. static constexpr auto ForTypeConstant(ConstantId const_id) -> TypeId {
  533. return TypeId(const_id.index);
  534. }
  535. // Returns the constant ID that defines the type.
  536. auto AsConstantId() const -> ConstantId { return ConstantId(index); }
  537. auto Print(llvm::raw_ostream& out) const -> void {
  538. out << "type";
  539. if (*this == TypeType) {
  540. out << "TypeType";
  541. } else if (*this == Error) {
  542. out << "Error";
  543. } else {
  544. out << "(";
  545. AsConstantId().Print(out, /*disambiguate=*/false);
  546. out << ")";
  547. }
  548. }
  549. };
  550. constexpr TypeId TypeId::TypeType = TypeId::ForTypeConstant(
  551. ConstantId::ForTemplateConstant(InstId::BuiltinTypeType));
  552. constexpr TypeId TypeId::Error = TypeId::ForTypeConstant(ConstantId::Error);
  553. constexpr TypeId TypeId::Invalid = TypeId(InvalidIndex);
  554. // The ID of a type block.
  555. struct TypeBlockId : public IdBase, public Printable<TypeBlockId> {
  556. using ElementType = TypeId;
  557. using ValueType = llvm::MutableArrayRef<ElementType>;
  558. // An explicitly invalid ID.
  559. static const TypeBlockId Invalid;
  560. using IdBase::IdBase;
  561. auto Print(llvm::raw_ostream& out) const -> void {
  562. out << "type_block";
  563. IdBase::Print(out);
  564. }
  565. };
  566. constexpr TypeBlockId TypeBlockId::Invalid = TypeBlockId(InvalidIndex);
  567. // An index for element access, for structs, tuples, and classes.
  568. struct ElementIndex : public IndexBase, public Printable<ElementIndex> {
  569. using IndexBase::IndexBase;
  570. auto Print(llvm::raw_ostream& out) const -> void {
  571. out << "element";
  572. IndexBase::Print(out);
  573. }
  574. };
  575. // The ID of a library name. This is either a string literal or `default`.
  576. struct LibraryNameId : public IdBase, public Printable<NameId> {
  577. using DiagnosticType = DiagnosticTypeInfo<std::string>;
  578. // An explicitly invalid ID.
  579. static const LibraryNameId Invalid;
  580. // The name of `default`.
  581. static const LibraryNameId Default;
  582. // Track cases where the library name was set, but has been diagnosed and
  583. // shouldn't be used anymore.
  584. static const LibraryNameId Error;
  585. // Returns the LibraryNameId for a library name as a string literal.
  586. static auto ForStringLiteralValueId(StringLiteralValueId id)
  587. -> LibraryNameId {
  588. CARBON_CHECK(id.index >= InvalidIndex, "Unexpected library name ID {0}",
  589. id);
  590. if (id == StringLiteralValueId::Invalid) {
  591. // Prior to SemIR, we use invalid to indicate `default`.
  592. return LibraryNameId::Default;
  593. } else {
  594. return LibraryNameId(id.index);
  595. }
  596. }
  597. using IdBase::IdBase;
  598. // Converts a LibraryNameId back to a string literal.
  599. auto AsStringLiteralValueId() const -> StringLiteralValueId {
  600. CARBON_CHECK(index >= InvalidIndex, "{0} must be handled directly", *this);
  601. return StringLiteralValueId(index);
  602. }
  603. auto Print(llvm::raw_ostream& out) const -> void {
  604. out << "libraryName";
  605. if (*this == Default) {
  606. out << "Default";
  607. } else if (*this == Error) {
  608. out << "<error>";
  609. } else {
  610. IdBase::Print(out);
  611. }
  612. }
  613. };
  614. constexpr LibraryNameId LibraryNameId::Invalid = LibraryNameId(InvalidIndex);
  615. constexpr LibraryNameId LibraryNameId::Default =
  616. LibraryNameId(InvalidIndex - 1);
  617. constexpr LibraryNameId LibraryNameId::Error = LibraryNameId(InvalidIndex - 2);
  618. // The ID of an ImportIRInst.
  619. struct ImportIRInstId : public IdBase, public Printable<ImportIRInstId> {
  620. using ValueType = ImportIRInst;
  621. // An explicitly invalid ID.
  622. static const ImportIRInstId Invalid;
  623. using IdBase::IdBase;
  624. auto Print(llvm::raw_ostream& out) const -> void {
  625. out << "import_ir_inst";
  626. IdBase::Print(out);
  627. }
  628. };
  629. constexpr ImportIRInstId ImportIRInstId::Invalid = ImportIRInstId(InvalidIndex);
  630. // A SemIR location used exclusively for diagnostic locations.
  631. //
  632. // Contents:
  633. // - index > Invalid: A Parse::NodeId in the current IR.
  634. // - index < Invalid: An ImportIRInstId.
  635. // - index == Invalid: Can be used for either.
  636. struct LocId : public IdBase, public Printable<LocId> {
  637. // An explicitly invalid ID.
  638. static const LocId Invalid;
  639. using IdBase::IdBase;
  640. // NOLINTNEXTLINE(google-explicit-constructor)
  641. constexpr LocId(Parse::InvalidNodeId /*invalid*/) : IdBase(InvalidIndex) {}
  642. // NOLINTNEXTLINE(google-explicit-constructor)
  643. constexpr LocId(Parse::NodeId node_id) : IdBase(node_id.index) {
  644. CARBON_CHECK(node_id.is_valid() == is_valid());
  645. }
  646. // NOLINTNEXTLINE(google-explicit-constructor)
  647. constexpr LocId(ImportIRInstId inst_id)
  648. : IdBase(InvalidIndex + ImportIRInstId::InvalidIndex - inst_id.index) {
  649. CARBON_CHECK(inst_id.is_valid() == is_valid());
  650. }
  651. auto is_node_id() const -> bool { return index > InvalidIndex; }
  652. auto is_import_ir_inst_id() const -> bool { return index < InvalidIndex; }
  653. // This is allowed to return an invalid NodeId, but should never be used for a
  654. // valid InstId.
  655. auto node_id() const -> Parse::NodeId {
  656. CARBON_CHECK(is_node_id() || !is_valid());
  657. return Parse::NodeId(index);
  658. }
  659. // This is allowed to return an invalid InstId, but should never be used for a
  660. // valid NodeId.
  661. auto import_ir_inst_id() const -> ImportIRInstId {
  662. CARBON_CHECK(is_import_ir_inst_id() || !is_valid());
  663. return ImportIRInstId(InvalidIndex + ImportIRInstId::InvalidIndex - index);
  664. }
  665. auto Print(llvm::raw_ostream& out) const -> void {
  666. out << "loc_";
  667. if (is_node_id() || !is_valid()) {
  668. out << node_id();
  669. } else {
  670. out << import_ir_inst_id();
  671. }
  672. }
  673. };
  674. constexpr LocId LocId::Invalid = LocId(Parse::NodeId::Invalid);
  675. } // namespace Carbon::SemIR
  676. #endif // CARBON_TOOLCHAIN_SEM_IR_IDS_H_