inst_namer.h 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 "common/type_enum.h"
  7. #include "llvm/Support/raw_ostream.h"
  8. #include "toolchain/lex/tokenized_buffer.h"
  9. #include "toolchain/parse/tree.h"
  10. #include "toolchain/sem_ir/file.h"
  11. #include "toolchain/sem_ir/ids.h"
  12. #include "toolchain/sem_ir/inst_categories.h"
  13. #include "toolchain/sem_ir/inst_fingerprinter.h"
  14. namespace Carbon::SemIR {
  15. // Assigns names to instructions, blocks, and scopes in the Semantics IR.
  16. //
  17. // If `<unexpected>` occurs in output of valid SemIR, it often means the
  18. // instruction needs to be handled by `NamingContext::NameInst` (see the cpp
  19. // file). Note that `<unexpected>` can occur in invalid SemIR just because we're
  20. // unable to correctly walk the SemIR.
  21. class InstNamer {
  22. public:
  23. // int32_t matches the input value size.
  24. enum class ScopeId : int32_t {
  25. None = -1,
  26. // The three top-level scopes.
  27. File = 0,
  28. Imports = 1,
  29. Constants = 2,
  30. // The first entity scope; see entities in `ScopeIdTypeEnum`.
  31. FirstEntityScope = 3,
  32. };
  33. static_assert(sizeof(ScopeId) == sizeof(AnyIdBase));
  34. // Entities whose scopes get entries from `ScopeId`.
  35. using ScopeIdTypeEnum =
  36. TypeEnum<AssociatedConstantId, ClassId, CppOverloadSetId, FunctionId,
  37. ImplId, InterfaceId, SpecificInterfaceId, VtableId>;
  38. // Construct the instruction namer, and assign names to all instructions in
  39. // the provided file.
  40. explicit InstNamer(const File* sem_ir, int total_ir_count);
  41. // Returns the scope ID corresponding to an ID of a function, class, or
  42. // interface.
  43. template <typename IdT>
  44. requires ScopeIdTypeEnum::Contains<IdT>
  45. auto GetScopeFor(IdT id) const -> ScopeId {
  46. return static_cast<ScopeId>(GetScopeIdOffset(ScopeIdTypeEnum::For<IdT>) +
  47. id.index);
  48. }
  49. // Returns the scope ID corresponding to a generic. A generic object shares
  50. // its scope with its generic entity.
  51. auto GetScopeFor(GenericId id) const -> ScopeId {
  52. return generic_scopes_[id.index];
  53. }
  54. // Returns the IR name for the specified scope.
  55. auto GetScopeName(ScopeId scope) const -> std::string;
  56. // Returns the name for a parent NameScope. Does not return a name for
  57. // namespaces. Used as part of naming functions with their containing scope.
  58. auto GetNameForParentNameScope(NameScopeId name_scope_id) -> llvm::StringRef;
  59. // Returns the IR name to use for a function, class, or interface.
  60. template <typename IdT>
  61. requires(ScopeIdTypeEnum::Contains<IdT> || std::same_as<IdT, GenericId>)
  62. auto GetNameFor(IdT id) const -> std::string {
  63. if (!id.has_value()) {
  64. return "invalid";
  65. }
  66. return GetScopeName(GetScopeFor(id));
  67. }
  68. // Returns the IR name to use for an instruction within its own scope, without
  69. // any prefix. Returns an empty string if there isn't a good name.
  70. auto GetUnscopedNameFor(InstId inst_id) const -> llvm::StringRef;
  71. // Returns the IR name to use for an instruction, when referenced from a given
  72. // scope.
  73. auto GetNameFor(ScopeId scope_id, InstId inst_id) const -> std::string;
  74. // Returns the IR name to use for a label within its own scope, without any
  75. // prefix. Returns an empty string if there isn't a good name.
  76. auto GetUnscopedLabelFor(InstBlockId block_id) const -> llvm::StringRef;
  77. // Returns the IR name to use for a label, when referenced from a given scope.
  78. auto GetLabelFor(ScopeId scope_id, InstBlockId block_id) const -> std::string;
  79. // Returns true if the instruction has a specific name assigned.
  80. auto has_name(InstId inst_id) const -> bool;
  81. private:
  82. // A space in which unique names can be allocated.
  83. class Namespace {
  84. private:
  85. // A result of a name lookup.
  86. struct NameResult;
  87. public:
  88. // A name in a namespace, which might be redirected to refer to another name
  89. // for disambiguation purposes.
  90. class Name {
  91. public:
  92. explicit Name() : value_(nullptr) {}
  93. explicit Name(llvm::StringMap<NameResult>::iterator it,
  94. size_t base_name_size)
  95. : value_(&*it), base_name_size_(base_name_size) {}
  96. explicit operator bool() const { return value_; }
  97. // Returns the disambiguated name.
  98. auto GetFullName() const -> llvm::StringRef;
  99. // Returns the base name, without any disambiguators.
  100. auto GetBaseName() const -> llvm::StringRef;
  101. auto SetFallback(Name name) -> void { value_->second.fallback = name; }
  102. auto SetAmbiguous() -> void { value_->second.ambiguous = true; }
  103. private:
  104. llvm::StringMapEntry<NameResult>* value_;
  105. // The base name length within `value_->first()`.
  106. size_t base_name_size_;
  107. };
  108. // Allocates and returns a name, handling ambiguity.
  109. auto AllocateName(const InstNamer& inst_namer,
  110. std::variant<LocId, uint64_t> loc_id_or_fingerprint,
  111. std::string name) -> Name;
  112. private:
  113. struct NameResult {
  114. bool ambiguous = false;
  115. Name fallback = Name();
  116. };
  117. llvm::StringMap<NameResult> allocated_;
  118. };
  119. // A named scope that contains named entities.
  120. struct Scope {
  121. Namespace::Name name;
  122. Namespace insts;
  123. Namespace labels;
  124. };
  125. // Helper class for naming a single instruction.
  126. class NamingContext;
  127. auto GetScopeInfo(ScopeId scope_id) -> Scope& {
  128. return scopes_[static_cast<int>(scope_id)];
  129. }
  130. auto GetScopeInfo(ScopeId scope_id) const -> const Scope& {
  131. return scopes_[static_cast<int>(scope_id)];
  132. }
  133. // For the given `IdT`, returns its start offset in the `ScopeId` space. Each
  134. // of `ScopeIdTypeEnum` is stored sequentially. When called with
  135. // `ScopeIdTypeEnum::None`, returns the full count of scopes.
  136. auto GetScopeIdOffset(ScopeIdTypeEnum id_enum) const -> int;
  137. auto AddBlockLabel(
  138. ScopeId scope_id, InstBlockId block_id, std::string name = "",
  139. std::variant<LocId, uint64_t> loc_id_or_fingerprint = LocId::None)
  140. -> void;
  141. // Finds and adds a suitable block label for the given SemIR instruction that
  142. // represents some kind of branch.
  143. auto AddBlockLabel(ScopeId scope_id, LocId loc_id, AnyBranch branch) -> void;
  144. // Adds a scope and instructions to walk. Avoids recursion while allowing
  145. // the loop to below add more instructions during iteration. The new
  146. // instructions are pushed such that they will be the next to be walked.
  147. // Internally that means they are reversed and added to the end of the vector,
  148. // since we pop from the back of the vector.
  149. auto PushBlockInsts(ScopeId scope_id, llvm::ArrayRef<InstId> inst_ids)
  150. -> void;
  151. auto PushBlockId(ScopeId scope_id, InstBlockId block_id) -> void;
  152. // Pushes generic information for an entity.
  153. auto PushGeneric(ScopeId scope_id, GenericId generic_id) -> void;
  154. // Names an entity, and pushes processing of its blocks.
  155. auto PushEntity(AssociatedConstantId associated_constant_id, ScopeId scope_id,
  156. Scope& scope) -> void;
  157. auto PushEntity(ClassId class_id, ScopeId scope_id, Scope& scope) -> void;
  158. auto PushEntity(FunctionId function_id, ScopeId scope_id, Scope& scope)
  159. -> void;
  160. auto PushEntity(CppOverloadSetId cpp_overload_set_id, ScopeId scope_id,
  161. Scope& scope) -> void;
  162. auto PushEntity(ImplId impl_id, ScopeId scope_id, Scope& scope) -> void;
  163. auto PushEntity(InterfaceId interface_id, ScopeId scope_id, Scope& scope)
  164. -> void;
  165. auto PushEntity(VtableId vtable_id, ScopeId scope_id, Scope& scope) -> void;
  166. // Always returns the name of the entity. May push it if it has not yet been
  167. // pushed.
  168. template <typename EntityIdT>
  169. auto MaybePushEntity(EntityIdT entity_id) -> llvm::StringRef {
  170. auto scope_id = GetScopeFor(entity_id);
  171. auto& scope = GetScopeInfo(scope_id);
  172. if (!scope.name) {
  173. PushEntity(entity_id, scope_id, scope);
  174. }
  175. return scope.name.GetBaseName();
  176. }
  177. const File* sem_ir_;
  178. InstFingerprinter fingerprinter_;
  179. // The namespace for entity names. Names within this namespace are prefixed
  180. // with `@` in formatted SemIR.
  181. Namespace globals_;
  182. // The enclosing scope and name for each instruction, indexed by the InstId's
  183. // index.
  184. std::vector<std::pair<ScopeId, Namespace::Name>> insts_;
  185. // The enclosing scope and name for each block that might be a branch target,
  186. // indexed by the InstBlockId's index.
  187. std::vector<std::pair<ScopeId, Namespace::Name>> labels_;
  188. // The scopes corresponding to ScopeId values.
  189. std::vector<Scope> scopes_;
  190. // The scope IDs corresponding to generics. The vector indexes are the
  191. // GenericId index.
  192. std::vector<ScopeId> generic_scopes_;
  193. // The stack of instructions to name.
  194. llvm::SmallVector<std::pair<ScopeId, InstId>> inst_stack_;
  195. // The stack of blocks to traverse.
  196. llvm::SmallVector<std::pair<ScopeId, InstBlockId>> inst_block_stack_;
  197. };
  198. } // namespace Carbon::SemIR
  199. #endif // CARBON_TOOLCHAIN_SEM_IR_INST_NAMER_H_