formatter.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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 "common/ostream.h"
  6. #include "llvm/ADT/Sequence.h"
  7. #include "llvm/ADT/StringExtras.h"
  8. #include "llvm/Support/SaveAndRestore.h"
  9. #include "toolchain/base/kind_switch.h"
  10. #include "toolchain/base/value_store.h"
  11. #include "toolchain/lex/tokenized_buffer.h"
  12. #include "toolchain/parse/tree.h"
  13. #include "toolchain/sem_ir/builtin_function_kind.h"
  14. #include "toolchain/sem_ir/function.h"
  15. #include "toolchain/sem_ir/ids.h"
  16. #include "toolchain/sem_ir/inst_namer.h"
  17. #include "toolchain/sem_ir/name_scope.h"
  18. #include "toolchain/sem_ir/typed_insts.h"
  19. namespace Carbon::SemIR {
  20. // Formatter for printing textual Semantics IR.
  21. class FormatterImpl {
  22. public:
  23. explicit FormatterImpl(const File& sem_ir, InstNamer* inst_namer,
  24. llvm::raw_ostream& out, int indent)
  25. : sem_ir_(sem_ir), inst_namer_(inst_namer), out_(out), indent_(indent) {}
  26. // Prints the SemIR.
  27. //
  28. // Constants are printed first and may be referenced by later sections,
  29. // including file-scoped instructions. The file scope may contain entity
  30. // declarations which are defined later, such as classes.
  31. auto Format() -> void {
  32. out_ << "--- " << sem_ir_.filename() << "\n\n";
  33. FormatScope(InstNamer::ScopeId::Constants, sem_ir_.constants().array_ref());
  34. FormatScope(InstNamer::ScopeId::ImportRefs,
  35. sem_ir_.inst_blocks().Get(InstBlockId::ImportRefs));
  36. out_ << inst_namer_->GetScopeName(InstNamer::ScopeId::File) << " ";
  37. OpenBrace();
  38. // TODO: Handle the case where there are multiple top-level instruction
  39. // blocks. For example, there may be branching in the initializer of a
  40. // global or a type expression.
  41. if (auto block_id = sem_ir_.top_inst_block_id(); block_id.is_valid()) {
  42. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::File);
  43. FormatCodeBlock(block_id);
  44. }
  45. CloseBrace();
  46. out_ << '\n';
  47. for (int i : llvm::seq(sem_ir_.interfaces().size())) {
  48. FormatInterface(InterfaceId(i));
  49. }
  50. for (int i : llvm::seq(sem_ir_.impls().size())) {
  51. FormatImpl(ImplId(i));
  52. }
  53. for (int i : llvm::seq(sem_ir_.classes().size())) {
  54. FormatClass(ClassId(i));
  55. }
  56. for (int i : llvm::seq(sem_ir_.functions().size())) {
  57. FormatFunction(FunctionId(i));
  58. }
  59. for (int i : llvm::seq(sem_ir_.specifics().size())) {
  60. FormatSpecific(SpecificId(i));
  61. }
  62. // End-of-file newline.
  63. out_ << "\n";
  64. }
  65. // Prints a code block.
  66. auto FormatPartialTrailingCodeBlock(llvm::ArrayRef<SemIR::InstId> block)
  67. -> void {
  68. out_ << ' ';
  69. OpenBrace();
  70. constexpr int NumPrintedOnSkip = 9;
  71. // Avoid only skipping one item.
  72. if (block.size() > NumPrintedOnSkip + 1) {
  73. Indent();
  74. out_ << "... skipping " << (block.size() - NumPrintedOnSkip)
  75. << " insts ...\n";
  76. block = block.take_back(NumPrintedOnSkip);
  77. }
  78. FormatCodeBlock(block);
  79. CloseBrace();
  80. }
  81. // Prints a single instruction.
  82. auto FormatInst(InstId inst_id) -> void {
  83. if (!inst_id.is_valid()) {
  84. Indent();
  85. out_ << "invalid\n";
  86. return;
  87. }
  88. FormatInst(inst_id, sem_ir_.insts().Get(inst_id));
  89. }
  90. private:
  91. enum class AddSpace : bool { Before, After };
  92. // Begins a braced block. Writes an open brace, and prepares to insert a
  93. // newline after it if the braced block is non-empty.
  94. auto OpenBrace() -> void {
  95. // Put the constant value of an instruction before any braced block, rather
  96. // than at the end.
  97. FormatPendingConstantValue(AddSpace::After);
  98. out_ << '{';
  99. indent_ += 2;
  100. after_open_brace_ = true;
  101. }
  102. // Ends a braced block by writing a close brace.
  103. auto CloseBrace() -> void {
  104. indent_ -= 2;
  105. if (!after_open_brace_) {
  106. Indent();
  107. }
  108. out_ << '}';
  109. after_open_brace_ = false;
  110. }
  111. // Adds beginning-of-line indentation. If we're at the start of a braced
  112. // block, first starts a new line.
  113. auto Indent(int offset = 0) -> void {
  114. if (after_open_brace_) {
  115. out_ << '\n';
  116. after_open_brace_ = false;
  117. }
  118. out_.indent(indent_ + offset);
  119. }
  120. // Adds beginning-of-label indentation. This is one level less than normal
  121. // indentation. Labels also get a preceding blank line unless they're at the
  122. // start of a block.
  123. auto IndentLabel() -> void {
  124. CARBON_CHECK(indent_ >= 2);
  125. if (!after_open_brace_) {
  126. out_ << '\n';
  127. }
  128. Indent(-2);
  129. }
  130. // Formats a top-level scope, particularly Constants and ImportRefs.
  131. auto FormatScope(InstNamer::ScopeId scope_id, llvm::ArrayRef<InstId> block)
  132. -> void {
  133. if (block.empty()) {
  134. return;
  135. }
  136. llvm::SaveAndRestore scope(scope_, scope_id);
  137. out_ << inst_namer_->GetScopeName(scope_id) << " ";
  138. OpenBrace();
  139. FormatCodeBlock(block);
  140. CloseBrace();
  141. out_ << "\n\n";
  142. }
  143. // Formats a full class.
  144. auto FormatClass(ClassId id) -> void {
  145. const Class& class_info = sem_ir_.classes().Get(id);
  146. FormatEntityStart("class", class_info.generic_id, id);
  147. llvm::SaveAndRestore class_scope(scope_, inst_namer_->GetScopeFor(id));
  148. if (class_info.scope_id.is_valid()) {
  149. out_ << ' ';
  150. OpenBrace();
  151. FormatCodeBlock(class_info.body_block_id);
  152. FormatNameScope(class_info.scope_id, "!members:\n");
  153. CloseBrace();
  154. out_ << '\n';
  155. } else {
  156. out_ << ";\n";
  157. }
  158. FormatEntityEnd(class_info.generic_id);
  159. }
  160. // Formats a full interface.
  161. auto FormatInterface(InterfaceId id) -> void {
  162. const Interface& interface_info = sem_ir_.interfaces().Get(id);
  163. FormatEntityStart("interface", interface_info.generic_id, id);
  164. llvm::SaveAndRestore interface_scope(scope_, inst_namer_->GetScopeFor(id));
  165. if (interface_info.scope_id.is_valid()) {
  166. out_ << ' ';
  167. OpenBrace();
  168. FormatCodeBlock(interface_info.body_block_id);
  169. // Always include the !members label because we always list the witness in
  170. // this section.
  171. IndentLabel();
  172. out_ << "!members:\n";
  173. FormatNameScope(interface_info.scope_id);
  174. Indent();
  175. out_ << "witness = ";
  176. FormatArg(interface_info.associated_entities_id);
  177. out_ << "\n";
  178. CloseBrace();
  179. out_ << '\n';
  180. } else {
  181. out_ << ";\n";
  182. }
  183. FormatEntityEnd(interface_info.generic_id);
  184. }
  185. // Formats a full impl.
  186. auto FormatImpl(ImplId id) -> void {
  187. const Impl& impl_info = sem_ir_.impls().Get(id);
  188. FormatEntityStart("impl", SemIR::GenericId::Invalid, id);
  189. out_ << ": ";
  190. // TODO: Include the deduced parameter list if present.
  191. FormatType(impl_info.self_id);
  192. out_ << " as ";
  193. FormatType(impl_info.constraint_id);
  194. llvm::SaveAndRestore impl_scope(scope_, inst_namer_->GetScopeFor(id));
  195. if (impl_info.is_defined()) {
  196. out_ << ' ';
  197. OpenBrace();
  198. FormatCodeBlock(impl_info.body_block_id);
  199. // Print the !members label even if the name scope is empty because we
  200. // always list the witness in this section.
  201. IndentLabel();
  202. out_ << "!members:\n";
  203. if (impl_info.scope_id.is_valid()) {
  204. FormatNameScope(impl_info.scope_id);
  205. }
  206. Indent();
  207. out_ << "witness = ";
  208. FormatArg(impl_info.witness_id);
  209. out_ << "\n";
  210. CloseBrace();
  211. out_ << '\n';
  212. } else {
  213. out_ << ";\n";
  214. }
  215. }
  216. // Formats a full function.
  217. auto FormatFunction(FunctionId id) -> void {
  218. const Function& fn = sem_ir_.functions().Get(id);
  219. std::string function_start;
  220. switch (fn.virtual_modifier) {
  221. case FunctionFields::VirtualModifier::Virtual:
  222. function_start += "virtual ";
  223. break;
  224. case FunctionFields::VirtualModifier::Abstract:
  225. function_start += "abstract ";
  226. break;
  227. case FunctionFields::VirtualModifier::Impl:
  228. function_start += "impl ";
  229. break;
  230. case FunctionFields::VirtualModifier::None:
  231. break;
  232. }
  233. if (fn.is_extern) {
  234. function_start += "extern ";
  235. }
  236. function_start += "fn";
  237. FormatEntityStart(function_start, fn.generic_id, id);
  238. llvm::SaveAndRestore function_scope(scope_, inst_namer_->GetScopeFor(id));
  239. FormatParamList(fn.implicit_param_refs_id, /*is_implicit=*/true);
  240. FormatParamList(fn.param_refs_id, /*is_implicit=*/false);
  241. if (fn.return_storage_id.is_valid()) {
  242. out_ << " -> ";
  243. auto return_info = ReturnTypeInfo::ForFunction(sem_ir_, fn);
  244. if (!fn.body_block_ids.empty() && return_info.is_valid() &&
  245. return_info.has_return_slot()) {
  246. FormatName(fn.return_storage_id);
  247. out_ << ": ";
  248. }
  249. FormatType(sem_ir_.insts().Get(fn.return_storage_id).type_id());
  250. }
  251. if (fn.builtin_function_kind != BuiltinFunctionKind::None) {
  252. out_ << " = \"";
  253. out_.write_escaped(fn.builtin_function_kind.name(),
  254. /*UseHexEscapes=*/true);
  255. out_ << "\"";
  256. }
  257. if (!fn.body_block_ids.empty()) {
  258. out_ << ' ';
  259. OpenBrace();
  260. for (auto block_id : fn.body_block_ids) {
  261. IndentLabel();
  262. FormatLabel(block_id);
  263. out_ << ":\n";
  264. FormatCodeBlock(block_id);
  265. }
  266. CloseBrace();
  267. out_ << '\n';
  268. } else {
  269. out_ << ";\n";
  270. }
  271. FormatEntityEnd(fn.generic_id);
  272. }
  273. // Helper for FormatSpecific to print regions.
  274. auto FormatSpecificRegion(const Generic& generic, const Specific& specific,
  275. GenericInstIndex::Region region,
  276. llvm::StringRef region_name) -> void {
  277. if (!specific.GetValueBlock(region).is_valid()) {
  278. return;
  279. }
  280. if (!region_name.empty()) {
  281. IndentLabel();
  282. out_ << "!" << region_name << ":\n";
  283. }
  284. for (auto [generic_inst_id, specific_inst_id] : llvm::zip_longest(
  285. sem_ir_.inst_blocks().GetOrEmpty(generic.GetEvalBlock(region)),
  286. sem_ir_.inst_blocks().GetOrEmpty(
  287. specific.GetValueBlock(region)))) {
  288. if (generic_inst_id && specific_inst_id &&
  289. sem_ir_.insts().Is<StructTypeField>(*generic_inst_id) &&
  290. sem_ir_.insts().Is<StructTypeField>(*specific_inst_id)) {
  291. // Skip printing struct type fields to match the way we print the
  292. // generic.
  293. continue;
  294. }
  295. Indent();
  296. if (generic_inst_id) {
  297. FormatName(*generic_inst_id);
  298. } else {
  299. out_ << "<missing>";
  300. }
  301. out_ << " => ";
  302. if (specific_inst_id) {
  303. FormatName(*specific_inst_id);
  304. } else {
  305. out_ << "<missing>";
  306. }
  307. out_ << "\n";
  308. }
  309. }
  310. // Formats a full specific.
  311. auto FormatSpecific(SpecificId id) -> void {
  312. const auto& specific = sem_ir_.specifics().Get(id);
  313. out_ << "\n";
  314. out_ << "specific ";
  315. FormatName(id);
  316. // TODO: Remove once we stop forming generic specifics with no generic
  317. // during import.
  318. if (!specific.generic_id.is_valid()) {
  319. out_ << ";\n";
  320. return;
  321. }
  322. out_ << " ";
  323. const auto& generic = sem_ir_.generics().Get(specific.generic_id);
  324. llvm::SaveAndRestore generic_scope(
  325. scope_, inst_namer_->GetScopeFor(specific.generic_id));
  326. OpenBrace();
  327. FormatSpecificRegion(generic, specific,
  328. GenericInstIndex::Region::Declaration, "");
  329. FormatSpecificRegion(generic, specific,
  330. GenericInstIndex::Region::Definition, "definition");
  331. CloseBrace();
  332. out_ << "\n";
  333. }
  334. // Handles generic-specific setup for FormatEntityStart.
  335. auto FormatGenericStart(llvm::StringRef entity_kind, GenericId generic_id)
  336. -> void {
  337. const auto& generic = sem_ir_.generics().Get(generic_id);
  338. out_ << "\n";
  339. Indent();
  340. out_ << "generic " << entity_kind << " ";
  341. FormatName(generic_id);
  342. llvm::SaveAndRestore generic_scope(scope_,
  343. inst_namer_->GetScopeFor(generic_id));
  344. FormatParamList(generic.bindings_id, /*is_implicit=*/false);
  345. out_ << " ";
  346. OpenBrace();
  347. FormatCodeBlock(generic.decl_block_id);
  348. if (generic.definition_block_id.is_valid()) {
  349. IndentLabel();
  350. out_ << "!definition:\n";
  351. FormatCodeBlock(generic.definition_block_id);
  352. }
  353. }
  354. // Provides common formatting for entities, paired with FormatEntityEnd.
  355. template <typename IdT>
  356. auto FormatEntityStart(llvm::StringRef entity_kind, GenericId generic_id,
  357. IdT entity_id) -> void {
  358. if (generic_id.is_valid()) {
  359. FormatGenericStart(entity_kind, generic_id);
  360. }
  361. out_ << "\n";
  362. Indent();
  363. out_ << entity_kind;
  364. // If there's a generic, it will have attached the name. Otherwise, add the
  365. // name here.
  366. if (!generic_id.is_valid()) {
  367. out_ << " ";
  368. FormatName(entity_id);
  369. }
  370. }
  371. // Provides common formatting for entities, paired with FormatEntityStart.
  372. auto FormatEntityEnd(GenericId generic_id) -> void {
  373. if (generic_id.is_valid()) {
  374. CloseBrace();
  375. out_ << '\n';
  376. }
  377. }
  378. // Formats parameters, eliding them completely if they're empty. Wraps in
  379. // parentheses or square brackets based on whether these are implicit
  380. // parameters.
  381. auto FormatParamList(InstBlockId param_refs_id, bool is_implicit) -> void {
  382. if (!param_refs_id.is_valid()) {
  383. return;
  384. }
  385. out_ << (is_implicit ? "[" : "(");
  386. llvm::ListSeparator sep;
  387. for (InstId param_id : sem_ir_.inst_blocks().Get(param_refs_id)) {
  388. out_ << sep;
  389. if (!param_id.is_valid()) {
  390. out_ << "invalid";
  391. continue;
  392. }
  393. if (auto addr = sem_ir_.insts().TryGetAs<SemIR::AddrPattern>(param_id)) {
  394. out_ << "addr ";
  395. param_id = addr->inner_id;
  396. }
  397. FormatName(param_id);
  398. out_ << ": ";
  399. FormatType(sem_ir_.insts().Get(param_id).type_id());
  400. }
  401. out_ << (is_implicit ? "]" : ")");
  402. }
  403. // Prints instructions for a code block.
  404. auto FormatCodeBlock(InstBlockId block_id) -> void {
  405. if (block_id.is_valid()) {
  406. FormatCodeBlock(sem_ir_.inst_blocks().Get(block_id));
  407. }
  408. }
  409. // Prints instructions for a code block.
  410. auto FormatCodeBlock(llvm::ArrayRef<InstId> block) -> void {
  411. for (const InstId inst_id : block) {
  412. FormatInst(inst_id);
  413. }
  414. }
  415. // Prints a code block with braces, intended to be used trailing after other
  416. // content on the same line. If non-empty, instructions are on separate lines.
  417. auto FormatTrailingBlock(InstBlockId block_id) -> void {
  418. out_ << ' ';
  419. OpenBrace();
  420. FormatCodeBlock(block_id);
  421. CloseBrace();
  422. }
  423. // Prints the contents of a name scope, with an optional label.
  424. auto FormatNameScope(NameScopeId id, llvm::StringRef label = "") -> void {
  425. const auto& scope = sem_ir_.name_scopes().Get(id);
  426. if (scope.names.empty() && scope.extended_scopes.empty() &&
  427. scope.import_ir_scopes.empty() && !scope.has_error) {
  428. // Name scope is empty.
  429. return;
  430. }
  431. if (!label.empty()) {
  432. IndentLabel();
  433. out_ << label;
  434. }
  435. for (auto [name_id, inst_id, access_kind] : scope.names) {
  436. Indent();
  437. out_ << ".";
  438. FormatName(name_id);
  439. switch (access_kind) {
  440. case SemIR::AccessKind::Public:
  441. break;
  442. case SemIR::AccessKind::Protected:
  443. out_ << " [protected]";
  444. break;
  445. case SemIR::AccessKind::Private:
  446. out_ << " [private]";
  447. break;
  448. }
  449. out_ << " = ";
  450. FormatName(inst_id);
  451. out_ << "\n";
  452. }
  453. for (auto extended_scope_id : scope.extended_scopes) {
  454. // TODO: Print this scope in a better way.
  455. Indent();
  456. out_ << "extend " << extended_scope_id << "\n";
  457. }
  458. for (auto [import_ir_id, unused] : scope.import_ir_scopes) {
  459. Indent();
  460. out_ << "import ";
  461. FormatArg(import_ir_id);
  462. out_ << "\n";
  463. }
  464. if (scope.has_error) {
  465. Indent();
  466. out_ << "has_error\n";
  467. }
  468. }
  469. auto FormatInst(InstId inst_id, Inst inst) -> void {
  470. CARBON_KIND_SWITCH(inst) {
  471. #define CARBON_SEM_IR_INST_KIND(InstT) \
  472. case CARBON_KIND(InstT typed_inst): { \
  473. FormatInst(inst_id, typed_inst); \
  474. break; \
  475. }
  476. #include "toolchain/sem_ir/inst_kind.def"
  477. }
  478. }
  479. template <typename InstT>
  480. auto FormatInst(InstId inst_id, InstT inst) -> void {
  481. Indent();
  482. FormatInstLHS(inst_id, inst);
  483. out_ << InstT::Kind.ir_name();
  484. pending_constant_value_ = sem_ir_.constant_values().Get(inst_id);
  485. pending_constant_value_is_self_ =
  486. sem_ir_.constant_values().GetInstIdIfValid(pending_constant_value_) ==
  487. inst_id;
  488. FormatInstRHS(inst);
  489. FormatPendingConstantValue(AddSpace::Before);
  490. out_ << "\n";
  491. }
  492. // Don't print a constant for ImportRefUnloaded.
  493. auto FormatInst(InstId inst_id, ImportRefUnloaded inst) -> void {
  494. Indent();
  495. FormatInstLHS(inst_id, inst);
  496. out_ << ImportRefUnloaded::Kind.ir_name();
  497. FormatInstRHS(inst);
  498. out_ << "\n";
  499. }
  500. // If there is a pending constant value attached to the current instruction,
  501. // print it now and clear it out. The constant value gets printed before the
  502. // first braced block argument, or at the end of the instruction if there are
  503. // no such arguments.
  504. auto FormatPendingConstantValue(AddSpace space_where) -> void {
  505. if (pending_constant_value_ == ConstantId::NotConstant) {
  506. return;
  507. }
  508. if (space_where == AddSpace::Before) {
  509. out_ << ' ';
  510. }
  511. out_ << '[';
  512. if (pending_constant_value_.is_valid()) {
  513. out_ << (pending_constant_value_.is_symbolic() ? "symbolic" : "template");
  514. if (!pending_constant_value_is_self_) {
  515. out_ << " = ";
  516. FormatConstant(pending_constant_value_);
  517. }
  518. } else {
  519. out_ << pending_constant_value_;
  520. }
  521. out_ << ']';
  522. if (space_where == AddSpace::After) {
  523. out_ << ' ';
  524. }
  525. pending_constant_value_ = ConstantId::NotConstant;
  526. }
  527. auto FormatInstLHS(InstId inst_id, Inst inst) -> void {
  528. switch (inst.kind().value_kind()) {
  529. case InstValueKind::Typed:
  530. FormatName(inst_id);
  531. out_ << ": ";
  532. switch (GetExprCategory(sem_ir_, inst_id)) {
  533. case ExprCategory::NotExpr:
  534. case ExprCategory::Error:
  535. case ExprCategory::Value:
  536. case ExprCategory::Mixed:
  537. break;
  538. case ExprCategory::DurableRef:
  539. case ExprCategory::EphemeralRef:
  540. out_ << "ref ";
  541. break;
  542. case ExprCategory::Initializing:
  543. out_ << "init ";
  544. break;
  545. }
  546. FormatType(inst.type_id());
  547. out_ << " = ";
  548. break;
  549. case InstValueKind::None:
  550. break;
  551. }
  552. }
  553. // Format ImportDecl with its name.
  554. auto FormatInstLHS(InstId inst_id, ImportDecl /*inst*/) -> void {
  555. FormatName(inst_id);
  556. out_ << " = ";
  557. }
  558. // Print ImportRefUnloaded with type-like semantics even though it lacks a
  559. // type_id.
  560. auto FormatInstLHS(InstId inst_id, ImportRefUnloaded /*inst*/) -> void {
  561. FormatName(inst_id);
  562. out_ << " = ";
  563. }
  564. template <typename InstT>
  565. auto FormatInstRHS(InstT inst) -> void {
  566. // By default, an instruction has a comma-separated argument list.
  567. using Info = Internal::InstLikeTypeInfo<InstT>;
  568. if constexpr (Info::NumArgs == 2) {
  569. // Several instructions have a second operand that's a specific ID. We
  570. // don't include it in the argument list if there is no corresponding
  571. // specific, that is, when we're not in a generic context.
  572. if constexpr (std::is_same_v<typename Info::template ArgType<1>,
  573. SemIR::SpecificId>) {
  574. if (!Info::template Get<1>(inst).is_valid()) {
  575. FormatArgs(Info::template Get<0>(inst));
  576. return;
  577. }
  578. }
  579. FormatArgs(Info::template Get<0>(inst), Info::template Get<1>(inst));
  580. } else if constexpr (Info::NumArgs == 1) {
  581. FormatArgs(Info::template Get<0>(inst));
  582. } else {
  583. FormatArgs();
  584. }
  585. }
  586. auto FormatInstRHS(BindSymbolicName inst) -> void {
  587. // A BindSymbolicName with no value is a purely symbolic binding, such as
  588. // the `Self` in an interface. Don't print out `invalid` for the value.
  589. if (inst.value_id.is_valid()) {
  590. FormatArgs(inst.entity_name_id, inst.value_id);
  591. } else {
  592. FormatArgs(inst.entity_name_id);
  593. }
  594. }
  595. auto FormatInstRHS(BlockArg inst) -> void {
  596. out_ << " ";
  597. FormatLabel(inst.block_id);
  598. }
  599. auto FormatInstRHS(Namespace inst) -> void {
  600. if (inst.import_id.is_valid()) {
  601. FormatArgs(inst.import_id, inst.name_scope_id);
  602. } else {
  603. FormatArgs(inst.name_scope_id);
  604. }
  605. }
  606. auto FormatInst(InstId /*inst_id*/, BranchIf inst) -> void {
  607. if (!in_terminator_sequence_) {
  608. Indent();
  609. }
  610. out_ << "if ";
  611. FormatName(inst.cond_id);
  612. out_ << " " << Branch::Kind.ir_name() << " ";
  613. FormatLabel(inst.target_id);
  614. out_ << " else ";
  615. in_terminator_sequence_ = true;
  616. }
  617. auto FormatInst(InstId /*inst_id*/, BranchWithArg inst) -> void {
  618. if (!in_terminator_sequence_) {
  619. Indent();
  620. }
  621. out_ << BranchWithArg::Kind.ir_name() << " ";
  622. FormatLabel(inst.target_id);
  623. out_ << "(";
  624. FormatName(inst.arg_id);
  625. out_ << ")\n";
  626. in_terminator_sequence_ = false;
  627. }
  628. auto FormatInst(InstId /*inst_id*/, Branch inst) -> void {
  629. if (!in_terminator_sequence_) {
  630. Indent();
  631. }
  632. out_ << Branch::Kind.ir_name() << " ";
  633. FormatLabel(inst.target_id);
  634. out_ << "\n";
  635. in_terminator_sequence_ = false;
  636. }
  637. auto FormatInstRHS(Call inst) -> void {
  638. out_ << " ";
  639. FormatArg(inst.callee_id);
  640. if (!inst.args_id.is_valid()) {
  641. out_ << "(<invalid>)";
  642. return;
  643. }
  644. llvm::ArrayRef<InstId> args = sem_ir_.inst_blocks().Get(inst.args_id);
  645. auto return_info = ReturnTypeInfo::ForType(sem_ir_, inst.type_id);
  646. bool has_return_slot = return_info.has_return_slot();
  647. InstId return_slot_id = InstId::Invalid;
  648. if (has_return_slot) {
  649. return_slot_id = args.back();
  650. args = args.drop_back();
  651. }
  652. llvm::ListSeparator sep;
  653. out_ << '(';
  654. for (auto inst_id : args) {
  655. out_ << sep;
  656. FormatArg(inst_id);
  657. }
  658. out_ << ')';
  659. if (has_return_slot) {
  660. FormatReturnSlot(return_slot_id);
  661. }
  662. }
  663. auto FormatInstRHS(ArrayInit inst) -> void {
  664. FormatArgs(inst.inits_id);
  665. FormatReturnSlot(inst.dest_id);
  666. }
  667. auto FormatInstRHS(InitializeFrom inst) -> void {
  668. FormatArgs(inst.src_id);
  669. FormatReturnSlot(inst.dest_id);
  670. }
  671. auto FormatInstRHS(ReturnExpr ret) -> void {
  672. FormatArgs(ret.expr_id);
  673. if (ret.dest_id.is_valid()) {
  674. FormatReturnSlot(ret.dest_id);
  675. }
  676. }
  677. auto FormatInstRHS(StructInit init) -> void {
  678. FormatArgs(init.elements_id);
  679. FormatReturnSlot(init.dest_id);
  680. }
  681. auto FormatInstRHS(TupleInit init) -> void {
  682. FormatArgs(init.elements_id);
  683. FormatReturnSlot(init.dest_id);
  684. }
  685. auto FormatInstRHS(FunctionDecl inst) -> void {
  686. FormatArgs(inst.function_id);
  687. llvm::SaveAndRestore class_scope(
  688. scope_, inst_namer_->GetScopeFor(inst.function_id));
  689. FormatTrailingBlock(
  690. sem_ir_.functions().Get(inst.function_id).pattern_block_id);
  691. FormatTrailingBlock(inst.decl_block_id);
  692. }
  693. auto FormatInstRHS(ClassDecl inst) -> void {
  694. FormatArgs(inst.class_id);
  695. llvm::SaveAndRestore class_scope(scope_,
  696. inst_namer_->GetScopeFor(inst.class_id));
  697. FormatTrailingBlock(sem_ir_.classes().Get(inst.class_id).pattern_block_id);
  698. FormatTrailingBlock(inst.decl_block_id);
  699. }
  700. auto FormatInstRHS(ImplDecl inst) -> void {
  701. FormatArgs(inst.impl_id);
  702. llvm::SaveAndRestore class_scope(scope_,
  703. inst_namer_->GetScopeFor(inst.impl_id));
  704. FormatTrailingBlock(sem_ir_.impls().Get(inst.impl_id).pattern_block_id);
  705. FormatTrailingBlock(inst.decl_block_id);
  706. }
  707. auto FormatInstRHS(InterfaceDecl inst) -> void {
  708. FormatArgs(inst.interface_id);
  709. llvm::SaveAndRestore class_scope(
  710. scope_, inst_namer_->GetScopeFor(inst.interface_id));
  711. FormatTrailingBlock(
  712. sem_ir_.interfaces().Get(inst.interface_id).pattern_block_id);
  713. FormatTrailingBlock(inst.decl_block_id);
  714. }
  715. auto FormatInstRHS(IntLiteral inst) -> void {
  716. out_ << " ";
  717. sem_ir_.ints()
  718. .Get(inst.int_id)
  719. .print(out_, sem_ir_.types().IsSignedInt(inst.type_id));
  720. }
  721. auto FormatInstRHS(FloatLiteral inst) -> void {
  722. llvm::SmallVector<char, 16> buffer;
  723. sem_ir_.floats().Get(inst.float_id).toString(buffer);
  724. out_ << " " << buffer;
  725. }
  726. auto FormatInstRHS(ImportRefUnloaded inst) -> void {
  727. FormatArgs(inst.import_ir_inst_id);
  728. out_ << ", unloaded";
  729. }
  730. auto FormatInstRHS(ImportRefLoaded inst) -> void {
  731. FormatArgs(inst.import_ir_inst_id);
  732. out_ << ", loaded";
  733. }
  734. auto FormatInstRHS(SpliceBlock inst) -> void {
  735. FormatArgs(inst.result_id);
  736. FormatTrailingBlock(inst.block_id);
  737. }
  738. auto FormatInstRHS(WhereExpr inst) -> void {
  739. FormatArgs(inst.period_self_id);
  740. FormatTrailingBlock(inst.requirements_id);
  741. }
  742. // StructTypeFields are formatted as part of their StructType.
  743. auto FormatInst(InstId /*inst_id*/, StructTypeField /*inst*/) -> void {}
  744. auto FormatInstRHS(StructType inst) -> void {
  745. out_ << " {";
  746. llvm::ListSeparator sep;
  747. for (auto field_id : sem_ir_.inst_blocks().Get(inst.fields_id)) {
  748. out_ << sep << ".";
  749. auto field = sem_ir_.insts().GetAs<StructTypeField>(field_id);
  750. FormatName(field.name_id);
  751. out_ << ": ";
  752. FormatType(field.field_type_id);
  753. }
  754. out_ << "}";
  755. }
  756. auto FormatArgs() -> void {}
  757. template <typename... Args>
  758. auto FormatArgs(Args... args) -> void {
  759. out_ << ' ';
  760. llvm::ListSeparator sep;
  761. ((out_ << sep, FormatArg(args)), ...);
  762. }
  763. // FormatArg variants handling printing instruction arguments. Several things
  764. // provide equivalent behavior with `FormatName`, so we provide that as the
  765. // default.
  766. template <typename IdT>
  767. auto FormatArg(IdT id) -> void {
  768. FormatName(id);
  769. }
  770. auto FormatArg(BoolValue v) -> void { out_ << v; }
  771. auto FormatArg(BuiltinInstKind kind) -> void { out_ << kind.label(); }
  772. auto FormatArg(EntityNameId id) -> void {
  773. const auto& info = sem_ir_.entity_names().Get(id);
  774. FormatName(info.name_id);
  775. if (info.bind_index.is_valid()) {
  776. out_ << " " << info.bind_index.index;
  777. }
  778. }
  779. auto FormatArg(IntKind k) -> void { k.Print(out_); }
  780. auto FormatArg(FloatKind k) -> void { k.Print(out_); }
  781. auto FormatArg(ImportIRId id) -> void {
  782. if (!id.is_valid()) {
  783. out_ << id;
  784. return;
  785. }
  786. const auto& import_ir = *sem_ir_.import_irs().Get(id).sem_ir;
  787. if (import_ir.package_id().is_valid()) {
  788. out_ << import_ir.identifiers().Get(import_ir.package_id());
  789. } else {
  790. out_ << "Main";
  791. }
  792. out_ << "//";
  793. CARBON_CHECK(import_ir.library_id().is_valid());
  794. if (import_ir.library_id() == LibraryNameId::Default) {
  795. out_ << "default";
  796. } else {
  797. out_ << import_ir.string_literal_values().Get(
  798. import_ir.library_id().AsStringLiteralValueId());
  799. }
  800. }
  801. auto FormatArg(ImportIRInstId id) -> void {
  802. // Don't format the inst_id because it refers to a different IR.
  803. // TODO: Consider a better way to format the InstID from other IRs.
  804. auto import_ir_inst = sem_ir_.import_ir_insts().Get(id);
  805. FormatArg(import_ir_inst.ir_id);
  806. out_ << ", " << import_ir_inst.inst_id;
  807. }
  808. auto FormatArg(IntId id) -> void {
  809. // We don't know the signedness to use here. Default to unsigned.
  810. sem_ir_.ints().Get(id).print(out_, /*isSigned=*/false);
  811. }
  812. auto FormatArg(LocId id) -> void {
  813. if (id.is_import_ir_inst_id()) {
  814. out_ << "{";
  815. FormatArg(id.import_ir_inst_id());
  816. out_ << "}";
  817. } else {
  818. // TODO: For a NodeId, this prints the index of the node. Do we want it to
  819. // print a line number or something in order to make it less dependent on
  820. // parse?
  821. out_ << id;
  822. }
  823. }
  824. auto FormatArg(ElementIndex index) -> void { out_ << index; }
  825. auto FormatArg(RuntimeParamIndex index) -> void { out_ << index; }
  826. auto FormatArg(NameScopeId id) -> void {
  827. OpenBrace();
  828. FormatNameScope(id);
  829. CloseBrace();
  830. }
  831. auto FormatArg(InstBlockId id) -> void {
  832. if (!id.is_valid()) {
  833. out_ << "invalid";
  834. return;
  835. }
  836. out_ << '(';
  837. llvm::ListSeparator sep;
  838. for (auto inst_id : sem_ir_.inst_blocks().Get(id)) {
  839. out_ << sep;
  840. FormatArg(inst_id);
  841. }
  842. out_ << ')';
  843. }
  844. auto FormatArg(RealId id) -> void {
  845. // TODO: Format with a `.` when the exponent is near zero.
  846. const auto& real = sem_ir_.reals().Get(id);
  847. real.mantissa.print(out_, /*isSigned=*/false);
  848. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  849. }
  850. auto FormatArg(StringLiteralValueId id) -> void {
  851. out_ << '"';
  852. out_.write_escaped(sem_ir_.string_literal_values().Get(id),
  853. /*UseHexEscapes=*/true);
  854. out_ << '"';
  855. }
  856. auto FormatArg(TypeId id) -> void { FormatType(id); }
  857. auto FormatArg(TypeBlockId id) -> void {
  858. out_ << '(';
  859. llvm::ListSeparator sep;
  860. for (auto type_id : sem_ir_.type_blocks().Get(id)) {
  861. out_ << sep;
  862. FormatArg(type_id);
  863. }
  864. out_ << ')';
  865. }
  866. auto FormatReturnSlot(InstId dest_id) -> void {
  867. out_ << " to ";
  868. FormatArg(dest_id);
  869. }
  870. // `FormatName` is used when we need the name from an id. Most id types use
  871. // equivalent name formatting from InstNamer, although there are a few special
  872. // formats below.
  873. template <typename IdT>
  874. auto FormatName(IdT id) -> void {
  875. out_ << inst_namer_->GetNameFor(id);
  876. }
  877. auto FormatName(NameId id) -> void {
  878. out_ << sem_ir_.names().GetFormatted(id);
  879. }
  880. auto FormatName(InstId id) -> void {
  881. out_ << inst_namer_->GetNameFor(scope_, id);
  882. }
  883. auto FormatName(AbsoluteInstId id) -> void {
  884. FormatName(static_cast<InstId>(id));
  885. }
  886. auto FormatName(SpecificId id) -> void {
  887. const auto& specific = sem_ir_.specifics().Get(id);
  888. FormatName(specific.generic_id);
  889. FormatArg(specific.args_id);
  890. }
  891. auto FormatLabel(InstBlockId id) -> void {
  892. out_ << inst_namer_->GetLabelFor(scope_, id);
  893. }
  894. auto FormatConstant(ConstantId id) -> void {
  895. if (!id.is_valid()) {
  896. out_ << "<not constant>";
  897. return;
  898. }
  899. // For a symbolic constant in a generic, list the constant value in the
  900. // generic first, and the canonical constant second.
  901. if (id.is_symbolic()) {
  902. const auto& symbolic_constant =
  903. sem_ir_.constant_values().GetSymbolicConstant(id);
  904. if (symbolic_constant.generic_id.is_valid()) {
  905. const auto& generic =
  906. sem_ir_.generics().Get(symbolic_constant.generic_id);
  907. FormatName(sem_ir_.inst_blocks().Get(generic.GetEvalBlock(
  908. symbolic_constant.index
  909. .region()))[symbolic_constant.index.index()]);
  910. out_ << " (";
  911. FormatName(sem_ir_.constant_values().GetInstId(id));
  912. out_ << ")";
  913. return;
  914. }
  915. }
  916. FormatName(sem_ir_.constant_values().GetInstId(id));
  917. }
  918. auto FormatType(TypeId id) -> void {
  919. if (!id.is_valid()) {
  920. out_ << "invalid";
  921. } else {
  922. // Types are formatted in the `constants` scope because they only refer to
  923. // constants.
  924. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  925. FormatConstant(sem_ir_.types().GetConstantId(id));
  926. }
  927. }
  928. const File& sem_ir_;
  929. InstNamer* const inst_namer_;
  930. // The output stream. Set while formatting instructions.
  931. llvm::raw_ostream& out_;
  932. // The current scope that we are formatting within. References to names in
  933. // this scope will not have a `@scope.` prefix added.
  934. InstNamer::ScopeId scope_ = InstNamer::ScopeId::None;
  935. // Whether we are formatting in a terminator sequence, that is, a sequence of
  936. // branches at the end of a block. The entirety of a terminator sequence is
  937. // formatted on a single line, despite being multiple instructions.
  938. bool in_terminator_sequence_ = false;
  939. // The indent depth to use for new instructions.
  940. int indent_;
  941. // Whether we are currently formatting immediately after an open brace. If so,
  942. // a newline will be inserted before the next line indent.
  943. bool after_open_brace_ = false;
  944. // The constant value of the current instruction, if it has one that has not
  945. // yet been printed. The value `NotConstant` is used as a sentinel to indicate
  946. // there is nothing to print.
  947. ConstantId pending_constant_value_ = ConstantId::NotConstant;
  948. // Whether `pending_constant_value_`'s instruction is the same as the
  949. // instruction currently being printed. If true, only the phase of the
  950. // constant is printed, and the value is omitted.
  951. bool pending_constant_value_is_self_ = false;
  952. };
  953. Formatter::Formatter(const Lex::TokenizedBuffer& tokenized_buffer,
  954. const Parse::Tree& parse_tree, const File& sem_ir)
  955. : sem_ir_(sem_ir), inst_namer_(tokenized_buffer, parse_tree, sem_ir) {}
  956. Formatter::~Formatter() = default;
  957. auto Formatter::Print(llvm::raw_ostream& out) -> void {
  958. FormatterImpl formatter(sem_ir_, &inst_namer_, out, /*indent=*/0);
  959. formatter.Format();
  960. }
  961. auto Formatter::PrintPartialTrailingCodeBlock(
  962. llvm::ArrayRef<SemIR::InstId> block, int indent, llvm::raw_ostream& out)
  963. -> void {
  964. FormatterImpl formatter(sem_ir_, &inst_namer_, out, indent);
  965. formatter.FormatPartialTrailingCodeBlock(block);
  966. }
  967. auto Formatter::PrintInst(SemIR::InstId inst_id, int indent,
  968. llvm::raw_ostream& out) -> void {
  969. FormatterImpl formatter(sem_ir_, &inst_namer_, out, indent);
  970. formatter.FormatInst(inst_id);
  971. }
  972. } // namespace Carbon::SemIR