singleton_insts.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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::ErrorInst,
  17. InstKind::IntLiteralType,
  18. InstKind::LegacyFloatType,
  19. InstKind::NamespaceType,
  20. InstKind::SpecificFunctionType,
  21. InstKind::StringType,
  22. InstKind::VtableType,
  23. InstKind::WitnessType,
  24. };
  25. // Returns true if the InstKind is a singleton.
  26. constexpr auto IsSingletonInstKind(InstKind kind) -> bool;
  27. // Provides the InstId for singleton instructions. These are exposed as
  28. // `InstT::SingletonInstId` in `typed_insts.h`.
  29. template <InstKind::RawEnumType Kind>
  30. requires(IsSingletonInstKind(InstKind::Make(Kind)))
  31. constexpr auto MakeSingletonInstId() -> InstId;
  32. // Returns true if the InstId corresponds to a singleton inst.
  33. constexpr auto IsSingletonInstId(InstId id) -> bool {
  34. return id.index >= 0 &&
  35. id.index < static_cast<int32_t>(SingletonInstKinds.size());
  36. }
  37. // Only implementation details are below.
  38. namespace Internal {
  39. // Returns the index for a singleton instruction, or -1 if it's not a singleton.
  40. constexpr auto GetSingletonInstIndex(InstKind kind) -> int32_t {
  41. for (int32_t i = 0; i < static_cast<int32_t>(SingletonInstKinds.size());
  42. ++i) {
  43. if (SingletonInstKinds[i] == kind) {
  44. return i;
  45. }
  46. }
  47. return -1;
  48. }
  49. } // namespace Internal
  50. constexpr auto IsSingletonInstKind(InstKind kind) -> bool {
  51. return Internal::GetSingletonInstIndex(kind) >= 0;
  52. }
  53. template <InstKind::RawEnumType Kind>
  54. requires(IsSingletonInstKind(InstKind::Make(Kind)))
  55. constexpr auto MakeSingletonInstId() -> InstId {
  56. auto index = Internal::GetSingletonInstIndex(InstKind::Make(Kind));
  57. return InstId(index);
  58. }
  59. } // namespace Carbon::SemIR
  60. #endif // CARBON_TOOLCHAIN_SEM_IR_SINGLETON_INSTS_H_