formatter.cpp 29 KB

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