inst_namer.h 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. class InstNamer {
  17. public:
  18. // int32_t matches the input value size.
  19. enum class ScopeId : int32_t {
  20. None = -1,
  21. // The three top-level scopes.
  22. File = 0,
  23. Imports = 1,
  24. Constants = 2,
  25. // The first entity scope; see entities in `ScopeIdTypeEnum`.
  26. FirstEntityScope = 3,
  27. };
  28. static_assert(sizeof(ScopeId) == sizeof(AnyIdBase));
  29. // Entities whose scopes get entries from `ScopeId`.
  30. using ScopeIdTypeEnum =
  31. TypeEnum<AssociatedConstantId, ClassId, VtableId, FunctionId, ImplId,
  32. InterfaceId, SpecificInterfaceId>;
  33. // Construct the instruction namer, and assign names to all instructions in
  34. // the provided file.
  35. explicit InstNamer(const File* sem_ir);
  36. // Returns the scope ID corresponding to an ID of a function, class, or
  37. // interface.
  38. template <typename IdT>
  39. requires ScopeIdTypeEnum::Contains<IdT>
  40. auto GetScopeFor(IdT id) const -> ScopeId {
  41. return static_cast<ScopeId>(GetScopeIdOffset(ScopeIdTypeEnum::For<IdT>) +
  42. id.index);
  43. }
  44. // Returns the scope ID corresponding to a generic. A generic object shares
  45. // its scope with its generic entity.
  46. auto GetScopeFor(GenericId id) const -> ScopeId {
  47. return generic_scopes_[id.index];
  48. }
  49. // Returns the IR name for the specified scope.
  50. auto GetScopeName(ScopeId scope) const -> std::string;
  51. // Returns the IR name to use for a function, class, or interface.
  52. template <typename IdT>
  53. requires(ScopeIdTypeEnum::Contains<IdT> || std::same_as<IdT, GenericId>)
  54. auto GetNameFor(IdT id) const -> std::string {
  55. if (!id.has_value()) {
  56. return "invalid";
  57. }
  58. return GetScopeName(GetScopeFor(id));
  59. }
  60. // Returns the IR name to use for an instruction within its own scope, without
  61. // any prefix. Returns an empty string if there isn't a good name.
  62. auto GetUnscopedNameFor(InstId inst_id) const -> llvm::StringRef;
  63. // Returns the IR name to use for an instruction, when referenced from a given
  64. // scope.
  65. auto GetNameFor(ScopeId scope_id, InstId inst_id) const -> std::string;
  66. // Returns the IR name to use for a label within its own scope, without any
  67. // prefix. Returns an empty string if there isn't a good name.
  68. auto GetUnscopedLabelFor(InstBlockId block_id) const -> llvm::StringRef;
  69. // Returns the IR name to use for a label, when referenced from a given scope.
  70. auto GetLabelFor(ScopeId scope_id, InstBlockId block_id) const -> std::string;
  71. // Returns true if the instruction has a specific name assigned.
  72. auto has_name(InstId inst_id) const -> bool {
  73. return static_cast<bool>(insts_[inst_id.index].second);
  74. }
  75. private:
  76. // A space in which unique names can be allocated.
  77. struct Namespace {
  78. // A result of a name lookup.
  79. struct NameResult;
  80. // A name in a namespace, which might be redirected to refer to another name
  81. // for disambiguation purposes.
  82. class Name {
  83. public:
  84. Name() : value_(nullptr) {}
  85. explicit Name(llvm::StringMapIterator<NameResult> it) : value_(&*it) {}
  86. explicit operator bool() const { return value_; }
  87. auto str() const -> llvm::StringRef;
  88. auto SetFallback(Name name) -> void { value_->second.fallback = name; }
  89. auto SetAmbiguous() -> void { value_->second.ambiguous = true; }
  90. private:
  91. llvm::StringMapEntry<NameResult>* value_ = nullptr;
  92. };
  93. struct NameResult {
  94. bool ambiguous = false;
  95. Name fallback = Name();
  96. };
  97. llvm::StringMap<NameResult> allocated = {};
  98. int unnamed_count = 0;
  99. auto AddNameUnchecked(llvm::StringRef name) -> Name {
  100. return Name(allocated.insert({name, NameResult()}).first);
  101. }
  102. auto AllocateName(const InstNamer& inst_namer,
  103. std::variant<LocId, uint64_t> loc_id_or_fingerprint,
  104. std::string name) -> Name;
  105. };
  106. // A named scope that contains named entities.
  107. struct Scope {
  108. Namespace::Name name;
  109. Namespace insts;
  110. Namespace labels;
  111. };
  112. // Helper class for naming a single instruction.
  113. class NamingContext;
  114. auto GetScopeInfo(ScopeId scope_id) -> Scope& {
  115. return scopes_[static_cast<int>(scope_id)];
  116. }
  117. auto GetScopeInfo(ScopeId scope_id) const -> const Scope& {
  118. return scopes_[static_cast<int>(scope_id)];
  119. }
  120. // For the given `IdT`, returns its start offset in the `ScopeId` space. Each
  121. // of `ScopeIdTypeEnum` is stored sequentially. When called with
  122. // `ScopeIdTypeEnum::None`, returns the full count of scopes.
  123. auto GetScopeIdOffset(ScopeIdTypeEnum id_enum) const -> int;
  124. auto AddBlockLabel(
  125. ScopeId scope_id, InstBlockId block_id, std::string name = "",
  126. std::variant<LocId, uint64_t> loc_id_or_fingerprint = LocId::None)
  127. -> void;
  128. // Finds and adds a suitable block label for the given SemIR instruction that
  129. // represents some kind of branch.
  130. auto AddBlockLabel(ScopeId scope_id, LocId loc_id, AnyBranch branch) -> void;
  131. auto CollectNamesInBlock(ScopeId scope_id, InstBlockId block_id) -> void;
  132. // Collects names from the provided block.
  133. //
  134. // This is essential for finding instructions that we need to name. If
  135. // `<unexpected>` occurs in output of valid SemIR, it often means the
  136. // instruction needs to be handled here. Note that `<unexpected>` can occur in
  137. // invalid SemIR just because we're unable to correctly walk the SemIR.
  138. auto CollectNamesInBlock(ScopeId scope_id, llvm::ArrayRef<InstId> block)
  139. -> void;
  140. auto CollectNamesInGeneric(ScopeId scope_id, GenericId generic_id) -> void;
  141. // Adds a scope and instructions to walk. Avoids recursion while allowing
  142. // the loop to below add more instructions during iteration. The new
  143. // instructions are queued such that they will be the next to be walked.
  144. // Internally that means they are reversed and added to the end of the vector,
  145. // since we pop from the back of the vector.
  146. auto QueueBlockInsts(llvm::SmallVector<std::pair<ScopeId, InstId>>& queue,
  147. ScopeId scope_id, llvm::ArrayRef<InstId> inst_ids)
  148. -> void;
  149. const File* sem_ir_;
  150. InstFingerprinter fingerprinter_;
  151. // The namespace for entity names. Names within this namespace are prefixed
  152. // with `@` in formatted SemIR.
  153. Namespace globals_;
  154. // The enclosing scope and name for each instruction, indexed by the InstId's
  155. // index.
  156. std::vector<std::pair<ScopeId, Namespace::Name>> insts_;
  157. // The enclosing scope and name for each block that might be a branch target,
  158. // indexed by the InstBlockId's index.
  159. std::vector<std::pair<ScopeId, Namespace::Name>> labels_;
  160. // The scopes corresponding to ScopeId values.
  161. std::vector<Scope> scopes_;
  162. // The scope IDs corresponding to generics. The vector indexes are the
  163. // GenericId index.
  164. std::vector<ScopeId> generic_scopes_;
  165. };
  166. } // namespace Carbon::SemIR
  167. #endif // CARBON_TOOLCHAIN_SEM_IR_INST_NAMER_H_