ids.h 29 KB

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