ids.h 40 KB

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