inst_namer.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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 "common/ostream.h"
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/base/shared_value_stores.h"
  8. #include "toolchain/lex/tokenized_buffer.h"
  9. #include "toolchain/parse/tree.h"
  10. #include "toolchain/sem_ir/builtin_function_kind.h"
  11. #include "toolchain/sem_ir/function.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/inst_kind.h"
  14. #include "toolchain/sem_ir/typed_insts.h"
  15. namespace Carbon::SemIR {
  16. InstNamer::InstNamer(const Lex::TokenizedBuffer& tokenized_buffer,
  17. const Parse::Tree& parse_tree, const File& sem_ir)
  18. : tokenized_buffer_(tokenized_buffer),
  19. parse_tree_(parse_tree),
  20. sem_ir_(sem_ir) {
  21. insts_.resize(sem_ir.insts().size(), {ScopeId::None, Namespace::Name()});
  22. labels_.resize(sem_ir.inst_blocks().size());
  23. scopes_.resize(static_cast<size_t>(GetScopeFor(NumberOfScopesTag())));
  24. generic_scopes_.resize(sem_ir.generics().size(), ScopeId::None);
  25. // Build the constants scope.
  26. CollectNamesInBlock(ScopeId::Constants, sem_ir.constants().array_ref());
  27. // Build the ImportRef scope.
  28. CollectNamesInBlock(ScopeId::ImportRefs,
  29. sem_ir.inst_blocks().Get(SemIR::InstBlockId::ImportRefs));
  30. // Build the file scope.
  31. CollectNamesInBlock(ScopeId::File, sem_ir.top_inst_block_id());
  32. // Build each function scope.
  33. for (auto [i, fn] : llvm::enumerate(sem_ir.functions().array_ref())) {
  34. FunctionId fn_id(i);
  35. auto fn_scope = GetScopeFor(fn_id);
  36. // TODO: Provide a location for the function for use as a
  37. // disambiguator.
  38. auto fn_loc = Parse::NodeId::Invalid;
  39. GetScopeInfo(fn_scope).name = globals_.AllocateName(
  40. *this, fn_loc, sem_ir.names().GetIRBaseName(fn.name_id).str());
  41. CollectNamesInBlock(fn_scope, fn.implicit_param_patterns_id);
  42. CollectNamesInBlock(fn_scope, fn.param_patterns_id);
  43. if (fn.return_slot_id.is_valid()) {
  44. insts_[fn.return_slot_id.index] = {
  45. fn_scope,
  46. GetScopeInfo(fn_scope).insts.AllocateName(
  47. *this, sem_ir.insts().GetLocId(fn.return_slot_id), "return")};
  48. }
  49. if (!fn.body_block_ids.empty()) {
  50. AddBlockLabel(fn_scope, fn.body_block_ids.front(), "entry", fn_loc);
  51. }
  52. for (auto block_id : fn.body_block_ids) {
  53. CollectNamesInBlock(fn_scope, block_id);
  54. }
  55. for (auto block_id : fn.body_block_ids) {
  56. AddBlockLabel(fn_scope, block_id);
  57. }
  58. CollectNamesInGeneric(fn_scope, fn.generic_id);
  59. }
  60. // Build each class scope.
  61. for (auto [i, class_info] : llvm::enumerate(sem_ir.classes().array_ref())) {
  62. ClassId class_id(i);
  63. auto class_scope = GetScopeFor(class_id);
  64. // TODO: Provide a location for the class for use as a disambiguator.
  65. auto class_loc = Parse::NodeId::Invalid;
  66. GetScopeInfo(class_scope).name = globals_.AllocateName(
  67. *this, class_loc,
  68. sem_ir.names().GetIRBaseName(class_info.name_id).str());
  69. AddBlockLabel(class_scope, class_info.body_block_id, "class", class_loc);
  70. CollectNamesInBlock(class_scope, class_info.body_block_id);
  71. CollectNamesInGeneric(class_scope, class_info.generic_id);
  72. }
  73. // Build each interface scope.
  74. for (auto [i, interface_info] :
  75. llvm::enumerate(sem_ir.interfaces().array_ref())) {
  76. InterfaceId interface_id(i);
  77. auto interface_scope = GetScopeFor(interface_id);
  78. // TODO: Provide a location for the interface for use as a disambiguator.
  79. auto interface_loc = Parse::NodeId::Invalid;
  80. GetScopeInfo(interface_scope).name = globals_.AllocateName(
  81. *this, interface_loc,
  82. sem_ir.names().GetIRBaseName(interface_info.name_id).str());
  83. AddBlockLabel(interface_scope, interface_info.body_block_id, "interface",
  84. interface_loc);
  85. CollectNamesInBlock(interface_scope, interface_info.body_block_id);
  86. CollectNamesInGeneric(interface_scope, interface_info.generic_id);
  87. }
  88. // Build each impl scope.
  89. for (auto [i, impl_info] : llvm::enumerate(sem_ir.impls().array_ref())) {
  90. ImplId impl_id(i);
  91. auto impl_scope = GetScopeFor(impl_id);
  92. // TODO: Provide a location for the impl for use as a disambiguator.
  93. auto impl_loc = Parse::NodeId::Invalid;
  94. // TODO: Invent a name based on the self and constraint types.
  95. GetScopeInfo(impl_scope).name =
  96. globals_.AllocateName(*this, impl_loc, "impl");
  97. AddBlockLabel(impl_scope, impl_info.body_block_id, "impl", impl_loc);
  98. CollectNamesInBlock(impl_scope, impl_info.body_block_id);
  99. CollectNamesInGeneric(impl_scope, impl_info.generic_id);
  100. }
  101. }
  102. auto InstNamer::GetScopeName(ScopeId scope) const -> std::string {
  103. switch (scope) {
  104. case ScopeId::None:
  105. return "<invalid scope>";
  106. // These are treated as SemIR keywords.
  107. case ScopeId::File:
  108. return "file";
  109. case ScopeId::ImportRefs:
  110. return "imports";
  111. case ScopeId::Constants:
  112. return "constants";
  113. // For everything else, use an @ prefix.
  114. default:
  115. return ("@" + GetScopeInfo(scope).name.str()).str();
  116. }
  117. }
  118. auto InstNamer::GetUnscopedNameFor(InstId inst_id) const -> llvm::StringRef {
  119. if (!inst_id.is_valid()) {
  120. return "";
  121. }
  122. const auto& inst_name = insts_[inst_id.index].second;
  123. return inst_name ? inst_name.str() : "";
  124. }
  125. auto InstNamer::GetNameFor(ScopeId scope_id, InstId inst_id) const
  126. -> std::string {
  127. if (!inst_id.is_valid()) {
  128. return "invalid";
  129. }
  130. // Check for a builtin.
  131. if (inst_id.is_builtin()) {
  132. return sem_ir_.insts().Get(inst_id).kind().ir_name().str();
  133. }
  134. if (inst_id == InstId::PackageNamespace) {
  135. return "package";
  136. }
  137. const auto& [inst_scope, inst_name] = insts_[inst_id.index];
  138. if (!inst_name) {
  139. // This should not happen in valid IR.
  140. std::string str;
  141. llvm::raw_string_ostream str_stream(str);
  142. str_stream << "<unexpected>." << inst_id;
  143. auto loc_id = sem_ir_.insts().GetLocId(inst_id);
  144. // TODO: Consider handling inst_id cases.
  145. if (loc_id.is_node_id()) {
  146. auto token = parse_tree_.node_token(loc_id.node_id());
  147. str_stream << ".loc" << tokenized_buffer_.GetLineNumber(token) << "_"
  148. << tokenized_buffer_.GetColumnNumber(token);
  149. }
  150. return str;
  151. }
  152. if (inst_scope == scope_id) {
  153. return ("%" + inst_name.str()).str();
  154. }
  155. return (GetScopeName(inst_scope) + ".%" + inst_name.str()).str();
  156. }
  157. auto InstNamer::GetUnscopedLabelFor(InstBlockId block_id) const
  158. -> llvm::StringRef {
  159. if (!block_id.is_valid()) {
  160. return "";
  161. }
  162. const auto& label_name = labels_[block_id.index].second;
  163. return label_name ? label_name.str() : "";
  164. }
  165. // Returns the IR name to use for a label, when referenced from a given scope.
  166. auto InstNamer::GetLabelFor(ScopeId scope_id, InstBlockId block_id) const
  167. -> std::string {
  168. if (!block_id.is_valid()) {
  169. return "!invalid";
  170. }
  171. const auto& [label_scope, label_name] = labels_[block_id.index];
  172. if (!label_name) {
  173. // This should not happen in valid IR.
  174. std::string str;
  175. llvm::raw_string_ostream(str)
  176. << "<unexpected instblockref " << block_id << ">";
  177. return str;
  178. }
  179. if (label_scope == scope_id) {
  180. return ("!" + label_name.str()).str();
  181. }
  182. return (GetScopeName(label_scope) + ".!" + label_name.str()).str();
  183. }
  184. auto InstNamer::Namespace::Name::str() const -> llvm::StringRef {
  185. llvm::StringMapEntry<NameResult>* value = value_;
  186. CARBON_CHECK(value, "cannot print a null name");
  187. while (value->second.ambiguous && value->second.fallback) {
  188. value = value->second.fallback.value_;
  189. }
  190. return value->first();
  191. }
  192. auto InstNamer::Namespace::AllocateName(const InstNamer& inst_namer,
  193. SemIR::LocId loc_id, std::string name)
  194. -> Name {
  195. // The best (shortest) name for this instruction so far, and the current
  196. // name for it.
  197. Name best;
  198. Name current;
  199. // Add `name` as a name for this entity.
  200. auto add_name = [&](bool mark_ambiguous = true) {
  201. auto [it, added] = allocated.insert({name, NameResult()});
  202. Name new_name = Name(it);
  203. if (!added) {
  204. if (mark_ambiguous) {
  205. // This name was allocated for a different instruction. Mark it as
  206. // ambiguous and keep looking for a name for this instruction.
  207. new_name.SetAmbiguous();
  208. }
  209. } else {
  210. if (!best) {
  211. best = new_name;
  212. } else {
  213. CARBON_CHECK(current);
  214. current.SetFallback(new_name);
  215. }
  216. current = new_name;
  217. }
  218. return added;
  219. };
  220. // Use the given name if it's available.
  221. if (!name.empty()) {
  222. add_name();
  223. }
  224. // Append location information to try to disambiguate.
  225. // TODO: Consider handling inst_id cases.
  226. if (loc_id.is_node_id()) {
  227. auto token = inst_namer.parse_tree_.node_token(loc_id.node_id());
  228. llvm::raw_string_ostream(name)
  229. << ".loc" << inst_namer.tokenized_buffer_.GetLineNumber(token);
  230. add_name();
  231. llvm::raw_string_ostream(name)
  232. << "_" << inst_namer.tokenized_buffer_.GetColumnNumber(token);
  233. add_name();
  234. }
  235. // Append numbers until we find an available name.
  236. name += ".";
  237. auto name_size_without_counter = name.size();
  238. for (int counter = 1;; ++counter) {
  239. name.resize(name_size_without_counter);
  240. llvm::raw_string_ostream(name) << counter;
  241. if (add_name(/*mark_ambiguous=*/false)) {
  242. return best;
  243. }
  244. }
  245. }
  246. auto InstNamer::AddBlockLabel(ScopeId scope_id, InstBlockId block_id,
  247. std::string name, SemIR::LocId loc_id) -> void {
  248. if (!block_id.is_valid() || labels_[block_id.index].second) {
  249. return;
  250. }
  251. if (!loc_id.is_valid()) {
  252. if (const auto& block = sem_ir_.inst_blocks().Get(block_id);
  253. !block.empty()) {
  254. loc_id = sem_ir_.insts().GetLocId(block.front());
  255. }
  256. }
  257. labels_[block_id.index] = {
  258. scope_id, GetScopeInfo(scope_id).labels.AllocateName(*this, loc_id,
  259. std::move(name))};
  260. }
  261. // Finds and adds a suitable block label for the given SemIR instruction that
  262. // represents some kind of branch.
  263. auto InstNamer::AddBlockLabel(ScopeId scope_id, SemIR::LocId loc_id,
  264. AnyBranch branch) -> void {
  265. llvm::StringRef name;
  266. switch (parse_tree_.node_kind(loc_id.node_id())) {
  267. case Parse::NodeKind::IfExprIf:
  268. switch (branch.kind) {
  269. case BranchIf::Kind:
  270. name = "if.expr.then";
  271. break;
  272. case Branch::Kind:
  273. name = "if.expr.else";
  274. break;
  275. case BranchWithArg::Kind:
  276. name = "if.expr.result";
  277. break;
  278. default:
  279. break;
  280. }
  281. break;
  282. case Parse::NodeKind::IfCondition:
  283. switch (branch.kind) {
  284. case BranchIf::Kind:
  285. name = "if.then";
  286. break;
  287. case Branch::Kind:
  288. name = "if.else";
  289. break;
  290. default:
  291. break;
  292. }
  293. break;
  294. case Parse::NodeKind::IfStatement:
  295. name = "if.done";
  296. break;
  297. case Parse::NodeKind::ShortCircuitOperandAnd:
  298. name = branch.kind == BranchIf::Kind ? "and.rhs" : "and.result";
  299. break;
  300. case Parse::NodeKind::ShortCircuitOperandOr:
  301. name = branch.kind == BranchIf::Kind ? "or.rhs" : "or.result";
  302. break;
  303. case Parse::NodeKind::WhileConditionStart:
  304. name = "while.cond";
  305. break;
  306. case Parse::NodeKind::WhileCondition:
  307. switch (branch.kind) {
  308. case BranchIf::Kind:
  309. name = "while.body";
  310. break;
  311. case Branch::Kind:
  312. name = "while.done";
  313. break;
  314. default:
  315. break;
  316. }
  317. break;
  318. default:
  319. break;
  320. }
  321. AddBlockLabel(scope_id, branch.target_id, name.str(), loc_id);
  322. }
  323. auto InstNamer::CollectNamesInBlock(ScopeId scope_id, InstBlockId block_id)
  324. -> void {
  325. if (block_id.is_valid()) {
  326. CollectNamesInBlock(scope_id, sem_ir_.inst_blocks().Get(block_id));
  327. }
  328. }
  329. auto InstNamer::CollectNamesInBlock(ScopeId scope_id,
  330. llvm::ArrayRef<InstId> block) -> void {
  331. Scope& scope = GetScopeInfo(scope_id);
  332. // Use bound names where available. Otherwise, assign a backup name.
  333. for (auto inst_id : block) {
  334. if (!inst_id.is_valid()) {
  335. continue;
  336. }
  337. auto untyped_inst = sem_ir_.insts().Get(inst_id);
  338. auto add_inst_name = [&](std::string name) {
  339. ScopeId old_scope_id = insts_[inst_id.index].first;
  340. if (old_scope_id == ScopeId::None) {
  341. insts_[inst_id.index] = {
  342. scope_id, scope.insts.AllocateName(
  343. *this, sem_ir_.insts().GetLocId(inst_id), name)};
  344. } else {
  345. CARBON_CHECK(old_scope_id == scope_id,
  346. "Attempting to name inst in multiple scopes");
  347. }
  348. };
  349. auto add_inst_name_id = [&](NameId name_id, llvm::StringRef suffix = "") {
  350. add_inst_name(
  351. (sem_ir_.names().GetIRBaseName(name_id).str() + suffix).str());
  352. };
  353. auto add_int_or_float_type_name = [&](char type_literal_prefix,
  354. SemIR::InstId bit_width_id) {
  355. std::string name;
  356. llvm::raw_string_ostream out(name);
  357. out << type_literal_prefix;
  358. if (auto bit_width = sem_ir_.insts().TryGetAs<IntValue>(bit_width_id)) {
  359. out << sem_ir_.ints().Get(bit_width->int_id);
  360. } else {
  361. out << "N";
  362. }
  363. add_inst_name(std::move(name));
  364. };
  365. auto facet_access_name_id = [&](InstId facet_value_inst_id) -> NameId {
  366. if (auto name = sem_ir_.insts().TryGetAs<NameRef>(facet_value_inst_id)) {
  367. return name->name_id;
  368. } else if (auto symbolic = sem_ir_.insts().TryGetAs<BindSymbolicName>(
  369. facet_value_inst_id)) {
  370. return sem_ir_.entity_names().Get(symbolic->entity_name_id).name_id;
  371. }
  372. return NameId::Invalid;
  373. };
  374. if (auto branch = untyped_inst.TryAs<AnyBranch>()) {
  375. AddBlockLabel(scope_id, sem_ir_.insts().GetLocId(inst_id), *branch);
  376. }
  377. CARBON_KIND_SWITCH(untyped_inst) {
  378. case AddrOf::Kind: {
  379. add_inst_name("addr");
  380. continue;
  381. }
  382. case ArrayType::Kind: {
  383. // TODO: Can we figure out the name of the type this is an array of?
  384. add_inst_name("array_type");
  385. continue;
  386. }
  387. case CARBON_KIND(AssociatedConstantDecl inst): {
  388. add_inst_name_id(inst.name_id);
  389. continue;
  390. }
  391. case CARBON_KIND(AssociatedEntity inst): {
  392. std::string name;
  393. llvm::raw_string_ostream out(name);
  394. out << "assoc" << inst.index.index;
  395. add_inst_name(std::move(name));
  396. continue;
  397. }
  398. case CARBON_KIND(AssociatedEntityType inst): {
  399. // TODO: Try to get the name of the interface associated with
  400. // `inst.interface_type_id`.
  401. if (auto fn_ty =
  402. sem_ir_.types().TryGetAs<FunctionType>(inst.entity_type_id)) {
  403. add_inst_name_id(sem_ir_.functions().Get(fn_ty->function_id).name_id,
  404. ".assoc_type");
  405. } else {
  406. // TODO: Handle other cases.
  407. add_inst_name("assoc_type");
  408. }
  409. continue;
  410. }
  411. case BindAlias::Kind:
  412. case BindName::Kind:
  413. case BindSymbolicName::Kind:
  414. case ExportDecl::Kind: {
  415. auto inst = untyped_inst.As<AnyBindNameOrExportDecl>();
  416. add_inst_name_id(
  417. sem_ir_.entity_names().Get(inst.entity_name_id).name_id);
  418. continue;
  419. }
  420. case BindingPattern::Kind:
  421. case SymbolicBindingPattern::Kind: {
  422. auto inst = untyped_inst.As<AnyBindingPattern>();
  423. add_inst_name_id(
  424. sem_ir_.entity_names().Get(inst.entity_name_id).name_id, ".patt");
  425. continue;
  426. }
  427. case CARBON_KIND(BoolLiteral inst): {
  428. if (inst.value.ToBool()) {
  429. add_inst_name("true");
  430. } else {
  431. add_inst_name("false");
  432. }
  433. continue;
  434. }
  435. case CARBON_KIND(BoundMethod inst): {
  436. auto type_id = sem_ir_.insts().Get(inst.function_id).type_id();
  437. if (auto fn_ty = sem_ir_.types().TryGetAs<FunctionType>(type_id)) {
  438. add_inst_name_id(sem_ir_.functions().Get(fn_ty->function_id).name_id,
  439. ".bound");
  440. } else {
  441. add_inst_name("bound_method");
  442. }
  443. continue;
  444. }
  445. case CARBON_KIND(Call inst): {
  446. auto callee_function =
  447. SemIR::GetCalleeFunction(sem_ir_, inst.callee_id);
  448. if (!callee_function.function_id.is_valid()) {
  449. break;
  450. }
  451. const auto& function =
  452. sem_ir_.functions().Get(callee_function.function_id);
  453. // Name the call's result based on the callee.
  454. if (function.builtin_function_kind !=
  455. SemIR::BuiltinFunctionKind::None) {
  456. // For a builtin, use the builtin name. Otherwise, we'd typically pick
  457. // the name `Op` below, which is probably not very useful.
  458. add_inst_name(function.builtin_function_kind.name().str());
  459. continue;
  460. }
  461. add_inst_name_id(function.name_id, ".call");
  462. continue;
  463. }
  464. case CARBON_KIND(ClassDecl inst): {
  465. const auto& class_info = sem_ir_.classes().Get(inst.class_id);
  466. add_inst_name_id(class_info.name_id, ".decl");
  467. auto class_scope_id = GetScopeFor(inst.class_id);
  468. CollectNamesInBlock(class_scope_id, class_info.pattern_block_id);
  469. CollectNamesInBlock(class_scope_id, inst.decl_block_id);
  470. continue;
  471. }
  472. case CARBON_KIND(ClassType inst): {
  473. add_inst_name_id(sem_ir_.classes().Get(inst.class_id).name_id);
  474. continue;
  475. }
  476. case CompleteTypeWitness::Kind: {
  477. // TODO: Can we figure out the name of the type this is a witness for?
  478. add_inst_name("complete_type");
  479. continue;
  480. }
  481. case ConstType::Kind: {
  482. // TODO: Can we figure out the name of the type argument?
  483. add_inst_name("const");
  484. continue;
  485. }
  486. case CARBON_KIND(FacetAccessType inst): {
  487. auto name_id = facet_access_name_id(inst.facet_value_inst_id);
  488. if (name_id.is_valid()) {
  489. add_inst_name_id(name_id, ".as_type");
  490. } else {
  491. add_inst_name("as_type");
  492. }
  493. continue;
  494. }
  495. case CARBON_KIND(FacetAccessWitness inst): {
  496. auto name_id = facet_access_name_id(inst.facet_value_inst_id);
  497. if (name_id.is_valid()) {
  498. add_inst_name_id(name_id, ".as_wit");
  499. } else {
  500. add_inst_name("as_wit");
  501. }
  502. continue;
  503. }
  504. case CARBON_KIND(FacetType inst): {
  505. const auto& facet_type_info =
  506. sem_ir_.facet_types().Get(inst.facet_type_id);
  507. bool has_where = facet_type_info.other_requirements ||
  508. !facet_type_info.rewrite_constraints.empty();
  509. if (auto interface = facet_type_info.TryAsSingleInterface()) {
  510. const auto& interface_info =
  511. sem_ir_.interfaces().Get(interface->interface_id);
  512. add_inst_name_id(interface_info.name_id,
  513. has_where ? "_where.type" : ".type");
  514. } else if (facet_type_info.impls_constraints.empty()) {
  515. add_inst_name(has_where ? "type_where" : "type");
  516. } else {
  517. add_inst_name("facet_type");
  518. }
  519. continue;
  520. }
  521. case CARBON_KIND(FacetValue inst): {
  522. if (auto facet_type =
  523. sem_ir_.types().TryGetAs<FacetType>(inst.type_id)) {
  524. const auto& facet_type_info =
  525. sem_ir_.facet_types().Get(facet_type->facet_type_id);
  526. if (auto interface = facet_type_info.TryAsSingleInterface()) {
  527. const auto& interface_info =
  528. sem_ir_.interfaces().Get(interface->interface_id);
  529. add_inst_name_id(interface_info.name_id, ".facet");
  530. continue;
  531. }
  532. }
  533. add_inst_name("facet_value");
  534. continue;
  535. }
  536. case FloatLiteral::Kind: {
  537. add_inst_name("float");
  538. continue;
  539. }
  540. case CARBON_KIND(FloatType inst): {
  541. add_int_or_float_type_name('f', inst.bit_width_id);
  542. continue;
  543. }
  544. case CARBON_KIND(FunctionDecl inst): {
  545. const auto& function_info = sem_ir_.functions().Get(inst.function_id);
  546. add_inst_name_id(function_info.name_id, ".decl");
  547. auto function_scope_id = GetScopeFor(inst.function_id);
  548. CollectNamesInBlock(function_scope_id, function_info.pattern_block_id);
  549. CollectNamesInBlock(function_scope_id, inst.decl_block_id);
  550. continue;
  551. }
  552. case CARBON_KIND(FunctionType inst): {
  553. add_inst_name_id(sem_ir_.functions().Get(inst.function_id).name_id,
  554. ".type");
  555. continue;
  556. }
  557. case CARBON_KIND(GenericClassType inst): {
  558. add_inst_name_id(sem_ir_.classes().Get(inst.class_id).name_id, ".type");
  559. continue;
  560. }
  561. case CARBON_KIND(GenericInterfaceType inst): {
  562. add_inst_name_id(sem_ir_.interfaces().Get(inst.interface_id).name_id,
  563. ".type");
  564. continue;
  565. }
  566. case CARBON_KIND(ImplDecl inst): {
  567. auto impl_scope_id = GetScopeFor(inst.impl_id);
  568. CollectNamesInBlock(impl_scope_id,
  569. sem_ir_.impls().Get(inst.impl_id).pattern_block_id);
  570. CollectNamesInBlock(impl_scope_id, inst.decl_block_id);
  571. break;
  572. }
  573. case CARBON_KIND(ImportDecl inst): {
  574. if (inst.package_id.is_valid()) {
  575. add_inst_name_id(inst.package_id, ".import");
  576. } else {
  577. add_inst_name("default.import");
  578. }
  579. continue;
  580. }
  581. case ImportRefUnloaded::Kind:
  582. case ImportRefLoaded::Kind: {
  583. add_inst_name("import_ref");
  584. // When building import refs, we frequently add instructions without
  585. // a block. Constants that refer to them need to be separately
  586. // named.
  587. auto const_id = sem_ir_.constant_values().Get(inst_id);
  588. if (const_id.is_valid() && const_id.is_template()) {
  589. auto const_inst_id = sem_ir_.constant_values().GetInstId(const_id);
  590. if (!insts_[const_inst_id.index].second) {
  591. CollectNamesInBlock(ScopeId::ImportRefs, const_inst_id);
  592. }
  593. }
  594. continue;
  595. }
  596. case CARBON_KIND(InterfaceDecl inst): {
  597. const auto& interface_info =
  598. sem_ir_.interfaces().Get(inst.interface_id);
  599. add_inst_name_id(interface_info.name_id, ".decl");
  600. auto interface_scope_id = GetScopeFor(inst.interface_id);
  601. CollectNamesInBlock(interface_scope_id,
  602. interface_info.pattern_block_id);
  603. CollectNamesInBlock(interface_scope_id, inst.decl_block_id);
  604. continue;
  605. }
  606. case InterfaceWitness::Kind: {
  607. // TODO: Include name of interface.
  608. add_inst_name("interface");
  609. continue;
  610. }
  611. case CARBON_KIND(InterfaceWitnessAccess inst): {
  612. std::string name;
  613. llvm::raw_string_ostream out(name);
  614. out << "impl.elem" << inst.index.index;
  615. add_inst_name(std::move(name));
  616. continue;
  617. }
  618. case CARBON_KIND(IntType inst): {
  619. add_int_or_float_type_name(inst.int_kind == IntKind::Signed ? 'i' : 'u',
  620. inst.bit_width_id);
  621. continue;
  622. }
  623. case CARBON_KIND(IntValue inst): {
  624. std::string name;
  625. llvm::raw_string_ostream out(name);
  626. out << "int_" << sem_ir_.ints().Get(inst.int_id);
  627. add_inst_name(std::move(name));
  628. continue;
  629. }
  630. case CARBON_KIND(NameRef inst): {
  631. add_inst_name_id(inst.name_id, ".ref");
  632. continue;
  633. }
  634. // The namespace is specified here due to the name conflict.
  635. case CARBON_KIND(SemIR::Namespace inst): {
  636. add_inst_name_id(sem_ir_.name_scopes().Get(inst.name_scope_id).name_id);
  637. continue;
  638. }
  639. case OutParam::Kind:
  640. case ValueParam::Kind: {
  641. add_inst_name_id(untyped_inst.As<AnyParam>().pretty_name_id, ".param");
  642. continue;
  643. }
  644. case OutParamPattern::Kind:
  645. case ValueParamPattern::Kind: {
  646. add_inst_name_id(
  647. SemIR::Function::GetNameFromPatternId(sem_ir_, inst_id),
  648. ".param_patt");
  649. continue;
  650. }
  651. case PointerType::Kind: {
  652. add_inst_name("ptr");
  653. continue;
  654. }
  655. case InstKind::ReturnSlotPattern: {
  656. add_inst_name_id(NameId::ReturnSlot, ".patt");
  657. continue;
  658. }
  659. case CARBON_KIND(SpecificFunction inst): {
  660. InstId callee_id = inst.callee_id;
  661. if (auto method = sem_ir_.insts().TryGetAs<BoundMethod>(callee_id)) {
  662. callee_id = method->function_id;
  663. }
  664. auto type_id = sem_ir_.insts().Get(callee_id).type_id();
  665. if (auto fn_ty = sem_ir_.types().TryGetAs<FunctionType>(type_id)) {
  666. add_inst_name_id(sem_ir_.functions().Get(fn_ty->function_id).name_id,
  667. ".specific_fn");
  668. } else {
  669. add_inst_name("specific_fn");
  670. }
  671. continue;
  672. }
  673. case CARBON_KIND(SpliceBlock inst): {
  674. CollectNamesInBlock(scope_id, inst.block_id);
  675. break;
  676. }
  677. case StringLiteral::Kind: {
  678. add_inst_name("str");
  679. continue;
  680. }
  681. case CARBON_KIND(StructValue inst): {
  682. if (auto fn_ty = sem_ir_.types().TryGetAs<FunctionType>(inst.type_id)) {
  683. add_inst_name_id(sem_ir_.functions().Get(fn_ty->function_id).name_id);
  684. } else if (auto class_ty =
  685. sem_ir_.types().TryGetAs<ClassType>(inst.type_id)) {
  686. add_inst_name_id(sem_ir_.classes().Get(class_ty->class_id).name_id,
  687. ".val");
  688. } else if (auto generic_class_ty =
  689. sem_ir_.types().TryGetAs<GenericClassType>(
  690. inst.type_id)) {
  691. add_inst_name_id(
  692. sem_ir_.classes().Get(generic_class_ty->class_id).name_id,
  693. ".generic");
  694. } else if (auto generic_interface_ty =
  695. sem_ir_.types().TryGetAs<GenericInterfaceType>(
  696. inst.type_id)) {
  697. add_inst_name_id(sem_ir_.interfaces()
  698. .Get(generic_interface_ty->interface_id)
  699. .name_id,
  700. ".generic");
  701. } else {
  702. if (sem_ir_.inst_blocks().Get(inst.elements_id).empty()) {
  703. add_inst_name("empty_struct");
  704. } else {
  705. add_inst_name("struct");
  706. }
  707. }
  708. continue;
  709. }
  710. case CARBON_KIND(StructType inst): {
  711. const auto& fields = sem_ir_.struct_type_fields().Get(inst.fields_id);
  712. if (fields.empty()) {
  713. add_inst_name("empty_struct_type");
  714. continue;
  715. }
  716. std::string name = "struct_type";
  717. for (auto field : fields) {
  718. name += ".";
  719. name += sem_ir_.names().GetIRBaseName(field.name_id).str();
  720. }
  721. add_inst_name(std::move(name));
  722. continue;
  723. }
  724. case CARBON_KIND(TupleAccess inst): {
  725. std::string name;
  726. llvm::raw_string_ostream out(name);
  727. out << "tuple.elem" << inst.index.index;
  728. add_inst_name(std::move(name));
  729. continue;
  730. }
  731. case CARBON_KIND(TupleType inst): {
  732. if (inst.elements_id == TypeBlockId::Empty) {
  733. add_inst_name("empty_tuple.type");
  734. } else {
  735. add_inst_name("tuple.type");
  736. }
  737. continue;
  738. }
  739. case CARBON_KIND(TupleValue inst): {
  740. if (sem_ir_.types().Is<ArrayType>(inst.type_id)) {
  741. add_inst_name("array");
  742. } else if (inst.elements_id == InstBlockId::Empty) {
  743. add_inst_name("empty_tuple");
  744. } else {
  745. add_inst_name("tuple");
  746. }
  747. continue;
  748. }
  749. case CARBON_KIND(UnboundElementType inst): {
  750. if (auto class_ty =
  751. sem_ir_.types().TryGetAs<ClassType>(inst.class_type_id)) {
  752. add_inst_name_id(sem_ir_.classes().Get(class_ty->class_id).name_id,
  753. ".elem");
  754. } else {
  755. add_inst_name("elem_type");
  756. }
  757. continue;
  758. }
  759. case CARBON_KIND(VarStorage inst): {
  760. add_inst_name_id(inst.name_id, ".var");
  761. continue;
  762. }
  763. default: {
  764. break;
  765. }
  766. }
  767. // Sequentially number all remaining values.
  768. if (untyped_inst.kind().value_kind() != InstValueKind::None) {
  769. add_inst_name("");
  770. }
  771. }
  772. }
  773. auto InstNamer::CollectNamesInGeneric(ScopeId scope_id, GenericId generic_id)
  774. -> void {
  775. if (!generic_id.is_valid()) {
  776. return;
  777. }
  778. generic_scopes_[generic_id.index] = scope_id;
  779. const auto& generic = sem_ir_.generics().Get(generic_id);
  780. CollectNamesInBlock(scope_id, generic.decl_block_id);
  781. CollectNamesInBlock(scope_id, generic.definition_block_id);
  782. }
  783. } // namespace Carbon::SemIR