id_kind.h 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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_ID_KIND_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_ID_KIND_H_
  6. #include <algorithm>
  7. #include "common/ostream.h"
  8. #include "toolchain/base/int.h"
  9. #include "toolchain/sem_ir/ids.h"
  10. namespace Carbon::SemIR {
  11. // An enum whose values are the specified types.
  12. template <typename... Types>
  13. class TypeEnum : public Printable<TypeEnum<Types...>> {
  14. public:
  15. static constexpr size_t NumTypes = sizeof...(Types);
  16. static constexpr size_t NumValues = NumTypes + 2;
  17. static_assert(NumValues <= 256, "Too many types for raw enum.");
  18. // TODO: Works around a clang-format bug:
  19. // https://github.com/llvm/llvm-project/issues/85476
  20. #define CARBON_OPEN_ENUM [[clang::enum_extensibility(open)]]
  21. // The underlying raw enumeration type.
  22. //
  23. // The enum_extensibility attribute indicates that this enum is intended to
  24. // take values that do not correspond to its declared enumerators.
  25. enum class CARBON_OPEN_ENUM RawEnumType : uint8_t {
  26. // The first sizeof...(Types) values correspond to the types.
  27. // An explicitly invalid value.
  28. Invalid = NumTypes,
  29. // Indicates that no type should be used.
  30. // TODO: This doesn't really fit the model of this type, but it's convenient
  31. // for all of its users.
  32. None,
  33. };
  34. #undef CARBON_OPEN_ENUM
  35. // Accesses the type given an enum value.
  36. template <RawEnumType K>
  37. requires(K != RawEnumType::Invalid)
  38. using TypeFor = __type_pack_element<static_cast<size_t>(K), Types...>;
  39. // Workaround for Clang bug https://github.com/llvm/llvm-project/issues/85461
  40. template <RawEnumType Value>
  41. static constexpr auto FromRaw = TypeEnum(Value);
  42. // Names for the `Invalid` and `None` enumeration values.
  43. static constexpr const TypeEnum& Invalid = FromRaw<RawEnumType::Invalid>;
  44. static constexpr const TypeEnum& None = FromRaw<RawEnumType::None>;
  45. // Accesses the enumeration value for the type `IdT`. If `AllowInvalid` is
  46. // set, any unexpected type is mapped to `Invalid`, otherwise an invalid type
  47. // results in a compile error.
  48. //
  49. // The `Self` parameter is an implementation detail to allow `ForImpl` to be
  50. // defined after this template, and should not be specified.
  51. template <typename IdT, bool AllowInvalid = false, typename Self = TypeEnum>
  52. static constexpr auto For = Self::template ForImpl<IdT, AllowInvalid>();
  53. // This bool indicates whether the specified type corresponds to a value in
  54. // this enum.
  55. template <typename IdT>
  56. static constexpr bool Contains = For<IdT, true>.is_valid();
  57. // Explicitly convert from the raw enum type.
  58. explicit constexpr TypeEnum(RawEnumType value) : value_(value) {}
  59. // Implicitly convert to the raw enum type, for use in `switch`.
  60. //
  61. // NOLINTNEXTLINE(google-explicit-constructor)
  62. constexpr operator RawEnumType() const { return value_; }
  63. // Conversion to bool is deleted to prevent direct use in an `if` condition
  64. // instead of comparing with another value.
  65. explicit operator bool() const = delete;
  66. // Returns the raw enum value.
  67. constexpr auto ToRaw() const -> RawEnumType { return value_; }
  68. // Returns a value that can be used as an array index. Returned value will be
  69. // < NumValues.
  70. constexpr auto ToIndex() const -> size_t {
  71. return static_cast<size_t>(value_);
  72. }
  73. // Returns whether this is a valid value, not `Invalid`.
  74. constexpr auto is_valid() const -> bool {
  75. return value_ != RawEnumType::Invalid;
  76. }
  77. auto Print(llvm::raw_ostream& out) const -> void {
  78. out << "IdKind(";
  79. if (value_ == RawEnumType::None) {
  80. out << "None";
  81. } else {
  82. static constexpr std::array<llvm::StringLiteral, sizeof...(Types)> Names =
  83. {
  84. Types::Label...,
  85. };
  86. out << Names[static_cast<int>(value_)];
  87. }
  88. out << ")";
  89. }
  90. private:
  91. // Translates a type to its enum value, or `Invalid`.
  92. template <typename IdT, bool AllowInvalid>
  93. static constexpr auto ForImpl() -> TypeEnum {
  94. // A bool for each type saying whether it matches. The result is the index
  95. // of the first `true` in this list. If none matches, then the result is the
  96. // length of the list, which is mapped to `Invalid`.
  97. constexpr bool TypeMatches[] = {std::same_as<IdT, Types>...};
  98. constexpr int Index =
  99. std::find(TypeMatches, TypeMatches + NumTypes, true) - TypeMatches;
  100. static_assert(Index != NumTypes || AllowInvalid,
  101. "Unexpected type passed to TypeEnum::For<...>");
  102. return TypeEnum(static_cast<RawEnumType>(Index));
  103. }
  104. RawEnumType value_;
  105. };
  106. // An enum of all the ID types used as instruction operands.
  107. //
  108. // As instruction operands, the types listed here can appear as fields of typed
  109. // instructions (`toolchain/sem_ir/typed_insts.h`) and must implement the
  110. // `FromRaw` and `ToRaw` protocol in `SemIR::Inst`. In most cases this is done
  111. // by inheriting from `IdBase` or `IndexBase`.
  112. using IdKind = TypeEnum<
  113. // From base/value_store.h.
  114. IntId, RealId, FloatId, StringLiteralValueId,
  115. // From sem_ir/ids.h.
  116. InstId, AbsoluteInstId, AnyRawId, ConstantId, EntityNameId,
  117. CompileTimeBindIndex, RuntimeParamIndex, FacetTypeId, FunctionId, ClassId,
  118. InterfaceId, AssociatedConstantId, ImplId, GenericId, SpecificId,
  119. ImportIRId, ImportIRInstId, LocId, BoolValue, IntKind, NameId, NameScopeId,
  120. InstBlockId, AbsoluteInstBlockId, DeclInstBlockId, LabelId, ExprRegionId,
  121. StructTypeFieldsId, TypeId, TypeBlockId, ElementIndex, LibraryNameId,
  122. FloatKind>;
  123. } // namespace Carbon::SemIR
  124. #endif // CARBON_TOOLCHAIN_SEM_IR_ID_KIND_H_