inst_namer.h 8.8 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, VtableId, FunctionId, ImplId,
  37. InterfaceId, SpecificInterfaceId>;
  38. // Construct the instruction namer, and assign names to all instructions in
  39. // the provided file.
  40. explicit InstNamer(const File* sem_ir);
  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. return static_cast<bool>(insts_[inst_id.index].second);
  82. }
  83. private:
  84. // A space in which unique names can be allocated.
  85. class Namespace {
  86. private:
  87. // A result of a name lookup.
  88. struct NameResult;
  89. public:
  90. // A name in a namespace, which might be redirected to refer to another name
  91. // for disambiguation purposes.
  92. class Name {
  93. public:
  94. explicit Name() : value_(nullptr) {}
  95. explicit Name(llvm::StringMapIterator<NameResult> it,
  96. size_t base_name_size)
  97. : value_(&*it), base_name_size_(base_name_size) {}
  98. explicit operator bool() const { return value_; }
  99. // Returns the disambiguated name.
  100. auto GetFullName() const -> llvm::StringRef;
  101. // Returns the base name, without any disambiguators.
  102. auto GetBaseName() const -> llvm::StringRef;
  103. auto SetFallback(Name name) -> void { value_->second.fallback = name; }
  104. auto SetAmbiguous() -> void { value_->second.ambiguous = true; }
  105. private:
  106. llvm::StringMapEntry<NameResult>* value_;
  107. // The base name length within `value_->first()`.
  108. size_t base_name_size_;
  109. };
  110. // Allocates and returns a name, handling ambiguity.
  111. auto AllocateName(const InstNamer& inst_namer,
  112. std::variant<LocId, uint64_t> loc_id_or_fingerprint,
  113. std::string name) -> Name;
  114. private:
  115. struct NameResult {
  116. bool ambiguous = false;
  117. Name fallback = Name();
  118. };
  119. llvm::StringMap<NameResult> allocated_;
  120. };
  121. // A named scope that contains named entities.
  122. struct Scope {
  123. Namespace::Name name;
  124. Namespace insts;
  125. Namespace labels;
  126. };
  127. // Helper class for naming a single instruction.
  128. class NamingContext;
  129. auto GetScopeInfo(ScopeId scope_id) -> Scope& {
  130. return scopes_[static_cast<int>(scope_id)];
  131. }
  132. auto GetScopeInfo(ScopeId scope_id) const -> const Scope& {
  133. return scopes_[static_cast<int>(scope_id)];
  134. }
  135. // For the given `IdT`, returns its start offset in the `ScopeId` space. Each
  136. // of `ScopeIdTypeEnum` is stored sequentially. When called with
  137. // `ScopeIdTypeEnum::None`, returns the full count of scopes.
  138. auto GetScopeIdOffset(ScopeIdTypeEnum id_enum) const -> int;
  139. auto AddBlockLabel(
  140. ScopeId scope_id, InstBlockId block_id, std::string name = "",
  141. std::variant<LocId, uint64_t> loc_id_or_fingerprint = LocId::None)
  142. -> void;
  143. // Finds and adds a suitable block label for the given SemIR instruction that
  144. // represents some kind of branch.
  145. auto AddBlockLabel(ScopeId scope_id, LocId loc_id, AnyBranch branch) -> void;
  146. // Adds a scope and instructions to walk. Avoids recursion while allowing
  147. // the loop to below add more instructions during iteration. The new
  148. // instructions are pushed such that they will be the next to be walked.
  149. // Internally that means they are reversed and added to the end of the vector,
  150. // since we pop from the back of the vector.
  151. auto PushBlockInsts(ScopeId scope_id, llvm::ArrayRef<InstId> inst_ids)
  152. -> void;
  153. auto PushBlockId(ScopeId scope_id, InstBlockId block_id) -> void;
  154. // Pushes generic information for an entity.
  155. auto PushGeneric(ScopeId scope_id, GenericId generic_id) -> void;
  156. // Names an entity, and pushes processing of its blocks.
  157. auto PushEntity(AssociatedConstantId associated_constant_id, ScopeId scope_id,
  158. Scope& scope) -> void;
  159. auto PushEntity(ClassId class_id, ScopeId scope_id, Scope& scope) -> void;
  160. auto PushEntity(FunctionId function_id, ScopeId scope_id, Scope& scope)
  161. -> 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_