inst_namer.h 6.3 KB

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