singleton_insts.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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_SINGLETON_INSTS_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_SINGLETON_INSTS_H_
  6. #include "toolchain/sem_ir/ids.h"
  7. #include "toolchain/sem_ir/inst_kind.h"
  8. namespace Carbon::SemIR {
  9. // The canonical list of singleton kinds. The order of `TypeType` is
  10. // significant because other singletons use it as a type.
  11. static constexpr std::array SingletonInstKinds = {
  12. InstKind::TypeType,
  13. InstKind::AutoType,
  14. InstKind::BoolType,
  15. InstKind::BoundMethodType,
  16. InstKind::CharLiteralType,
  17. InstKind::ErrorInst,
  18. InstKind::FloatLiteralType,
  19. InstKind::FormType,
  20. InstKind::InstType,
  21. InstKind::IntLiteralType,
  22. InstKind::NamespaceType,
  23. InstKind::RequireSpecificDefinitionType,
  24. InstKind::SpecificFunctionType,
  25. InstKind::VtableType,
  26. InstKind::WitnessType,
  27. };
  28. // Returns true if the InstKind is a singleton.
  29. constexpr auto IsSingletonInstKind(InstKind kind) -> bool;
  30. // Provides the TypeInstId for singleton instructions. These are exposed as
  31. // `InstT::TypeInstId` in `typed_insts.h`.
  32. template <InstKind::RawEnumType Kind>
  33. requires(IsSingletonInstKind(InstKind::Make(Kind)))
  34. constexpr auto MakeSingletonTypeInstId() -> TypeInstId;
  35. // Returns true if the InstId corresponds to a singleton inst.
  36. constexpr auto IsSingletonInstId(InstId id) -> bool {
  37. return id.index >= 0 &&
  38. id.index < static_cast<int32_t>(SingletonInstKinds.size());
  39. }
  40. // Only implementation details are below.
  41. namespace Internal {
  42. // Returns the index for a singleton instruction, or -1 if it's not a singleton.
  43. constexpr auto GetSingletonInstIndex(InstKind kind) -> int32_t {
  44. for (int32_t i = 0; i < static_cast<int32_t>(SingletonInstKinds.size());
  45. ++i) {
  46. if (SingletonInstKinds[i] == kind) {
  47. return i;
  48. }
  49. }
  50. return -1;
  51. }
  52. } // namespace Internal
  53. constexpr auto IsSingletonInstKind(InstKind kind) -> bool {
  54. return Internal::GetSingletonInstIndex(kind) >= 0;
  55. }
  56. template <InstKind::RawEnumType Kind>
  57. requires(IsSingletonInstKind(InstKind::Make(Kind)))
  58. constexpr auto MakeSingletonTypeInstId() -> TypeInstId {
  59. auto index = Internal::GetSingletonInstIndex(InstKind::Make(Kind));
  60. return TypeInstId(index);
  61. }
  62. } // namespace Carbon::SemIR
  63. #endif // CARBON_TOOLCHAIN_SEM_IR_SINGLETON_INSTS_H_