inst_namer.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352
  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. #include "toolchain/sem_ir/inst_namer.h"
  5. #include <string>
  6. #include <utility>
  7. #include <variant>
  8. #include "common/ostream.h"
  9. #include "common/raw_string_ostream.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ADT/StableHashing.h"
  13. #include "toolchain/base/kind_switch.h"
  14. #include "toolchain/base/shared_value_stores.h"
  15. #include "toolchain/base/value_ids.h"
  16. #include "toolchain/lex/tokenized_buffer.h"
  17. #include "toolchain/parse/tree.h"
  18. #include "toolchain/sem_ir/cpp_overload_set.h"
  19. #include "toolchain/sem_ir/entity_with_params_base.h"
  20. #include "toolchain/sem_ir/function.h"
  21. #include "toolchain/sem_ir/ids.h"
  22. #include "toolchain/sem_ir/inst_kind.h"
  23. #include "toolchain/sem_ir/pattern.h"
  24. #include "toolchain/sem_ir/singleton_insts.h"
  25. #include "toolchain/sem_ir/specific_interface.h"
  26. #include "toolchain/sem_ir/specific_named_constraint.h"
  27. #include "toolchain/sem_ir/type_info.h"
  28. #include "toolchain/sem_ir/typed_insts.h"
  29. namespace Carbon::SemIR {
  30. class InstNamer::NamingContext {
  31. public:
  32. explicit NamingContext(InstNamer* inst_namer, InstNamer::ScopeId scope_id,
  33. InstId inst_id);
  34. // Names the single instruction. Use bound names where available. Otherwise,
  35. // assign a backup name.
  36. //
  37. // Insts with a type_id are required to add names; other insts may
  38. // optionally set a name. All insts may push other insts to be named.
  39. auto NameInst() -> void;
  40. private:
  41. // Adds the instruction's name.
  42. auto AddInstName(std::string name) -> void;
  43. // Adds the instruction's name by `NameId`.
  44. auto AddInstNameId(NameId name_id, llvm::StringRef suffix = "") -> void {
  45. AddInstName((sem_ir().names().GetIRBaseName(name_id) + suffix).str());
  46. }
  47. // Names an `IntType` or `FloatType`.
  48. auto AddIntOrFloatTypeName(char type_literal_prefix, InstId bit_width_id,
  49. llvm::StringRef suffix = "") -> void;
  50. // Names an `ImplWitnessTable` instruction.
  51. auto AddWitnessTableName(InstId witness_table_inst_id, std::string name)
  52. -> void;
  53. auto AddBlockLabel(ScopeId scope_id, InstBlockId block_id, std::string name,
  54. LocId loc_id) -> void {
  55. inst_namer_->AddBlockLabel(scope_id, block_id, name, loc_id);
  56. }
  57. // Pushes all instructions in a generic, by ID.
  58. auto PushGeneric(ScopeId scope_id, GenericId generic_id) -> void {
  59. inst_namer_->PushGeneric(scope_id, generic_id);
  60. }
  61. // Pushes all instructions in a block, by ID.
  62. auto PushBlockId(ScopeId scope_id, InstBlockId block_id) -> void {
  63. inst_namer_->PushBlockId(scope_id, block_id);
  64. }
  65. // Names the instruction as an entity. May push processing of the entity.
  66. template <typename EntityIdT>
  67. auto AddEntityNameAndMaybePush(EntityIdT id, llvm::StringRef suffix = "")
  68. -> void {
  69. AddInstName((inst_namer_->MaybePushEntity(id) + suffix).str());
  70. }
  71. auto sem_ir() -> const File& { return *inst_namer_->sem_ir_; }
  72. InstNamer* inst_namer_;
  73. ScopeId scope_id_;
  74. InstId inst_id_;
  75. Inst inst_;
  76. };
  77. InstNamer::InstNamer(const File* sem_ir, int total_ir_count)
  78. : sem_ir_(sem_ir), fingerprinter_(total_ir_count) {
  79. insts_.resize(sem_ir->insts().size(), {ScopeId::None, Namespace::Name()});
  80. labels_.resize(sem_ir->inst_blocks().size());
  81. scopes_.resize(GetScopeIdOffset(ScopeIdTypeEnum::None));
  82. generic_scopes_.resize(sem_ir->generics().size(), ScopeId::None);
  83. // We process the stack between each large block in order to reduce the
  84. // temporary size of the stack.
  85. auto process_stack = [&] {
  86. while (!inst_stack_.empty() || !inst_block_stack_.empty()) {
  87. if (inst_stack_.empty()) {
  88. auto [scope_id, block_id] = inst_block_stack_.pop_back_val();
  89. PushBlockInsts(scope_id, sem_ir_->inst_blocks().Get(block_id));
  90. }
  91. while (!inst_stack_.empty()) {
  92. auto [scope_id, inst_id] = inst_stack_.pop_back_val();
  93. NamingContext context(this, scope_id, inst_id);
  94. context.NameInst();
  95. }
  96. }
  97. };
  98. // Name each of the top-level scopes, in order. We use these as the roots of
  99. // walking the IR.
  100. PushBlockInsts(ScopeId::Constants, sem_ir->constants().array_ref());
  101. process_stack();
  102. PushBlockId(ScopeId::Imports, InstBlockId::Imports);
  103. process_stack();
  104. PushBlockId(ScopeId::File, sem_ir->top_inst_block_id());
  105. process_stack();
  106. // Global init won't have any other references, so we add it directly.
  107. if (sem_ir_->global_ctor_id().has_value()) {
  108. MaybePushEntity(sem_ir_->global_ctor_id());
  109. process_stack();
  110. }
  111. }
  112. auto InstNamer::GetScopeIdOffset(ScopeIdTypeEnum id_enum) const -> int {
  113. int offset = 0;
  114. // For each Id type, add the number of entities *above* its case; for example,
  115. // the offset for functions excludes the functions themselves. The fallthrough
  116. // handles summing to get uniqueness; order isn't special.
  117. switch (id_enum) {
  118. case ScopeIdTypeEnum::None:
  119. // `None` will be getting a full count of scopes.
  120. offset += sem_ir_->associated_constants().size();
  121. [[fallthrough]];
  122. case ScopeIdTypeEnum::For<AssociatedConstantId>:
  123. offset += sem_ir_->classes().size();
  124. [[fallthrough]];
  125. case ScopeIdTypeEnum::For<ClassId>:
  126. offset += sem_ir_->cpp_overload_sets().size();
  127. [[fallthrough]];
  128. case ScopeIdTypeEnum::For<CppOverloadSetId>:
  129. offset += sem_ir_->functions().size();
  130. [[fallthrough]];
  131. case ScopeIdTypeEnum::For<FunctionId>:
  132. offset += sem_ir_->impls().size();
  133. [[fallthrough]];
  134. case ScopeIdTypeEnum::For<ImplId>:
  135. offset += sem_ir_->interfaces().size();
  136. [[fallthrough]];
  137. case ScopeIdTypeEnum::For<InterfaceId>:
  138. offset += sem_ir_->named_constraints().size();
  139. [[fallthrough]];
  140. case ScopeIdTypeEnum::For<NamedConstraintId>:
  141. offset += sem_ir_->require_impls().size();
  142. [[fallthrough]];
  143. case ScopeIdTypeEnum::For<RequireImplsId>:
  144. offset += sem_ir_->specific_interfaces().size();
  145. [[fallthrough]];
  146. case ScopeIdTypeEnum::For<SpecificInterfaceId>:
  147. offset += sem_ir_->vtables().size();
  148. [[fallthrough]];
  149. case ScopeIdTypeEnum::For<VtableId>:
  150. // All type-specific scopes are offset by `FirstEntityScope`.
  151. offset += static_cast<int>(ScopeId::FirstEntityScope);
  152. return offset;
  153. default:
  154. CARBON_FATAL("Unexpected ScopeIdTypeEnum: {0}", id_enum);
  155. }
  156. }
  157. auto InstNamer::GetScopeName(ScopeId scope) const -> std::string {
  158. switch (scope) {
  159. case ScopeId::None:
  160. return "<no scope>";
  161. // These are treated as SemIR keywords.
  162. case ScopeId::File:
  163. return "file";
  164. case ScopeId::Imports:
  165. return "imports";
  166. case ScopeId::Constants:
  167. return "constants";
  168. // For everything else, use an @ prefix.
  169. default:
  170. return ("@" + GetScopeInfo(scope).name.GetFullName()).str();
  171. }
  172. }
  173. auto InstNamer::GetUnscopedNameFor(InstId inst_id) const -> llvm::StringRef {
  174. if (!inst_id.has_value()) {
  175. return "";
  176. }
  177. if (IsSingletonInstId(inst_id)) {
  178. return sem_ir_->insts().Get(inst_id).kind().ir_name();
  179. }
  180. auto index = sem_ir_->insts().GetRawIndex(inst_id);
  181. const auto& inst_name = insts_[index].second;
  182. return inst_name ? inst_name.GetFullName() : "";
  183. }
  184. auto InstNamer::GetNameFor(ScopeId scope_id, InstId inst_id) const
  185. -> std::string {
  186. if (!inst_id.has_value()) {
  187. return "invalid";
  188. }
  189. // Check for a builtin.
  190. if (IsSingletonInstId(inst_id)) {
  191. return sem_ir_->insts().Get(inst_id).kind().ir_name().str();
  192. }
  193. if (inst_id == SemIR::Namespace::PackageInstId) {
  194. return "package";
  195. }
  196. auto index = sem_ir_->insts().GetRawIndex(inst_id);
  197. const auto& [inst_scope, inst_name] = insts_[index];
  198. if (!inst_name) {
  199. // This should not happen in valid IR.
  200. RawStringOstream out;
  201. out << "<unexpected>." << inst_id;
  202. auto loc_id = sem_ir_->insts().GetCanonicalLocId(inst_id);
  203. // TODO: Consider handling other kinds.
  204. if (loc_id.kind() == LocId::Kind::NodeId) {
  205. const auto& tree = sem_ir_->parse_tree();
  206. auto token = tree.node_token(loc_id.node_id());
  207. out << ".loc" << tree.tokens().GetLineNumber(token) << "_"
  208. << tree.tokens().GetColumnNumber(token);
  209. }
  210. return out.TakeStr();
  211. }
  212. if (inst_scope == scope_id) {
  213. return ("%" + inst_name.GetFullName()).str();
  214. }
  215. return (GetScopeName(inst_scope) + ".%" + inst_name.GetFullName()).str();
  216. }
  217. auto InstNamer::GetUnscopedLabelFor(InstBlockId block_id) const
  218. -> llvm::StringRef {
  219. if (!block_id.has_value()) {
  220. return "";
  221. }
  222. const auto& label_name =
  223. labels_[sem_ir_->inst_blocks().GetRawIndex(block_id)].second;
  224. return label_name ? label_name.GetFullName() : "";
  225. }
  226. // Returns the IR name to use for a label, when referenced from a given scope.
  227. auto InstNamer::GetLabelFor(ScopeId scope_id, InstBlockId block_id) const
  228. -> std::string {
  229. if (!block_id.has_value()) {
  230. return "!invalid";
  231. }
  232. const auto& [label_scope, label_name] =
  233. labels_[sem_ir_->inst_blocks().GetRawIndex(block_id)];
  234. if (!label_name) {
  235. // This should not happen in valid IR.
  236. RawStringOstream out;
  237. out << "<unexpected instblockref " << block_id << ">";
  238. return out.TakeStr();
  239. }
  240. if (label_scope == scope_id) {
  241. return ("!" + label_name.GetFullName()).str();
  242. }
  243. return (GetScopeName(label_scope) + ".!" + label_name.GetFullName()).str();
  244. }
  245. auto InstNamer::Namespace::Name::GetFullName() const -> llvm::StringRef {
  246. if (!value_) {
  247. return "<null name>";
  248. }
  249. llvm::StringMapEntry<NameResult>* value = value_;
  250. while (value->second.ambiguous && value->second.fallback) {
  251. value = value->second.fallback.value_;
  252. }
  253. return value->first();
  254. }
  255. auto InstNamer::Namespace::Name::GetBaseName() const -> llvm::StringRef {
  256. if (!value_) {
  257. return "<null name>";
  258. }
  259. return value_->first().take_front(base_name_size_);
  260. }
  261. auto InstNamer::Namespace::AllocateName(
  262. const InstNamer& inst_namer,
  263. std::variant<LocId, uint64_t> loc_id_or_fingerprint, std::string name)
  264. -> Name {
  265. // The best (shortest) name for this instruction so far, and the current
  266. // name for it.
  267. Name best;
  268. Name current;
  269. const size_t base_name_size = name.size();
  270. // Add `name` as a name for this entity.
  271. auto add_name = [&](bool mark_ambiguous = true) {
  272. auto [it, added] = allocated_.insert({name, NameResult()});
  273. Name new_name = Name(it, base_name_size);
  274. if (!added) {
  275. if (mark_ambiguous) {
  276. // This name was allocated for a different instruction. Mark it as
  277. // ambiguous and keep looking for a name for this instruction.
  278. new_name.SetAmbiguous();
  279. }
  280. } else {
  281. if (!best) {
  282. best = new_name;
  283. } else {
  284. CARBON_CHECK(current);
  285. current.SetFallback(new_name);
  286. }
  287. current = new_name;
  288. }
  289. return added;
  290. };
  291. // Use the given name if it's available.
  292. if (!name.empty()) {
  293. add_name();
  294. }
  295. // Append location information to try to disambiguate.
  296. if (auto* loc_id = std::get_if<LocId>(&loc_id_or_fingerprint)) {
  297. *loc_id = inst_namer.sem_ir_->insts().GetCanonicalLocId(*loc_id);
  298. // TODO: Consider handling other kinds.
  299. if (loc_id->kind() == LocId::Kind::NodeId) {
  300. const auto& tree = inst_namer.sem_ir_->parse_tree();
  301. auto token = tree.node_token(loc_id->node_id());
  302. llvm::raw_string_ostream(name)
  303. << ".loc" << tree.tokens().GetLineNumber(token);
  304. add_name();
  305. llvm::raw_string_ostream(name)
  306. << "_" << tree.tokens().GetColumnNumber(token);
  307. add_name();
  308. }
  309. } else {
  310. uint64_t fingerprint = std::get<uint64_t>(loc_id_or_fingerprint);
  311. llvm::raw_string_ostream out(name);
  312. out << ".";
  313. // Include names with 3-6 characters from the fingerprint. Then fall back to
  314. // sequential numbering.
  315. for (int n : llvm::seq(1, 7)) {
  316. out.write_hex((fingerprint >> (64 - 4 * n)) & 0xF);
  317. if (n >= 3) {
  318. add_name();
  319. }
  320. }
  321. }
  322. // Append numbers until we find an available name.
  323. name += ".";
  324. auto name_size_without_counter = name.size();
  325. for (int counter = 1;; ++counter) {
  326. name.resize(name_size_without_counter);
  327. llvm::raw_string_ostream(name) << counter;
  328. if (add_name(/*mark_ambiguous=*/false)) {
  329. return best;
  330. }
  331. }
  332. }
  333. auto InstNamer::AddBlockLabel(
  334. ScopeId scope_id, InstBlockId block_id, std::string name,
  335. std::variant<LocId, uint64_t> loc_id_or_fingerprint) -> void {
  336. if (!block_id.has_value() ||
  337. labels_[sem_ir_->inst_blocks().GetRawIndex(block_id)].second) {
  338. return;
  339. }
  340. if (auto* loc_id = std::get_if<LocId>(&loc_id_or_fingerprint);
  341. loc_id && !loc_id->has_value()) {
  342. if (const auto& block = sem_ir_->inst_blocks().Get(block_id);
  343. !block.empty()) {
  344. loc_id_or_fingerprint = LocId(block.front());
  345. }
  346. }
  347. labels_[sem_ir_->inst_blocks().GetRawIndex(block_id)] = {
  348. scope_id, GetScopeInfo(scope_id).labels.AllocateName(
  349. *this, loc_id_or_fingerprint, std::move(name))};
  350. }
  351. // Provides names for `AddBlockLabel`.
  352. struct BranchNames {
  353. // Returns names for a branching parse node, or nullopt if not a branch.
  354. static auto For(Parse::NodeKind node_kind) -> std::optional<BranchNames> {
  355. switch (node_kind) {
  356. case Parse::NodeKind::ForHeaderStart:
  357. return {{.prefix = "for", .branch = "next"}};
  358. case Parse::NodeKind::ForHeader:
  359. return {{.prefix = "for", .branch_if = "body", .branch = "done"}};
  360. case Parse::NodeKind::IfExprIf:
  361. return {{.prefix = "if.expr",
  362. .branch_if = "then",
  363. .branch = "else",
  364. .branch_with_arg = "result"}};
  365. case Parse::NodeKind::IfCondition:
  366. return {{.prefix = "if", .branch_if = "then", .branch = "else"}};
  367. case Parse::NodeKind::IfStatement:
  368. return {{.prefix = "if", .branch = "done"}};
  369. case Parse::NodeKind::ShortCircuitOperandAnd:
  370. return {
  371. {.prefix = "and", .branch_if = "rhs", .branch_with_arg = "result"}};
  372. case Parse::NodeKind::ShortCircuitOperandOr:
  373. return {
  374. {.prefix = "or", .branch_if = "rhs", .branch_with_arg = "result"}};
  375. case Parse::NodeKind::WhileConditionStart:
  376. return {{.prefix = "while", .branch = "cond"}};
  377. case Parse::NodeKind::WhileCondition:
  378. return {{.prefix = "while", .branch_if = "body", .branch = "done"}};
  379. default:
  380. return std::nullopt;
  381. }
  382. }
  383. // Returns the provided suffix for the instruction kind, or an empty string.
  384. auto GetSuffix(InstKind inst_kind) -> llvm::StringLiteral {
  385. switch (inst_kind) {
  386. case BranchIf::Kind:
  387. return branch_if;
  388. case Branch::Kind:
  389. return branch;
  390. case BranchWithArg::Kind:
  391. return branch_with_arg;
  392. default:
  393. return "";
  394. }
  395. }
  396. // The kind of branch, based on the node kind.
  397. llvm::StringLiteral prefix;
  398. // For labeling branch instruction kinds. Only expected kinds need a value;
  399. // the empty string is for unexpected kinds.
  400. llvm::StringLiteral branch_if = "";
  401. llvm::StringLiteral branch = "";
  402. llvm::StringLiteral branch_with_arg = "";
  403. };
  404. // Finds and adds a suitable block label for the given SemIR instruction that
  405. // represents some kind of branch.
  406. auto InstNamer::AddBlockLabel(ScopeId scope_id, LocId loc_id, AnyBranch branch)
  407. -> void {
  408. std::string label;
  409. loc_id = sem_ir_->insts().GetCanonicalLocId(loc_id);
  410. if (loc_id.node_id().has_value()) {
  411. if (auto names = BranchNames::For(
  412. sem_ir_->parse_tree().node_kind(loc_id.node_id()))) {
  413. if (auto suffix = names->GetSuffix(branch.kind); !suffix.empty()) {
  414. label = llvm::formatv("{0}.{1}", names->prefix, suffix);
  415. } else {
  416. label =
  417. llvm::formatv("{0}.<unexpected {1}>", names->prefix, branch.kind);
  418. }
  419. }
  420. }
  421. AddBlockLabel(scope_id, branch.target_id, label, loc_id);
  422. }
  423. auto InstNamer::PushBlockId(ScopeId scope_id, InstBlockId block_id) -> void {
  424. if (block_id.has_value()) {
  425. inst_block_stack_.push_back({scope_id, block_id});
  426. }
  427. }
  428. auto InstNamer::PushBlockInsts(ScopeId scope_id,
  429. llvm::ArrayRef<InstId> inst_ids) -> void {
  430. for (auto inst_id : llvm::reverse(inst_ids)) {
  431. if (inst_id.has_value() && !IsSingletonInstId(inst_id)) {
  432. inst_stack_.push_back(std::make_pair(scope_id, inst_id));
  433. }
  434. }
  435. }
  436. auto InstNamer::PushGeneric(ScopeId scope_id, GenericId generic_id) -> void {
  437. if (!generic_id.has_value()) {
  438. return;
  439. }
  440. generic_scopes_[sem_ir_->generics().GetRawIndex(generic_id)] = scope_id;
  441. const auto& generic = sem_ir_->generics().Get(generic_id);
  442. // Push blocks in reverse order.
  443. PushBlockId(scope_id, generic.definition_block_id);
  444. PushBlockId(scope_id, generic.decl_block_id);
  445. }
  446. auto InstNamer::PushEntity(AssociatedConstantId associated_constant_id,
  447. ScopeId scope_id, Scope& scope) -> void {
  448. const auto& assoc_const =
  449. sem_ir_->associated_constants().Get(associated_constant_id);
  450. scope.name = globals_.AllocateName(
  451. *this, LocId(assoc_const.decl_id),
  452. sem_ir_->names().GetIRBaseName(assoc_const.name_id).str());
  453. // Push blocks in reverse order.
  454. PushGeneric(scope_id, assoc_const.generic_id);
  455. }
  456. auto InstNamer::PushEntity(ClassId class_id, ScopeId scope_id, Scope& scope)
  457. -> void {
  458. const auto& class_info = sem_ir_->classes().Get(class_id);
  459. LocId class_loc(class_info.latest_decl_id());
  460. scope.name = globals_.AllocateName(
  461. *this, class_loc,
  462. sem_ir_->names().GetIRBaseName(class_info.name_id).str());
  463. AddBlockLabel(scope_id, class_info.body_block_id, "class", class_loc);
  464. PushGeneric(scope_id, class_info.generic_id);
  465. // Push blocks in reverse order.
  466. PushBlockId(scope_id, class_info.body_block_id);
  467. PushBlockId(scope_id, class_info.pattern_block_id);
  468. }
  469. auto InstNamer::GetNameForParentNameScope(NameScopeId name_scope_id)
  470. -> llvm::StringRef {
  471. if (!name_scope_id.has_value()) {
  472. return "";
  473. }
  474. auto scope_inst =
  475. sem_ir_->insts().Get(sem_ir_->name_scopes().Get(name_scope_id).inst_id());
  476. CARBON_KIND_SWITCH(scope_inst) {
  477. case CARBON_KIND(ClassDecl class_decl): {
  478. return MaybePushEntity(class_decl.class_id);
  479. }
  480. case CARBON_KIND(ImplDecl impl): {
  481. return MaybePushEntity(impl.impl_id);
  482. }
  483. case CARBON_KIND(InterfaceDecl interface): {
  484. return MaybePushEntity(interface.interface_id);
  485. }
  486. case CARBON_KIND(NamedConstraintDecl named_constraint): {
  487. return MaybePushEntity(named_constraint.named_constraint_id);
  488. }
  489. case SemIR::Namespace::Kind: {
  490. // Only prefix type scopes.
  491. return "";
  492. }
  493. default: {
  494. return "<unsupported scope>";
  495. }
  496. }
  497. }
  498. auto InstNamer::PushEntity(FunctionId function_id, ScopeId scope_id,
  499. Scope& scope) -> void {
  500. const auto& fn = sem_ir_->functions().Get(function_id);
  501. LocId fn_loc(fn.latest_decl_id());
  502. auto scope_prefix = GetNameForParentNameScope(fn.parent_scope_id);
  503. scope.name = globals_.AllocateName(
  504. *this, fn_loc,
  505. llvm::formatv("{0}{1}{2}", scope_prefix, scope_prefix.empty() ? "" : ".",
  506. sem_ir_->names().GetIRBaseName(fn.name_id)));
  507. if (!fn.body_block_ids.empty()) {
  508. AddBlockLabel(scope_id, fn.body_block_ids.front(), "entry", fn_loc);
  509. }
  510. // Push blocks in reverse order.
  511. PushGeneric(scope_id, fn.generic_id);
  512. for (auto block_id : llvm::reverse(fn.body_block_ids)) {
  513. PushBlockId(scope_id, block_id);
  514. }
  515. PushBlockId(scope_id, fn.pattern_block_id);
  516. PushBlockId(scope_id, fn.call_params_id);
  517. }
  518. auto InstNamer::PushEntity(RequireImplsId require_impls_id, ScopeId scope_id,
  519. Scope& scope) -> void {
  520. const auto& require = sem_ir_->require_impls().Get(require_impls_id);
  521. LocId require_loc(require.decl_id);
  522. auto scope_prefix = GetNameForParentNameScope(require.parent_scope_id);
  523. scope.name = globals_.AllocateName(
  524. *this, require_loc,
  525. // TODO: Include the Interface being required if there's only one, instead
  526. // of the index.
  527. llvm::formatv("{0}{1}require{2}", scope_prefix,
  528. scope_prefix.empty() ? "" : ".", require_impls_id.index));
  529. auto decl = sem_ir_->insts().GetAs<SemIR::RequireImplsDecl>(require.decl_id);
  530. AddBlockLabel(scope_id, decl.decl_block_id, "require", require_loc);
  531. // Push blocks in reverse order.
  532. PushGeneric(scope_id, require.generic_id);
  533. }
  534. auto InstNamer::PushEntity(CppOverloadSetId cpp_overload_set_id,
  535. ScopeId /*scope_id*/, Scope& scope) -> void {
  536. const CppOverloadSet& overload_set =
  537. sem_ir_->cpp_overload_sets().Get(cpp_overload_set_id);
  538. uint64_t fingerprint =
  539. fingerprinter_.GetOrCompute(sem_ir_, cpp_overload_set_id);
  540. auto scope_prefix = GetNameForParentNameScope(overload_set.parent_scope_id);
  541. scope.name = globals_.AllocateName(
  542. *this, fingerprint,
  543. llvm::formatv("{0}{1}{2}.cpp_overload_set", scope_prefix,
  544. scope_prefix.empty() ? "" : ".",
  545. sem_ir_->names().GetIRBaseName(overload_set.name_id)));
  546. }
  547. auto InstNamer::PushEntity(ImplId impl_id, ScopeId scope_id, Scope& scope)
  548. -> void {
  549. const auto& impl = sem_ir_->impls().Get(impl_id);
  550. auto impl_fingerprint = fingerprinter_.GetOrCompute(sem_ir_, impl_id);
  551. llvm::StringRef self_name;
  552. auto self_const_id =
  553. sem_ir_->constant_values().GetConstantInstId(impl.self_id);
  554. auto index = sem_ir_->insts().GetRawIndex(self_const_id);
  555. if (IsSingletonInstId(self_const_id)) {
  556. self_name = sem_ir_->insts().Get(self_const_id).kind().ir_name();
  557. } else if (const auto& inst_name = insts_[index].second) {
  558. self_name = inst_name.GetBaseName();
  559. } else {
  560. self_name = "<unexpected self>";
  561. }
  562. llvm::StringRef interface_name;
  563. if (impl.interface.interface_id.has_value()) {
  564. interface_name = MaybePushEntity(impl.interface.interface_id);
  565. } else {
  566. interface_name = "<error>";
  567. }
  568. scope.name = globals_.AllocateName(
  569. *this, impl_fingerprint,
  570. llvm::formatv("{0}.as.{1}.impl", self_name, interface_name));
  571. AddBlockLabel(scope_id, impl.body_block_id, "impl", impl_fingerprint);
  572. // Push blocks in reverse order.
  573. PushGeneric(scope_id, impl.generic_id);
  574. PushBlockId(scope_id, impl.body_block_id);
  575. PushBlockId(scope_id, impl.pattern_block_id);
  576. }
  577. auto InstNamer::PushEntity(InterfaceId interface_id, ScopeId scope_id,
  578. Scope& scope) -> void {
  579. const auto& interface = sem_ir_->interfaces().Get(interface_id);
  580. LocId interface_loc(interface.latest_decl_id());
  581. scope.name = globals_.AllocateName(
  582. *this, interface_loc,
  583. sem_ir_->names().GetIRBaseName(interface.name_id).str());
  584. AddBlockLabel(scope_id, interface.body_block_id, "interface", interface_loc);
  585. // Push blocks in reverse order.
  586. PushGeneric(scope_id, interface.generic_id);
  587. PushBlockId(scope_id, interface.body_block_id);
  588. PushBlockId(scope_id, interface.pattern_block_id);
  589. }
  590. auto InstNamer::PushEntity(NamedConstraintId named_constraint_id,
  591. ScopeId scope_id, Scope& scope) -> void {
  592. const auto& constraint =
  593. sem_ir_->named_constraints().Get(named_constraint_id);
  594. LocId constraint_loc(constraint.latest_decl_id());
  595. scope.name = globals_.AllocateName(
  596. *this, constraint_loc,
  597. sem_ir_->names().GetIRBaseName(constraint.name_id).str());
  598. AddBlockLabel(scope_id, constraint.body_block_id, "constraint",
  599. constraint_loc);
  600. // Push blocks in reverse order.
  601. PushGeneric(scope_id, constraint.generic_id);
  602. PushBlockId(scope_id, constraint.body_block_id);
  603. PushBlockId(scope_id, constraint.pattern_block_id);
  604. }
  605. auto InstNamer::PushEntity(VtableId vtable_id, ScopeId /*scope_id*/,
  606. Scope& scope) -> void {
  607. const auto& vtable = sem_ir_->vtables().Get(vtable_id);
  608. const auto& class_info = sem_ir_->classes().Get(vtable.class_id);
  609. LocId vtable_loc(class_info.latest_decl_id());
  610. scope.name = globals_.AllocateName(
  611. *this, vtable_loc,
  612. sem_ir_->names().GetIRBaseName(class_info.name_id).str() + ".vtable");
  613. // TODO: Add support for generic vtables here and elsewhere.
  614. // PushGeneric(scope_id, vtable_info.generic_id);
  615. }
  616. InstNamer::NamingContext::NamingContext(InstNamer* inst_namer,
  617. InstNamer::ScopeId scope_id,
  618. InstId inst_id)
  619. : inst_namer_(inst_namer),
  620. scope_id_(scope_id),
  621. inst_id_(inst_id),
  622. inst_(sem_ir().insts().Get(inst_id)) {}
  623. auto InstNamer::NamingContext::AddInstName(std::string name) -> void {
  624. auto index = sem_ir().insts().GetRawIndex(inst_id_);
  625. ScopeId old_scope_id = inst_namer_->insts_[index].first;
  626. if (old_scope_id == ScopeId::None) {
  627. std::variant<LocId, uint64_t> loc_id_or_fingerprint = LocId::None;
  628. if (scope_id_ == ScopeId::Constants || scope_id_ == ScopeId::Imports) {
  629. loc_id_or_fingerprint =
  630. inst_namer_->fingerprinter_.GetOrCompute(&sem_ir(), inst_id_);
  631. } else {
  632. loc_id_or_fingerprint = LocId(inst_id_);
  633. }
  634. auto scoped_name = inst_namer_->GetScopeInfo(scope_id_).insts.AllocateName(
  635. *inst_namer_, loc_id_or_fingerprint, std::move(name));
  636. inst_namer_->insts_[index] = {scope_id_, scoped_name};
  637. } else {
  638. CARBON_CHECK(old_scope_id == scope_id_,
  639. "Attempting to name inst in multiple scopes");
  640. }
  641. }
  642. auto InstNamer::NamingContext::AddIntOrFloatTypeName(char type_literal_prefix,
  643. InstId bit_width_id,
  644. llvm::StringRef suffix)
  645. -> void {
  646. RawStringOstream out;
  647. out << type_literal_prefix;
  648. if (auto bit_width = sem_ir().insts().TryGetAs<IntValue>(bit_width_id)) {
  649. out << sem_ir().ints().Get(bit_width->int_id);
  650. } else {
  651. out << "N";
  652. }
  653. out << suffix;
  654. AddInstName(out.TakeStr());
  655. }
  656. auto InstNamer::NamingContext::AddWitnessTableName(InstId witness_table_inst_id,
  657. std::string name) -> void {
  658. auto witness_table =
  659. sem_ir().insts().TryGetAs<ImplWitnessTable>(witness_table_inst_id);
  660. if (!witness_table || !witness_table->impl_id.has_value()) {
  661. // TODO: If `impl_id` is None, the witness comes from a facet value. Can we
  662. // get the interface names from it? Store the facet value instruction in the
  663. // table?
  664. AddInstName(name);
  665. return;
  666. }
  667. const auto& impl = sem_ir().impls().Get(witness_table->impl_id);
  668. auto name_id = sem_ir().interfaces().Get(impl.interface.interface_id).name_id;
  669. std::string suffix = llvm::formatv(".{}", name);
  670. AddInstNameId(name_id, suffix);
  671. }
  672. auto InstNamer::NamingContext::NameInst() -> void {
  673. CARBON_KIND_SWITCH(inst_) {
  674. case AddrOf::Kind: {
  675. AddInstName("addr");
  676. return;
  677. }
  678. case ArrayType::Kind: {
  679. // TODO: Can we figure out the name of the type this is an array of?
  680. AddInstName("array_type");
  681. return;
  682. }
  683. case CARBON_KIND(AssociatedConstantDecl inst): {
  684. AddEntityNameAndMaybePush(inst.assoc_const_id);
  685. PushBlockId(inst_namer_->GetScopeFor(inst.assoc_const_id),
  686. inst.decl_block_id);
  687. return;
  688. }
  689. case CARBON_KIND(AssociatedEntity inst): {
  690. RawStringOstream out;
  691. out << "assoc" << inst.index.index;
  692. AddInstName(out.TakeStr());
  693. return;
  694. }
  695. case CARBON_KIND(AssociatedEntityType inst): {
  696. AddEntityNameAndMaybePush(inst.interface_id, ".assoc_type");
  697. return;
  698. }
  699. case AliasBinding::Kind:
  700. case RefBinding::Kind:
  701. case SymbolicBinding::Kind:
  702. case ValueBinding::Kind:
  703. case ExportDecl::Kind: {
  704. auto inst = inst_.As<AnyBindingOrExportDecl>();
  705. AddInstNameId(sem_ir().entity_names().Get(inst.entity_name_id).name_id);
  706. return;
  707. }
  708. case RefBindingPattern::Kind:
  709. case SymbolicBindingPattern::Kind:
  710. case ValueBindingPattern::Kind: {
  711. auto inst = inst_.As<AnyBindingPattern>();
  712. auto name_id = NameId::Underscore;
  713. if (inst.entity_name_id.has_value()) {
  714. name_id = sem_ir().entity_names().Get(inst.entity_name_id).name_id;
  715. }
  716. AddInstNameId(name_id, ".patt");
  717. return;
  718. }
  719. case CARBON_KIND(BoolLiteral inst): {
  720. if (inst.value.ToBool()) {
  721. AddInstName("true");
  722. } else {
  723. AddInstName("false");
  724. }
  725. return;
  726. }
  727. case CARBON_KIND(BoundMethod inst): {
  728. auto type_id = sem_ir().insts().Get(inst.function_decl_id).type_id();
  729. if (auto fn_ty = sem_ir().types().TryGetAs<FunctionType>(type_id)) {
  730. AddEntityNameAndMaybePush(fn_ty->function_id, ".bound");
  731. } else {
  732. AddInstName("bound_method");
  733. }
  734. return;
  735. }
  736. case Branch::Kind:
  737. case BranchIf::Kind:
  738. case BranchWithArg::Kind: {
  739. auto branch = inst_.As<AnyBranch>();
  740. inst_namer_->AddBlockLabel(scope_id_, LocId(inst_id_), branch);
  741. return;
  742. }
  743. case CARBON_KIND(Call inst): {
  744. auto callee = GetCallee(sem_ir(), inst.callee_id);
  745. if (auto* fn = std::get_if<CalleeFunction>(&callee)) {
  746. AddEntityNameAndMaybePush(fn->function_id, ".call");
  747. return;
  748. }
  749. AddInstName("");
  750. return;
  751. }
  752. case CARBON_KIND(ClassDecl inst): {
  753. AddEntityNameAndMaybePush(inst.class_id, ".decl");
  754. auto class_scope_id = inst_namer_->GetScopeFor(inst.class_id);
  755. PushBlockId(class_scope_id, inst.decl_block_id);
  756. return;
  757. }
  758. case CARBON_KIND(ClassType inst): {
  759. if (auto type_info = RecognizedTypeInfo::ForType(sem_ir(), inst);
  760. type_info.is_valid()) {
  761. RawStringOstream out;
  762. if (type_info.PrintLiteral(sem_ir(), out)) {
  763. AddInstName(out.TakeStr());
  764. return;
  765. }
  766. }
  767. AddEntityNameAndMaybePush(inst.class_id);
  768. return;
  769. }
  770. case CompleteTypeWitness::Kind: {
  771. // TODO: Can we figure out the name of the type this is a witness for?
  772. AddInstName("complete_type");
  773. return;
  774. }
  775. case CARBON_KIND(VtableDecl inst): {
  776. const auto& vtable = sem_ir().vtables().Get(inst.vtable_id);
  777. inst_namer_->MaybePushEntity(inst.vtable_id);
  778. if (inst_namer_->GetScopeFor(vtable.class_id) == scope_id_) {
  779. inst_namer_->MaybePushEntity(vtable.class_id);
  780. AddInstName("vtable_decl");
  781. } else {
  782. AddEntityNameAndMaybePush(vtable.class_id, ".vtable_decl");
  783. }
  784. return;
  785. }
  786. case CARBON_KIND(VtablePtr inst): {
  787. const auto& vtable = sem_ir().vtables().Get(inst.vtable_id);
  788. inst_namer_->MaybePushEntity(inst.vtable_id);
  789. AddEntityNameAndMaybePush(vtable.class_id, ".vtable_ptr");
  790. return;
  791. }
  792. case ConstType::Kind: {
  793. // TODO: Can we figure out the name of the type argument?
  794. AddInstName("const");
  795. return;
  796. }
  797. case CARBON_KIND(CppTemplateNameType inst): {
  798. AddInstNameId(sem_ir().entity_names().Get(inst.name_id).name_id, ".type");
  799. return;
  800. }
  801. case CppWitness::Kind: {
  802. AddInstName("cpp_witness");
  803. return;
  804. }
  805. case CARBON_KIND(FacetAccessType inst): {
  806. auto name_id = SemIR::NameId::None;
  807. if (auto name =
  808. sem_ir().insts().TryGetAs<NameRef>(inst.facet_value_inst_id)) {
  809. name_id = name->name_id;
  810. } else if (auto bind = sem_ir().insts().TryGetAs<SymbolicBinding>(
  811. inst.facet_value_inst_id)) {
  812. name_id = sem_ir().entity_names().Get(bind->entity_name_id).name_id;
  813. }
  814. if (name_id.has_value()) {
  815. AddInstNameId(name_id, ".as_type");
  816. } else {
  817. AddInstName("as_type");
  818. }
  819. return;
  820. }
  821. case CARBON_KIND(SymbolicBindingType inst): {
  822. auto bind =
  823. sem_ir().insts().GetAs<SymbolicBinding>(inst.facet_value_inst_id);
  824. auto name_id = sem_ir().entity_names().Get(bind.entity_name_id).name_id;
  825. if (name_id.has_value()) {
  826. AddInstNameId(name_id, ".binding.as_type");
  827. } else {
  828. AddInstName("binding.as_type");
  829. }
  830. return;
  831. }
  832. case CARBON_KIND(FacetType inst): {
  833. const auto& facet_type_info =
  834. sem_ir().facet_types().Get(inst.facet_type_id);
  835. bool has_where = facet_type_info.other_requirements ||
  836. !facet_type_info.builtin_constraint_mask.empty() ||
  837. !facet_type_info.self_impls_constraints.empty() ||
  838. !facet_type_info.self_impls_named_constraints.empty() ||
  839. !facet_type_info.rewrite_constraints.empty();
  840. if (facet_type_info.extend_constraints.size() == 1 &&
  841. facet_type_info.extend_named_constraints.empty()) {
  842. AddEntityNameAndMaybePush(
  843. facet_type_info.extend_constraints.front().interface_id,
  844. has_where ? "_where.type" : ".type");
  845. } else if (facet_type_info.extend_named_constraints.size() == 1 &&
  846. facet_type_info.extend_constraints.empty()) {
  847. AddEntityNameAndMaybePush(
  848. facet_type_info.extend_named_constraints.front()
  849. .named_constraint_id,
  850. has_where ? "_where.type" : ".type");
  851. } else if (facet_type_info.extend_constraints.empty() &&
  852. facet_type_info.extend_named_constraints.empty()) {
  853. AddInstName(has_where ? "type_where" : "type");
  854. } else {
  855. AddInstName("facet_type");
  856. }
  857. return;
  858. }
  859. case CARBON_KIND(FacetValue inst): {
  860. if (auto facet_type =
  861. sem_ir().types().TryGetAs<FacetType>(inst.type_id)) {
  862. const auto& facet_type_info =
  863. sem_ir().facet_types().Get(facet_type->facet_type_id);
  864. if (auto single = facet_type_info.TryAsSingleExtend()) {
  865. CARBON_KIND_SWITCH(*single) {
  866. case CARBON_KIND(SemIR::SpecificInterface interface): {
  867. AddEntityNameAndMaybePush(interface.interface_id, ".facet");
  868. break;
  869. }
  870. case CARBON_KIND(SemIR::SpecificNamedConstraint constraint): {
  871. AddEntityNameAndMaybePush(constraint.named_constraint_id,
  872. ".facet");
  873. break;
  874. }
  875. }
  876. return;
  877. }
  878. }
  879. AddInstName("facet_value");
  880. return;
  881. }
  882. case CARBON_KIND(FloatType inst): {
  883. AddIntOrFloatTypeName('f', inst.bit_width_id);
  884. return;
  885. }
  886. case FloatLiteralValue::Kind:
  887. case FloatValue::Kind: {
  888. AddInstName("float");
  889. return;
  890. }
  891. case CARBON_KIND(FunctionDecl inst): {
  892. AddEntityNameAndMaybePush(inst.function_id, ".decl");
  893. auto function_scope_id = inst_namer_->GetScopeFor(inst.function_id);
  894. PushBlockId(function_scope_id, inst.decl_block_id);
  895. return;
  896. }
  897. case CARBON_KIND(FunctionType inst): {
  898. AddEntityNameAndMaybePush(inst.function_id, ".type");
  899. return;
  900. }
  901. case CARBON_KIND(CppOverloadSetValue inst): {
  902. AddEntityNameAndMaybePush(inst.overload_set_id, ".value");
  903. return;
  904. }
  905. case CARBON_KIND(CppOverloadSetType inst): {
  906. AddEntityNameAndMaybePush(inst.overload_set_id, ".type");
  907. return;
  908. }
  909. case CARBON_KIND(GenericClassType inst): {
  910. AddEntityNameAndMaybePush(inst.class_id, ".type");
  911. return;
  912. }
  913. case CARBON_KIND(GenericInterfaceType inst): {
  914. AddEntityNameAndMaybePush(inst.interface_id, ".type");
  915. return;
  916. }
  917. case CARBON_KIND(GenericNamedConstraintType inst): {
  918. AddEntityNameAndMaybePush(inst.named_constraint_id, ".type");
  919. return;
  920. }
  921. case CARBON_KIND(ImplDecl inst): {
  922. // `impl` declarations aren't named because they aren't added to any
  923. // namespace, and so aren't referenced directly.
  924. inst_namer_->MaybePushEntity(inst.impl_id);
  925. PushBlockId(inst_namer_->GetScopeFor(inst.impl_id), inst.decl_block_id);
  926. return;
  927. }
  928. case CARBON_KIND(LookupImplWitness inst): {
  929. const auto& interface =
  930. sem_ir().specific_interfaces().Get(inst.query_specific_interface_id);
  931. AddEntityNameAndMaybePush(interface.interface_id, ".lookup_impl_witness");
  932. return;
  933. }
  934. case CARBON_KIND(ImplWitness inst): {
  935. AddWitnessTableName(inst.witness_table_id, "impl_witness");
  936. return;
  937. }
  938. case CARBON_KIND(ImplWitnessAccess inst): {
  939. // TODO: Include information about the impl?
  940. RawStringOstream out;
  941. out << "impl.elem" << inst.index.index;
  942. AddInstName(out.TakeStr());
  943. return;
  944. }
  945. case CARBON_KIND(ImplWitnessAccessSubstituted inst): {
  946. // TODO: Include information about the impl?
  947. RawStringOstream out;
  948. auto access = sem_ir().insts().GetAs<ImplWitnessAccess>(
  949. inst.impl_witness_access_id);
  950. out << "impl.elem" << access.index.index << ".subst";
  951. AddInstName(out.TakeStr());
  952. return;
  953. }
  954. case ImplWitnessAssociatedConstant::Kind: {
  955. AddInstName("impl_witness_assoc_constant");
  956. return;
  957. }
  958. case ImplWitnessTable::Kind: {
  959. AddWitnessTableName(inst_id_, "impl_witness_table");
  960. return;
  961. }
  962. case ImportCppDecl::Kind: {
  963. AddInstName("Cpp.import_cpp");
  964. return;
  965. }
  966. case CARBON_KIND(ImportDecl inst): {
  967. if (inst.package_id.has_value()) {
  968. AddInstNameId(inst.package_id, ".import");
  969. } else {
  970. AddInstName("default.import");
  971. }
  972. return;
  973. }
  974. case ImportRefUnloaded::Kind:
  975. case ImportRefLoaded::Kind: {
  976. // Build the base import name: <package>.<entity-name>
  977. RawStringOstream out;
  978. auto inst = inst_.As<AnyImportRef>();
  979. auto import_ir_inst =
  980. sem_ir().import_ir_insts().Get(inst.import_ir_inst_id);
  981. const auto& import_ir =
  982. *sem_ir().import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  983. auto package_id = import_ir.package_id();
  984. if (auto ident_id = package_id.AsIdentifierId(); ident_id.has_value()) {
  985. out << import_ir.identifiers().Get(ident_id);
  986. } else {
  987. out << package_id.AsSpecialName();
  988. }
  989. out << ".";
  990. // Add entity name if available.
  991. if (inst.entity_name_id.has_value()) {
  992. auto name_id = sem_ir().entity_names().Get(inst.entity_name_id).name_id;
  993. out << sem_ir().names().GetIRBaseName(name_id);
  994. } else {
  995. out << "import_ref";
  996. }
  997. AddInstName(out.TakeStr());
  998. // When building import refs, we frequently add instructions without
  999. // a block. Constants that refer to them need to be separately
  1000. // named.
  1001. auto const_id = sem_ir().constant_values().Get(inst_id_);
  1002. if (const_id.has_value() && const_id.is_concrete()) {
  1003. auto const_inst_id = sem_ir().constant_values().GetInstId(const_id);
  1004. auto index = sem_ir().insts().GetRawIndex(const_inst_id);
  1005. if (!inst_namer_->insts_[index].second) {
  1006. inst_namer_->PushBlockInsts(ScopeId::Imports, const_inst_id);
  1007. }
  1008. }
  1009. return;
  1010. }
  1011. case CARBON_KIND(InstValue inst): {
  1012. inst_namer_->PushBlockInsts(scope_id_, inst.inst_id);
  1013. AddInstName(
  1014. ("inst." + sem_ir().insts().Get(inst.inst_id).kind().ir_name())
  1015. .str());
  1016. return;
  1017. }
  1018. case CARBON_KIND(InterfaceDecl inst): {
  1019. AddEntityNameAndMaybePush(inst.interface_id, ".decl");
  1020. auto interface_scope_id = inst_namer_->GetScopeFor(inst.interface_id);
  1021. PushBlockId(interface_scope_id, inst.decl_block_id);
  1022. return;
  1023. }
  1024. case CARBON_KIND(IntType inst): {
  1025. AddIntOrFloatTypeName(inst.int_kind == IntKind::Signed ? 'i' : 'u',
  1026. inst.bit_width_id, ".builtin");
  1027. return;
  1028. }
  1029. case CARBON_KIND(IntValue inst): {
  1030. RawStringOstream out;
  1031. out << "int_" << sem_ir().ints().Get(inst.int_id);
  1032. AddInstName(out.TakeStr());
  1033. return;
  1034. }
  1035. case CARBON_KIND(NameBindingDecl inst): {
  1036. PushBlockId(scope_id_, inst.pattern_block_id);
  1037. return;
  1038. }
  1039. case CARBON_KIND(NamedConstraintDecl inst): {
  1040. AddEntityNameAndMaybePush(inst.named_constraint_id, ".decl");
  1041. auto interface_scope_id =
  1042. inst_namer_->GetScopeFor(inst.named_constraint_id);
  1043. PushBlockId(interface_scope_id, inst.decl_block_id);
  1044. return;
  1045. }
  1046. case CARBON_KIND(NameRef inst): {
  1047. AddInstNameId(inst.name_id, ".ref");
  1048. return;
  1049. }
  1050. // The namespace is specified here due to the name conflict.
  1051. case CARBON_KIND(SemIR::Namespace inst): {
  1052. AddInstNameId(sem_ir().name_scopes().Get(inst.name_scope_id).name_id());
  1053. return;
  1054. }
  1055. case OutParam::Kind:
  1056. case RefParam::Kind:
  1057. case ValueParam::Kind: {
  1058. AddInstNameId(inst_.As<AnyParam>().pretty_name_id, ".param");
  1059. return;
  1060. }
  1061. case OutParamPattern::Kind:
  1062. case RefParamPattern::Kind:
  1063. case ValueParamPattern::Kind:
  1064. case VarParamPattern::Kind: {
  1065. AddInstNameId(GetPrettyNameFromPatternId(sem_ir(), inst_id_),
  1066. ".param_patt");
  1067. return;
  1068. }
  1069. case PatternType::Kind: {
  1070. AddInstName("pattern_type");
  1071. return;
  1072. }
  1073. case PointerType::Kind: {
  1074. AddInstName("ptr");
  1075. return;
  1076. }
  1077. case RequireCompleteType::Kind: {
  1078. AddInstName("require_complete");
  1079. return;
  1080. }
  1081. case CARBON_KIND(RequireImplsDecl inst): {
  1082. AddEntityNameAndMaybePush(inst.require_impls_id, ".decl");
  1083. auto require_scope_id = inst_namer_->GetScopeFor(inst.require_impls_id);
  1084. PushBlockId(require_scope_id, inst.decl_block_id);
  1085. return;
  1086. }
  1087. case ReturnSlotPattern::Kind: {
  1088. AddInstNameId(NameId::ReturnSlot, ".patt");
  1089. return;
  1090. }
  1091. case CARBON_KIND(SpecificFunction inst): {
  1092. auto type_id = sem_ir().insts().Get(inst.callee_id).type_id();
  1093. if (auto fn_ty = sem_ir().types().TryGetAs<FunctionType>(type_id)) {
  1094. AddEntityNameAndMaybePush(fn_ty->function_id, ".specific_fn");
  1095. } else {
  1096. AddInstName("specific_fn");
  1097. }
  1098. return;
  1099. }
  1100. case CARBON_KIND(SpecificImplFunction inst): {
  1101. auto type_id = sem_ir().insts().Get(inst.callee_id).type_id();
  1102. if (auto fn_ty = sem_ir().types().TryGetAs<FunctionType>(type_id)) {
  1103. AddEntityNameAndMaybePush(fn_ty->function_id, ".specific_impl_fn");
  1104. } else {
  1105. AddInstName("specific_impl_fn");
  1106. }
  1107. return;
  1108. }
  1109. case ReturnSlot::Kind: {
  1110. AddInstNameId(NameId::ReturnSlot);
  1111. return;
  1112. }
  1113. case CARBON_KIND(SpliceBlock inst): {
  1114. PushBlockId(scope_id_, inst.block_id);
  1115. AddInstName("");
  1116. return;
  1117. }
  1118. case StringLiteral::Kind: {
  1119. AddInstName("str");
  1120. return;
  1121. }
  1122. case CARBON_KIND(StructType inst): {
  1123. const auto& fields = sem_ir().struct_type_fields().Get(inst.fields_id);
  1124. if (fields.empty()) {
  1125. AddInstName("empty_struct_type");
  1126. return;
  1127. }
  1128. std::string name = "struct_type";
  1129. for (auto field : fields) {
  1130. name += ".";
  1131. name += sem_ir().names().GetIRBaseName(field.name_id).str();
  1132. }
  1133. AddInstName(std::move(name));
  1134. return;
  1135. }
  1136. case CARBON_KIND(StructValue inst): {
  1137. if (auto fn_ty = sem_ir().types().TryGetAs<FunctionType>(inst.type_id)) {
  1138. AddEntityNameAndMaybePush(fn_ty->function_id);
  1139. } else if (auto class_ty =
  1140. sem_ir().types().TryGetAs<ClassType>(inst.type_id)) {
  1141. AddEntityNameAndMaybePush(class_ty->class_id, ".val");
  1142. } else if (auto generic_class_ty =
  1143. sem_ir().types().TryGetAs<GenericClassType>(
  1144. inst.type_id)) {
  1145. AddEntityNameAndMaybePush(generic_class_ty->class_id, ".generic");
  1146. } else if (auto generic_interface_ty =
  1147. sem_ir().types().TryGetAs<GenericInterfaceType>(
  1148. inst.type_id)) {
  1149. AddInstNameId(sem_ir()
  1150. .interfaces()
  1151. .Get(generic_interface_ty->interface_id)
  1152. .name_id,
  1153. ".generic");
  1154. } else if (auto template_name_ty =
  1155. sem_ir().types().TryGetAs<CppTemplateNameType>(
  1156. inst.type_id)) {
  1157. AddInstNameId(
  1158. sem_ir().entity_names().Get(template_name_ty->name_id).name_id,
  1159. ".template");
  1160. } else {
  1161. if (sem_ir().inst_blocks().Get(inst.elements_id).empty()) {
  1162. AddInstName("empty_struct");
  1163. } else {
  1164. AddInstName("struct");
  1165. }
  1166. }
  1167. return;
  1168. }
  1169. case CARBON_KIND(TupleAccess inst): {
  1170. RawStringOstream out;
  1171. out << "tuple.elem" << inst.index.index;
  1172. AddInstName(out.TakeStr());
  1173. return;
  1174. }
  1175. case CARBON_KIND(TupleType inst): {
  1176. if (inst.type_elements_id == InstBlockId::Empty) {
  1177. AddInstName("empty_tuple.type");
  1178. } else {
  1179. AddInstName("tuple.type");
  1180. }
  1181. return;
  1182. }
  1183. case CARBON_KIND(TupleValue inst): {
  1184. if (sem_ir().types().Is<ArrayType>(inst.type_id)) {
  1185. AddInstName("array");
  1186. } else if (inst.elements_id == InstBlockId::Empty) {
  1187. AddInstName("empty_tuple");
  1188. } else {
  1189. AddInstName("tuple");
  1190. }
  1191. return;
  1192. }
  1193. case CARBON_KIND(UnboundElementType inst): {
  1194. if (auto class_ty =
  1195. sem_ir().insts().TryGetAs<ClassType>(inst.class_type_inst_id)) {
  1196. AddEntityNameAndMaybePush(class_ty->class_id, ".elem");
  1197. } else {
  1198. AddInstName("elem_type");
  1199. }
  1200. return;
  1201. }
  1202. case UninitializedValue::Kind: {
  1203. AddInstName("uninit");
  1204. return;
  1205. }
  1206. case VarPattern::Kind: {
  1207. AddInstNameId(GetPrettyNameFromPatternId(sem_ir(), inst_id_),
  1208. ".var_patt");
  1209. return;
  1210. }
  1211. case CARBON_KIND(VarStorage inst): {
  1212. if (inst.pattern_id.has_value()) {
  1213. AddInstNameId(GetPrettyNameFromPatternId(sem_ir(), inst.pattern_id),
  1214. ".var");
  1215. } else {
  1216. AddInstName("var");
  1217. }
  1218. return;
  1219. }
  1220. default: {
  1221. // Sequentially number all remaining values.
  1222. if (inst_.kind().has_type()) {
  1223. AddInstName("");
  1224. }
  1225. return;
  1226. }
  1227. }
  1228. }
  1229. auto InstNamer::has_name(InstId inst_id) const -> bool {
  1230. return static_cast<bool>(
  1231. insts_[sem_ir_->insts().GetRawIndex(inst_id)].second);
  1232. }
  1233. } // namespace Carbon::SemIR