formatter.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  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/formatter.h"
  5. #include "llvm/ADT/Sequence.h"
  6. #include "llvm/ADT/StringExtras.h"
  7. #include "llvm/ADT/StringMap.h"
  8. #include "llvm/Support/SaveAndRestore.h"
  9. #include "toolchain/base/value_store.h"
  10. #include "toolchain/lex/tokenized_buffer.h"
  11. #include "toolchain/parse/tree.h"
  12. namespace Carbon::SemIR {
  13. namespace {
  14. // Assigns names to instructions, blocks, and scopes in the Semantics IR.
  15. //
  16. // TODOs / future work ideas:
  17. // - Add a documentation file for the textual format and link to the
  18. // naming section here.
  19. // - Consider representing literals as just `literal` in the IR and using the
  20. // type to distinguish.
  21. class InstNamer {
  22. public:
  23. // int32_t matches the input value size.
  24. // NOLINTNEXTLINE(performance-enum-size)
  25. enum class ScopeIndex : int32_t {
  26. None = -1,
  27. File = 0,
  28. Constants = 1,
  29. FirstFunction = 2,
  30. };
  31. static_assert(sizeof(ScopeIndex) == sizeof(FunctionId));
  32. InstNamer(const Lex::TokenizedBuffer& tokenized_buffer,
  33. const Parse::Tree& parse_tree, const File& sem_ir)
  34. : tokenized_buffer_(tokenized_buffer),
  35. parse_tree_(parse_tree),
  36. sem_ir_(sem_ir) {
  37. insts.resize(sem_ir.insts().size());
  38. labels.resize(sem_ir.inst_blocks().size());
  39. scopes.resize(static_cast<int32_t>(ScopeIndex::FirstFunction) +
  40. sem_ir.functions().size() + sem_ir.classes().size());
  41. // Build the constants scope.
  42. GetScopeInfo(ScopeIndex::Constants).name =
  43. globals.AddNameUnchecked("constants");
  44. CollectNamesInBlock(ScopeIndex::Constants, sem_ir.constants().array_ref());
  45. // Build the file scope.
  46. GetScopeInfo(ScopeIndex::File).name = globals.AddNameUnchecked("file");
  47. CollectNamesInBlock(ScopeIndex::File, sem_ir.top_inst_block_id());
  48. // Build each function scope.
  49. for (auto [i, fn] : llvm::enumerate(sem_ir.functions().array_ref())) {
  50. auto fn_id = FunctionId(i);
  51. auto fn_scope = GetScopeFor(fn_id);
  52. // TODO: Provide a location for the function for use as a
  53. // disambiguator.
  54. auto fn_loc = Parse::Node::Invalid;
  55. GetScopeInfo(fn_scope).name = globals.AllocateName(
  56. *this, fn_loc, sem_ir.names().GetIRBaseName(fn.name_id).str());
  57. CollectNamesInBlock(fn_scope, fn.implicit_param_refs_id);
  58. CollectNamesInBlock(fn_scope, fn.param_refs_id);
  59. if (fn.return_slot_id.is_valid()) {
  60. insts[fn.return_slot_id.index] = {
  61. fn_scope,
  62. GetScopeInfo(fn_scope).insts.AllocateName(
  63. *this, sem_ir.insts().Get(fn.return_slot_id).parse_node(),
  64. "return")};
  65. }
  66. if (!fn.body_block_ids.empty()) {
  67. AddBlockLabel(fn_scope, fn.body_block_ids.front(), "entry", fn_loc);
  68. }
  69. for (auto block_id : fn.body_block_ids) {
  70. CollectNamesInBlock(fn_scope, block_id);
  71. }
  72. for (auto block_id : fn.body_block_ids) {
  73. AddBlockLabel(fn_scope, block_id);
  74. }
  75. }
  76. // Build each class scope.
  77. for (auto [i, class_info] : llvm::enumerate(sem_ir.classes().array_ref())) {
  78. auto class_id = ClassId(i);
  79. auto class_scope = GetScopeFor(class_id);
  80. // TODO: Provide a location for the class for use as a
  81. // disambiguator.
  82. auto class_loc = Parse::Node::Invalid;
  83. GetScopeInfo(class_scope).name = globals.AllocateName(
  84. *this, class_loc,
  85. sem_ir.names().GetIRBaseName(class_info.name_id).str());
  86. AddBlockLabel(class_scope, class_info.body_block_id, "class", class_loc);
  87. CollectNamesInBlock(class_scope, class_info.body_block_id);
  88. }
  89. }
  90. // Returns the scope index corresponding to a function.
  91. auto GetScopeFor(FunctionId fn_id) -> ScopeIndex {
  92. return static_cast<ScopeIndex>(
  93. static_cast<int32_t>(ScopeIndex::FirstFunction) + fn_id.index);
  94. }
  95. // Returns the scope index corresponding to a class.
  96. auto GetScopeFor(ClassId class_id) -> ScopeIndex {
  97. return static_cast<ScopeIndex>(
  98. static_cast<int32_t>(ScopeIndex::FirstFunction) +
  99. sem_ir_.functions().size() + class_id.index);
  100. }
  101. // Returns the IR name to use for a function.
  102. auto GetNameFor(FunctionId fn_id) -> llvm::StringRef {
  103. if (!fn_id.is_valid()) {
  104. return "invalid";
  105. }
  106. return GetScopeInfo(GetScopeFor(fn_id)).name.str();
  107. }
  108. // Returns the IR name to use for a class.
  109. auto GetNameFor(ClassId class_id) -> llvm::StringRef {
  110. if (!class_id.is_valid()) {
  111. return "invalid";
  112. }
  113. return GetScopeInfo(GetScopeFor(class_id)).name.str();
  114. }
  115. // Returns the IR name to use for an instruction, when referenced from a given
  116. // scope.
  117. auto GetNameFor(ScopeIndex scope_idx, InstId inst_id) -> std::string {
  118. if (!inst_id.is_valid()) {
  119. return "invalid";
  120. }
  121. // Check for a builtin.
  122. if (inst_id.index < BuiltinKind::ValidCount) {
  123. return BuiltinKind::FromInt(inst_id.index).label().str();
  124. }
  125. auto& [inst_scope, inst_name] = insts[inst_id.index];
  126. if (!inst_name) {
  127. // This should not happen in valid IR.
  128. std::string str;
  129. llvm::raw_string_ostream(str) << "<unexpected instref " << inst_id << ">";
  130. return str;
  131. }
  132. if (inst_scope == scope_idx) {
  133. return inst_name.str().str();
  134. }
  135. return (GetScopeInfo(inst_scope).name.str() + "." + inst_name.str()).str();
  136. }
  137. // Returns the IR name to use for a label, when referenced from a given scope.
  138. auto GetLabelFor(ScopeIndex scope_idx, InstBlockId block_id) -> std::string {
  139. if (!block_id.is_valid()) {
  140. return "!invalid";
  141. }
  142. auto& [label_scope, label_name] = labels[block_id.index];
  143. if (!label_name) {
  144. // This should not happen in valid IR.
  145. std::string str;
  146. llvm::raw_string_ostream(str)
  147. << "<unexpected instblockref " << block_id << ">";
  148. return str;
  149. }
  150. if (label_scope == scope_idx) {
  151. return label_name.str().str();
  152. }
  153. return (GetScopeInfo(label_scope).name.str() + "." + label_name.str())
  154. .str();
  155. }
  156. private:
  157. // A space in which unique names can be allocated.
  158. struct Namespace {
  159. // A result of a name lookup.
  160. struct NameResult;
  161. // A name in a namespace, which might be redirected to refer to another name
  162. // for disambiguation purposes.
  163. class Name {
  164. public:
  165. Name() : value_(nullptr) {}
  166. explicit Name(llvm::StringMapIterator<NameResult> it) : value_(&*it) {}
  167. explicit operator bool() const { return value_; }
  168. auto str() const -> llvm::StringRef {
  169. llvm::StringMapEntry<NameResult>* value = value_;
  170. CARBON_CHECK(value) << "cannot print a null name";
  171. while (value->second.ambiguous && value->second.fallback) {
  172. value = value->second.fallback.value_;
  173. }
  174. return value->first();
  175. }
  176. auto SetFallback(Name name) -> void { value_->second.fallback = name; }
  177. auto SetAmbiguous() -> void { value_->second.ambiguous = true; }
  178. private:
  179. llvm::StringMapEntry<NameResult>* value_ = nullptr;
  180. };
  181. struct NameResult {
  182. bool ambiguous = false;
  183. Name fallback = Name();
  184. };
  185. llvm::StringRef prefix;
  186. llvm::StringMap<NameResult> allocated = {};
  187. int unnamed_count = 0;
  188. auto AddNameUnchecked(llvm::StringRef name) -> Name {
  189. return Name(allocated.insert({name, NameResult()}).first);
  190. }
  191. auto AllocateName(const InstNamer& namer, Parse::Node node,
  192. std::string name = "") -> Name {
  193. // The best (shortest) name for this instruction so far, and the current
  194. // name for it.
  195. Name best;
  196. Name current;
  197. // Add `name` as a name for this entity.
  198. auto add_name = [&](bool mark_ambiguous = true) {
  199. auto [it, added] = allocated.insert({name, NameResult()});
  200. Name new_name = Name(it);
  201. if (!added) {
  202. if (mark_ambiguous) {
  203. // This name was allocated for a different instruction. Mark it as
  204. // ambiguous and keep looking for a name for this instruction.
  205. new_name.SetAmbiguous();
  206. }
  207. } else {
  208. if (!best) {
  209. best = new_name;
  210. } else {
  211. CARBON_CHECK(current);
  212. current.SetFallback(new_name);
  213. }
  214. current = new_name;
  215. }
  216. return added;
  217. };
  218. // All names start with the prefix.
  219. name.insert(0, prefix);
  220. // Use the given name if it's available and not just the prefix.
  221. if (name.size() > prefix.size()) {
  222. add_name();
  223. }
  224. // Append location information to try to disambiguate.
  225. if (node.is_valid()) {
  226. auto token = namer.parse_tree_.node_token(node);
  227. llvm::raw_string_ostream(name)
  228. << ".loc" << namer.tokenized_buffer_.GetLineNumber(token);
  229. add_name();
  230. llvm::raw_string_ostream(name)
  231. << "_" << namer.tokenized_buffer_.GetColumnNumber(token);
  232. add_name();
  233. }
  234. // Append numbers until we find an available name.
  235. name += ".";
  236. auto name_size_without_counter = name.size();
  237. for (int counter = 1;; ++counter) {
  238. name.resize(name_size_without_counter);
  239. llvm::raw_string_ostream(name) << counter;
  240. if (add_name(/*mark_ambiguous=*/false)) {
  241. return best;
  242. }
  243. }
  244. }
  245. };
  246. // A named scope that contains named entities.
  247. struct Scope {
  248. Namespace::Name name;
  249. Namespace insts = {.prefix = "%"};
  250. Namespace labels = {.prefix = "!"};
  251. };
  252. auto GetScopeInfo(ScopeIndex scope_idx) -> Scope& {
  253. return scopes[static_cast<int>(scope_idx)];
  254. }
  255. auto AddBlockLabel(ScopeIndex scope_idx, InstBlockId block_id,
  256. std::string name = "",
  257. Parse::Node parse_node = Parse::Node::Invalid) -> void {
  258. if (!block_id.is_valid() || labels[block_id.index].second) {
  259. return;
  260. }
  261. if (parse_node == Parse::Node::Invalid) {
  262. if (const auto& block = sem_ir_.inst_blocks().Get(block_id);
  263. !block.empty()) {
  264. parse_node = sem_ir_.insts().Get(block.front()).parse_node();
  265. }
  266. }
  267. labels[block_id.index] = {scope_idx,
  268. GetScopeInfo(scope_idx).labels.AllocateName(
  269. *this, parse_node, std::move(name))};
  270. }
  271. // Finds and adds a suitable block label for the given SemIR instruction that
  272. // represents some kind of branch.
  273. auto AddBlockLabel(ScopeIndex scope_idx, InstBlockId block_id, Inst inst)
  274. -> void {
  275. llvm::StringRef name;
  276. switch (parse_tree_.node_kind(inst.parse_node())) {
  277. case Parse::NodeKind::IfExprIf:
  278. switch (inst.kind()) {
  279. case BranchIf::Kind:
  280. name = "if.expr.then";
  281. break;
  282. case Branch::Kind:
  283. name = "if.expr.else";
  284. break;
  285. case BranchWithArg::Kind:
  286. name = "if.expr.result";
  287. break;
  288. default:
  289. break;
  290. }
  291. break;
  292. case Parse::NodeKind::IfCondition:
  293. switch (inst.kind()) {
  294. case BranchIf::Kind:
  295. name = "if.then";
  296. break;
  297. case Branch::Kind:
  298. name = "if.else";
  299. break;
  300. default:
  301. break;
  302. }
  303. break;
  304. case Parse::NodeKind::IfStatement:
  305. name = "if.done";
  306. break;
  307. case Parse::NodeKind::ShortCircuitOperand: {
  308. bool is_rhs = inst.Is<BranchIf>();
  309. bool is_and = tokenized_buffer_.GetKind(parse_tree_.node_token(
  310. inst.parse_node())) == Lex::TokenKind::And;
  311. name = is_and ? (is_rhs ? "and.rhs" : "and.result")
  312. : (is_rhs ? "or.rhs" : "or.result");
  313. break;
  314. }
  315. case Parse::NodeKind::WhileConditionStart:
  316. name = "while.cond";
  317. break;
  318. case Parse::NodeKind::WhileCondition:
  319. switch (inst.kind()) {
  320. case InstKind::BranchIf:
  321. name = "while.body";
  322. break;
  323. case InstKind::Branch:
  324. name = "while.done";
  325. break;
  326. default:
  327. break;
  328. }
  329. break;
  330. default:
  331. break;
  332. }
  333. AddBlockLabel(scope_idx, block_id, name.str(), inst.parse_node());
  334. }
  335. auto CollectNamesInBlock(ScopeIndex scope_idx, InstBlockId block_id) -> void {
  336. if (block_id.is_valid()) {
  337. CollectNamesInBlock(scope_idx, sem_ir_.inst_blocks().Get(block_id));
  338. }
  339. }
  340. auto CollectNamesInBlock(ScopeIndex scope_idx, llvm::ArrayRef<InstId> block)
  341. -> void {
  342. Scope& scope = GetScopeInfo(scope_idx);
  343. // Use bound names where available. Otherwise, assign a backup name.
  344. for (auto inst_id : block) {
  345. if (!inst_id.is_valid()) {
  346. continue;
  347. }
  348. auto inst = sem_ir_.insts().Get(inst_id);
  349. auto add_inst_name = [&](std::string name) {
  350. insts[inst_id.index] = {scope_idx, scope.insts.AllocateName(
  351. *this, inst.parse_node(), name)};
  352. };
  353. auto add_inst_name_id = [&](NameId name_id, llvm::StringRef suffix = "") {
  354. add_inst_name(
  355. (sem_ir_.names().GetIRBaseName(name_id).str() + suffix).str());
  356. };
  357. switch (inst.kind()) {
  358. case Branch::Kind: {
  359. AddBlockLabel(scope_idx, inst.As<Branch>().target_id, inst);
  360. break;
  361. }
  362. case BranchIf::Kind: {
  363. AddBlockLabel(scope_idx, inst.As<BranchIf>().target_id, inst);
  364. break;
  365. }
  366. case BranchWithArg::Kind: {
  367. AddBlockLabel(scope_idx, inst.As<BranchWithArg>().target_id, inst);
  368. break;
  369. }
  370. case SpliceBlock::Kind: {
  371. CollectNamesInBlock(scope_idx, inst.As<SpliceBlock>().block_id);
  372. break;
  373. }
  374. case BindName::Kind: {
  375. add_inst_name_id(inst.As<BindName>().name_id);
  376. continue;
  377. }
  378. case FunctionDecl::Kind: {
  379. add_inst_name_id(sem_ir_.functions()
  380. .Get(inst.As<FunctionDecl>().function_id)
  381. .name_id);
  382. continue;
  383. }
  384. case ClassType::Kind: {
  385. add_inst_name_id(
  386. sem_ir_.classes().Get(inst.As<ClassType>().class_id).name_id);
  387. continue;
  388. }
  389. case NameRef::Kind: {
  390. add_inst_name_id(inst.As<NameRef>().name_id, ".ref");
  391. continue;
  392. }
  393. case Param::Kind: {
  394. add_inst_name_id(inst.As<Param>().name_id);
  395. continue;
  396. }
  397. case SelfParam::Kind: {
  398. add_inst_name(inst.As<SelfParam>().is_addr_self.index ? "self.addr"
  399. : "self");
  400. continue;
  401. }
  402. case VarStorage::Kind: {
  403. add_inst_name_id(inst.As<VarStorage>().name_id, ".var");
  404. continue;
  405. }
  406. default: {
  407. break;
  408. }
  409. }
  410. // Sequentially number all remaining values.
  411. if (inst.kind().value_kind() != InstValueKind::None) {
  412. add_inst_name("");
  413. }
  414. }
  415. }
  416. const Lex::TokenizedBuffer& tokenized_buffer_;
  417. const Parse::Tree& parse_tree_;
  418. const File& sem_ir_;
  419. Namespace globals = {.prefix = "@"};
  420. std::vector<std::pair<ScopeIndex, Namespace::Name>> insts;
  421. std::vector<std::pair<ScopeIndex, Namespace::Name>> labels;
  422. std::vector<Scope> scopes;
  423. };
  424. } // namespace
  425. // Formatter for printing textual Semantics IR.
  426. class Formatter {
  427. public:
  428. explicit Formatter(const Lex::TokenizedBuffer& tokenized_buffer,
  429. const Parse::Tree& parse_tree, const File& sem_ir,
  430. llvm::raw_ostream& out)
  431. : sem_ir_(sem_ir),
  432. out_(out),
  433. inst_namer_(tokenized_buffer, parse_tree, sem_ir) {}
  434. auto Format() -> void {
  435. FormatConstants();
  436. out_ << "file \"" << sem_ir_.filename() << "\" {\n";
  437. // TODO: Include information from the `package` declaration, once we
  438. // fully support it.
  439. // TODO: Handle the case where there are multiple top-level instruction
  440. // blocks. For example, there may be branching in the initializer of a
  441. // global or a type expression.
  442. if (auto block_id = sem_ir_.top_inst_block_id(); block_id.is_valid()) {
  443. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeIndex::File);
  444. FormatCodeBlock(block_id);
  445. }
  446. out_ << "}\n";
  447. for (int i : llvm::seq(sem_ir_.classes().size())) {
  448. FormatClass(ClassId(i));
  449. }
  450. for (int i : llvm::seq(sem_ir_.functions().size())) {
  451. FormatFunction(FunctionId(i));
  452. }
  453. }
  454. auto FormatConstants() -> void {
  455. if (!sem_ir_.constants().size()) {
  456. return;
  457. }
  458. llvm::SaveAndRestore constants_scope(scope_,
  459. InstNamer::ScopeIndex::Constants);
  460. out_ << "constants {\n";
  461. FormatCodeBlock(sem_ir_.constants().array_ref());
  462. out_ << "}\n\n";
  463. }
  464. auto FormatClass(ClassId id) -> void {
  465. const Class& class_info = sem_ir_.classes().Get(id);
  466. out_ << "\nclass ";
  467. FormatClassName(id);
  468. llvm::SaveAndRestore class_scope(scope_, inst_namer_.GetScopeFor(id));
  469. if (class_info.scope_id.is_valid()) {
  470. out_ << " {\n";
  471. FormatCodeBlock(class_info.body_block_id);
  472. out_ << "\n!members:";
  473. FormatNameScope(class_info.scope_id, "", "\n .");
  474. out_ << "\n}\n";
  475. } else {
  476. out_ << ";\n";
  477. }
  478. }
  479. auto FormatFunction(FunctionId id) -> void {
  480. const Function& fn = sem_ir_.functions().Get(id);
  481. out_ << "\nfn ";
  482. FormatFunctionName(id);
  483. llvm::SaveAndRestore function_scope(scope_, inst_namer_.GetScopeFor(id));
  484. if (fn.implicit_param_refs_id != InstBlockId::Empty) {
  485. out_ << "[";
  486. FormatParamList(fn.implicit_param_refs_id);
  487. out_ << "]";
  488. }
  489. out_ << "(";
  490. FormatParamList(fn.param_refs_id);
  491. out_ << ")";
  492. if (fn.return_type_id.is_valid()) {
  493. out_ << " -> ";
  494. if (fn.return_slot_id.is_valid()) {
  495. FormatInstName(fn.return_slot_id);
  496. out_ << ": ";
  497. }
  498. FormatType(fn.return_type_id);
  499. }
  500. if (!fn.body_block_ids.empty()) {
  501. out_ << " {";
  502. for (auto block_id : fn.body_block_ids) {
  503. out_ << "\n";
  504. FormatLabel(block_id);
  505. out_ << ":\n";
  506. FormatCodeBlock(block_id);
  507. }
  508. out_ << "}\n";
  509. } else {
  510. out_ << ";\n";
  511. }
  512. }
  513. auto FormatParamList(InstBlockId param_refs_id) -> void {
  514. llvm::ListSeparator sep;
  515. for (const InstId param_id : sem_ir_.inst_blocks().Get(param_refs_id)) {
  516. out_ << sep;
  517. if (!param_id.is_valid()) {
  518. out_ << "invalid";
  519. continue;
  520. }
  521. FormatInstName(param_id);
  522. out_ << ": ";
  523. FormatType(sem_ir_.insts().Get(param_id).type_id());
  524. }
  525. }
  526. auto FormatCodeBlock(InstBlockId block_id) -> void {
  527. if (block_id.is_valid()) {
  528. FormatCodeBlock(sem_ir_.inst_blocks().Get(block_id));
  529. }
  530. }
  531. auto FormatCodeBlock(llvm::ArrayRef<InstId> block) -> void {
  532. for (const InstId inst_id : block) {
  533. FormatInstruction(inst_id);
  534. }
  535. }
  536. auto FormatNameScope(NameScopeId id, llvm::StringRef separator,
  537. llvm::StringRef prefix) -> void {
  538. // Name scopes aren't kept in any particular order. Sort the entries before
  539. // we print them for stability and consistency.
  540. llvm::SmallVector<std::pair<InstId, NameId>> entries;
  541. for (auto [name_id, inst_id] : sem_ir_.name_scopes().Get(id)) {
  542. entries.push_back({inst_id, name_id});
  543. }
  544. llvm::sort(entries,
  545. [](auto a, auto b) { return a.first.index < b.first.index; });
  546. llvm::ListSeparator sep(separator);
  547. for (auto [inst_id, name_id] : entries) {
  548. out_ << sep << prefix;
  549. FormatName(name_id);
  550. out_ << " = ";
  551. FormatInstName(inst_id);
  552. }
  553. }
  554. auto FormatInstruction(InstId inst_id) -> void {
  555. if (!inst_id.is_valid()) {
  556. Indent();
  557. out_ << "invalid\n";
  558. return;
  559. }
  560. FormatInstruction(inst_id, sem_ir_.insts().Get(inst_id));
  561. }
  562. auto FormatInstruction(InstId inst_id, Inst inst) -> void {
  563. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  564. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  565. switch (inst.kind()) {
  566. #define CARBON_SEM_IR_INST_KIND(InstT) \
  567. case InstT::Kind: \
  568. FormatInstruction(inst_id, inst.As<InstT>()); \
  569. break;
  570. #include "toolchain/sem_ir/inst_kind.def"
  571. }
  572. }
  573. auto Indent() -> void { out_.indent(indent_); }
  574. template <typename InstT>
  575. auto FormatInstruction(InstId inst_id, InstT inst) -> void {
  576. Indent();
  577. FormatInstructionLHS(inst_id, inst);
  578. out_ << InstT::Kind.ir_name();
  579. FormatInstructionRHS(inst);
  580. out_ << "\n";
  581. }
  582. auto FormatInstructionLHS(InstId inst_id, Inst inst) -> void {
  583. switch (inst.kind().value_kind()) {
  584. case InstValueKind::Typed:
  585. FormatInstName(inst_id);
  586. out_ << ": ";
  587. switch (GetExprCategory(sem_ir_, inst_id)) {
  588. case ExprCategory::NotExpr:
  589. case ExprCategory::Error:
  590. case ExprCategory::Value:
  591. case ExprCategory::Mixed:
  592. break;
  593. case ExprCategory::DurableRef:
  594. case ExprCategory::EphemeralRef:
  595. out_ << "ref ";
  596. break;
  597. case ExprCategory::Initializing:
  598. out_ << "init ";
  599. break;
  600. }
  601. FormatType(inst.type_id());
  602. out_ << " = ";
  603. break;
  604. case InstValueKind::None:
  605. break;
  606. }
  607. }
  608. template <typename InstT>
  609. auto FormatInstructionRHS(InstT inst) -> void {
  610. // By default, an instruction has a comma-separated argument list.
  611. using Info = TypedInstArgsInfo<InstT>;
  612. if constexpr (Info::NumArgs == 2) {
  613. FormatArgs(Info::template Get<0>(inst), Info::template Get<1>(inst));
  614. } else if constexpr (Info::NumArgs == 1) {
  615. FormatArgs(Info::template Get<0>(inst));
  616. } else {
  617. FormatArgs();
  618. }
  619. }
  620. auto FormatInstructionRHS(BlockArg inst) -> void {
  621. out_ << " ";
  622. FormatLabel(inst.block_id);
  623. }
  624. auto FormatInstruction(InstId /*inst_id*/, BranchIf inst) -> void {
  625. if (!in_terminator_sequence_) {
  626. Indent();
  627. }
  628. out_ << "if ";
  629. FormatInstName(inst.cond_id);
  630. out_ << " " << Branch::Kind.ir_name() << " ";
  631. FormatLabel(inst.target_id);
  632. out_ << " else ";
  633. in_terminator_sequence_ = true;
  634. }
  635. auto FormatInstruction(InstId /*inst_id*/, BranchWithArg inst) -> void {
  636. if (!in_terminator_sequence_) {
  637. Indent();
  638. }
  639. out_ << BranchWithArg::Kind.ir_name() << " ";
  640. FormatLabel(inst.target_id);
  641. out_ << "(";
  642. FormatInstName(inst.arg_id);
  643. out_ << ")\n";
  644. in_terminator_sequence_ = false;
  645. }
  646. auto FormatInstruction(InstId /*inst_id*/, Branch inst) -> void {
  647. if (!in_terminator_sequence_) {
  648. Indent();
  649. }
  650. out_ << Branch::Kind.ir_name() << " ";
  651. FormatLabel(inst.target_id);
  652. out_ << "\n";
  653. in_terminator_sequence_ = false;
  654. }
  655. auto FormatInstructionRHS(Call inst) -> void {
  656. out_ << " ";
  657. FormatArg(inst.callee_id);
  658. if (!inst.args_id.is_valid()) {
  659. out_ << "(<invalid>)";
  660. return;
  661. }
  662. llvm::ArrayRef<InstId> args = sem_ir_.inst_blocks().Get(inst.args_id);
  663. bool has_return_slot =
  664. GetInitializingRepresentation(sem_ir_, inst.type_id).has_return_slot();
  665. InstId return_slot_id = InstId::Invalid;
  666. if (has_return_slot) {
  667. return_slot_id = args.back();
  668. args = args.drop_back();
  669. }
  670. llvm::ListSeparator sep;
  671. out_ << '(';
  672. for (auto inst_id : args) {
  673. out_ << sep;
  674. FormatArg(inst_id);
  675. }
  676. out_ << ')';
  677. if (has_return_slot) {
  678. FormatReturnSlot(return_slot_id);
  679. }
  680. }
  681. auto FormatInstructionRHS(ArrayInit inst) -> void {
  682. FormatArgs(inst.inits_id);
  683. FormatReturnSlot(inst.dest_id);
  684. }
  685. auto FormatInstructionRHS(InitializeFrom inst) -> void {
  686. FormatArgs(inst.src_id);
  687. FormatReturnSlot(inst.dest_id);
  688. }
  689. auto FormatInstructionRHS(StructInit init) -> void {
  690. FormatArgs(init.elements_id);
  691. FormatReturnSlot(init.dest_id);
  692. }
  693. auto FormatInstructionRHS(TupleInit init) -> void {
  694. FormatArgs(init.elements_id);
  695. FormatReturnSlot(init.dest_id);
  696. }
  697. auto FormatInstructionRHS(CrossRef inst) -> void {
  698. // TODO: Figure out a way to make this meaningful. We'll need some way to
  699. // name cross-reference IRs, perhaps by the instruction ID of the import?
  700. out_ << " " << inst.ir_id << "." << inst.inst_id;
  701. }
  702. auto FormatInstructionRHS(SpliceBlock inst) -> void {
  703. FormatArgs(inst.result_id);
  704. out_ << " {";
  705. if (!sem_ir_.inst_blocks().Get(inst.block_id).empty()) {
  706. out_ << "\n";
  707. indent_ += 2;
  708. FormatCodeBlock(inst.block_id);
  709. indent_ -= 2;
  710. Indent();
  711. }
  712. out_ << "}";
  713. }
  714. // StructTypeFields are formatted as part of their StructType.
  715. auto FormatInstruction(InstId /*inst_id*/, StructTypeField /*inst*/) -> void {
  716. }
  717. auto FormatInstructionRHS(StructType inst) -> void {
  718. out_ << " {";
  719. llvm::ListSeparator sep;
  720. for (auto field_id : sem_ir_.inst_blocks().Get(inst.fields_id)) {
  721. out_ << sep << ".";
  722. auto field = sem_ir_.insts().GetAs<StructTypeField>(field_id);
  723. FormatName(field.name_id);
  724. out_ << ": ";
  725. FormatType(field.field_type_id);
  726. }
  727. out_ << "}";
  728. }
  729. auto FormatArgs() -> void {}
  730. template <typename... Args>
  731. auto FormatArgs(Args... args) -> void {
  732. out_ << ' ';
  733. llvm::ListSeparator sep;
  734. ((out_ << sep, FormatArg(args)), ...);
  735. }
  736. auto FormatArg(BoolValue v) -> void { out_ << v; }
  737. auto FormatArg(BuiltinKind kind) -> void { out_ << kind.label(); }
  738. auto FormatArg(FunctionId id) -> void { FormatFunctionName(id); }
  739. auto FormatArg(ClassId id) -> void { FormatClassName(id); }
  740. auto FormatArg(IntegerId id) -> void {
  741. sem_ir_.integers().Get(id).print(out_, /*isSigned=*/false);
  742. }
  743. auto FormatArg(MemberIndex index) -> void { out_ << index; }
  744. auto FormatArg(NameScopeId id) -> void {
  745. out_ << '{';
  746. FormatNameScope(id, ", ", ".");
  747. out_ << '}';
  748. }
  749. auto FormatArg(InstId id) -> void { FormatInstName(id); }
  750. auto FormatArg(InstBlockId id) -> void {
  751. out_ << '(';
  752. llvm::ListSeparator sep;
  753. for (auto inst_id : sem_ir_.inst_blocks().Get(id)) {
  754. out_ << sep;
  755. FormatArg(inst_id);
  756. }
  757. out_ << ')';
  758. }
  759. auto FormatArg(RealId id) -> void {
  760. // TODO: Format with a `.` when the exponent is near zero.
  761. const auto& real = sem_ir_.reals().Get(id);
  762. real.mantissa.print(out_, /*isSigned=*/false);
  763. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  764. }
  765. auto FormatArg(StringLiteralId id) -> void {
  766. out_ << '"';
  767. out_.write_escaped(sem_ir_.string_literals().Get(id),
  768. /*UseHexEscapes=*/true);
  769. out_ << '"';
  770. }
  771. auto FormatArg(NameId id) -> void { FormatName(id); }
  772. auto FormatArg(TypeId id) -> void { FormatType(id); }
  773. auto FormatArg(TypeBlockId id) -> void {
  774. out_ << '(';
  775. llvm::ListSeparator sep;
  776. for (auto type_id : sem_ir_.type_blocks().Get(id)) {
  777. out_ << sep;
  778. FormatArg(type_id);
  779. }
  780. out_ << ')';
  781. }
  782. auto FormatReturnSlot(InstId dest_id) -> void {
  783. out_ << " to ";
  784. FormatArg(dest_id);
  785. }
  786. auto FormatName(NameId id) -> void {
  787. out_ << sem_ir_.names().GetFormatted(id);
  788. }
  789. auto FormatInstName(InstId id) -> void {
  790. out_ << inst_namer_.GetNameFor(scope_, id);
  791. }
  792. auto FormatLabel(InstBlockId id) -> void {
  793. out_ << inst_namer_.GetLabelFor(scope_, id);
  794. }
  795. auto FormatFunctionName(FunctionId id) -> void {
  796. out_ << inst_namer_.GetNameFor(id);
  797. }
  798. auto FormatClassName(ClassId id) -> void {
  799. out_ << inst_namer_.GetNameFor(id);
  800. }
  801. auto FormatType(TypeId id) -> void {
  802. if (!id.is_valid()) {
  803. out_ << "invalid";
  804. } else {
  805. out_ << sem_ir_.StringifyType(id, /*in_type_context=*/true);
  806. }
  807. }
  808. private:
  809. const File& sem_ir_;
  810. llvm::raw_ostream& out_;
  811. InstNamer inst_namer_;
  812. InstNamer::ScopeIndex scope_ = InstNamer::ScopeIndex::None;
  813. bool in_terminator_sequence_ = false;
  814. int indent_ = 2;
  815. };
  816. auto FormatFile(const Lex::TokenizedBuffer& tokenized_buffer,
  817. const Parse::Tree& parse_tree, const File& sem_ir,
  818. llvm::raw_ostream& out) -> void {
  819. Formatter(tokenized_buffer, parse_tree, sem_ir, out).Format();
  820. }
  821. } // namespace Carbon::SemIR