ids.h 37 KB

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