ids.h 39 KB

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