formatter.cpp 29 KB

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