formatter.cpp 28 KB

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