formatter.cpp 33 KB

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