inst_namer.h 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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_INST_NAMER_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_INST_NAMER_H_
  6. #include "llvm/Support/raw_ostream.h"
  7. #include "toolchain/lex/tokenized_buffer.h"
  8. #include "toolchain/parse/tree.h"
  9. #include "toolchain/sem_ir/file.h"
  10. #include "toolchain/sem_ir/ids.h"
  11. #include "toolchain/sem_ir/inst_fingerprinter.h"
  12. namespace Carbon::SemIR {
  13. // Assigns names to instructions, blocks, and scopes in the Semantics IR.
  14. class InstNamer {
  15. public:
  16. // int32_t matches the input value size.
  17. // NOLINTNEXTLINE(performance-enum-size)
  18. enum class ScopeId : int32_t {
  19. None = -1,
  20. File = 0,
  21. ImportRefs = 1,
  22. Constants = 2,
  23. FirstFunction = 3,
  24. };
  25. static_assert(sizeof(ScopeId) == sizeof(FunctionId));
  26. struct NumberOfScopesTag {};
  27. // Construct the instruction namer, and assign names to all instructions in
  28. // the provided file.
  29. explicit InstNamer(const File* sem_ir);
  30. // Returns the scope ID corresponding to an ID of a function, class, or
  31. // interface.
  32. template <typename IdT>
  33. auto GetScopeFor(IdT id) const -> ScopeId {
  34. auto index = static_cast<int32_t>(ScopeId::FirstFunction);
  35. if constexpr (!std::same_as<FunctionId, IdT>) {
  36. index += sem_ir_->functions().size();
  37. if constexpr (!std::same_as<ClassId, IdT>) {
  38. index += sem_ir_->classes().size();
  39. if constexpr (!std::same_as<InterfaceId, IdT>) {
  40. index += sem_ir_->interfaces().size();
  41. if constexpr (!std::same_as<AssociatedConstantId, IdT>) {
  42. index += sem_ir_->associated_constants().size();
  43. if constexpr (!std::same_as<ImplId, IdT>) {
  44. index += sem_ir_->impls().size();
  45. if constexpr (!std::same_as<SpecificInterfaceId, IdT>) {
  46. index += sem_ir_->specific_interfaces().size();
  47. static_assert(std::same_as<NumberOfScopesTag, IdT>,
  48. "Unknown ID kind for scope");
  49. }
  50. }
  51. }
  52. }
  53. }
  54. }
  55. if constexpr (!std::same_as<NumberOfScopesTag, IdT>) {
  56. index += id.index;
  57. }
  58. return static_cast<ScopeId>(index);
  59. }
  60. // Returns the scope ID corresponding to a generic. A generic object shares
  61. // its scope with its generic entity.
  62. auto GetScopeFor(GenericId id) const -> ScopeId {
  63. return generic_scopes_[id.index];
  64. }
  65. // Returns the IR name for the specified scope.
  66. auto GetScopeName(ScopeId scope) const -> std::string;
  67. // Returns the IR name to use for a function, class, or interface.
  68. template <typename IdT>
  69. auto GetNameFor(IdT id) const -> std::string {
  70. if (!id.has_value()) {
  71. return "invalid";
  72. }
  73. return GetScopeName(GetScopeFor(id));
  74. }
  75. // Returns the IR name to use for an instruction within its own scope, without
  76. // any prefix. Returns an empty string if there isn't a good name.
  77. auto GetUnscopedNameFor(InstId inst_id) const -> llvm::StringRef;
  78. // Returns the IR name to use for an instruction, when referenced from a given
  79. // scope.
  80. auto GetNameFor(ScopeId scope_id, InstId inst_id) const -> std::string;
  81. // Returns the IR name to use for a label within its own scope, without any
  82. // prefix. Returns an empty string if there isn't a good name.
  83. auto GetUnscopedLabelFor(InstBlockId block_id) const -> llvm::StringRef;
  84. // Returns the IR name to use for a label, when referenced from a given scope.
  85. auto GetLabelFor(ScopeId scope_id, InstBlockId block_id) const -> std::string;
  86. private:
  87. // A space in which unique names can be allocated.
  88. struct Namespace {
  89. // A result of a name lookup.
  90. struct NameResult;
  91. // A name in a namespace, which might be redirected to refer to another name
  92. // for disambiguation purposes.
  93. class Name {
  94. public:
  95. Name() : value_(nullptr) {}
  96. explicit Name(llvm::StringMapIterator<NameResult> it) : value_(&*it) {}
  97. explicit operator bool() const { return value_; }
  98. auto str() const -> llvm::StringRef;
  99. auto SetFallback(Name name) -> void { value_->second.fallback = name; }
  100. auto SetAmbiguous() -> void { value_->second.ambiguous = true; }
  101. private:
  102. llvm::StringMapEntry<NameResult>* value_ = nullptr;
  103. };
  104. struct NameResult {
  105. bool ambiguous = false;
  106. Name fallback = Name();
  107. };
  108. llvm::StringMap<NameResult> allocated = {};
  109. int unnamed_count = 0;
  110. auto AddNameUnchecked(llvm::StringRef name) -> Name {
  111. return Name(allocated.insert({name, NameResult()}).first);
  112. }
  113. auto AllocateName(const InstNamer& inst_namer,
  114. std::variant<LocId, uint64_t> loc_id_or_fingerprint,
  115. std::string name) -> Name;
  116. };
  117. // A named scope that contains named entities.
  118. struct Scope {
  119. Namespace::Name name;
  120. Namespace insts;
  121. Namespace labels;
  122. };
  123. auto GetScopeInfo(ScopeId scope_id) -> Scope& {
  124. return scopes_[static_cast<int>(scope_id)];
  125. }
  126. auto GetScopeInfo(ScopeId scope_id) const -> const Scope& {
  127. return scopes_[static_cast<int>(scope_id)];
  128. }
  129. auto AddBlockLabel(
  130. ScopeId scope_id, InstBlockId block_id, std::string name = "",
  131. std::variant<LocId, uint64_t> loc_id_or_fingerprint = LocId::None)
  132. -> void;
  133. // Finds and adds a suitable block label for the given SemIR instruction that
  134. // represents some kind of branch.
  135. auto AddBlockLabel(ScopeId scope_id, LocId loc_id, AnyBranch branch) -> void;
  136. auto CollectNamesInBlock(ScopeId scope_id, InstBlockId block_id) -> void;
  137. auto CollectNamesInBlock(ScopeId scope_id, llvm::ArrayRef<InstId> block)
  138. -> void;
  139. auto CollectNamesInGeneric(ScopeId scope_id, GenericId generic_id) -> void;
  140. const File* sem_ir_;
  141. InstFingerprinter fingerprinter_;
  142. // The namespace for entity names. Names within this namespace are prefixed
  143. // with `@` in formatted SemIR.
  144. Namespace globals_;
  145. // The enclosing scope and name for each instruction, indexed by the InstId's
  146. // index.
  147. std::vector<std::pair<ScopeId, Namespace::Name>> insts_;
  148. // The enclosing scope and name for each block that might be a branch target,
  149. // indexed by the InstBlockId's index.
  150. std::vector<std::pair<ScopeId, Namespace::Name>> labels_;
  151. // The scopes corresponding to ScopeId values.
  152. std::vector<Scope> scopes_;
  153. // The scope IDs corresponding to generics. The vector indexes are the
  154. // GenericId index.
  155. std::vector<ScopeId> generic_scopes_;
  156. };
  157. } // namespace Carbon::SemIR
  158. #endif // CARBON_TOOLCHAIN_SEM_IR_INST_NAMER_H_