formatter.cpp 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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", impl_info.generic_id, id);
  189. llvm::SaveAndRestore impl_scope(scope_, inst_namer_->GetScopeFor(id));
  190. out_ << ": ";
  191. FormatName(impl_info.self_id);
  192. out_ << " as ";
  193. FormatName(impl_info.constraint_id);
  194. if (impl_info.is_defined()) {
  195. out_ << ' ';
  196. OpenBrace();
  197. FormatCodeBlock(impl_info.body_block_id);
  198. // Print the !members label even if the name scope is empty because we
  199. // always list the witness in this section.
  200. IndentLabel();
  201. out_ << "!members:\n";
  202. if (impl_info.scope_id.is_valid()) {
  203. FormatNameScope(impl_info.scope_id);
  204. }
  205. Indent();
  206. out_ << "witness = ";
  207. FormatArg(impl_info.witness_id);
  208. out_ << "\n";
  209. CloseBrace();
  210. out_ << '\n';
  211. } else {
  212. out_ << ";\n";
  213. }
  214. FormatEntityEnd(impl_info.generic_id);
  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_patterns_id, /*is_implicit=*/true);
  240. FormatParamList(fn.param_patterns_id, /*is_implicit=*/false);
  241. if (fn.return_slot_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_slot_id);
  247. out_ << ": ";
  248. }
  249. FormatType(sem_ir_.insts().Get(fn.return_slot_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_patterns_id, bool is_implicit)
  382. -> void {
  383. if (!param_patterns_id.is_valid()) {
  384. return;
  385. }
  386. out_ << (is_implicit ? "[" : "(");
  387. llvm::ListSeparator sep;
  388. for (InstId param_id : sem_ir_.inst_blocks().Get(param_patterns_id)) {
  389. out_ << sep;
  390. if (!param_id.is_valid()) {
  391. out_ << "invalid";
  392. continue;
  393. }
  394. if (auto addr = sem_ir_.insts().TryGetAs<SemIR::AddrPattern>(param_id)) {
  395. out_ << "addr ";
  396. param_id = addr->inner_id;
  397. }
  398. FormatName(param_id);
  399. out_ << ": ";
  400. FormatType(sem_ir_.insts().Get(param_id).type_id());
  401. }
  402. out_ << (is_implicit ? "]" : ")");
  403. }
  404. // Prints instructions for a code block.
  405. auto FormatCodeBlock(InstBlockId block_id) -> void {
  406. if (block_id.is_valid()) {
  407. FormatCodeBlock(sem_ir_.inst_blocks().Get(block_id));
  408. }
  409. }
  410. // Prints instructions for a code block.
  411. auto FormatCodeBlock(llvm::ArrayRef<InstId> block) -> void {
  412. for (const InstId inst_id : block) {
  413. FormatInst(inst_id);
  414. }
  415. }
  416. // Prints a code block with braces, intended to be used trailing after other
  417. // content on the same line. If non-empty, instructions are on separate lines.
  418. auto FormatTrailingBlock(InstBlockId block_id) -> void {
  419. out_ << ' ';
  420. OpenBrace();
  421. FormatCodeBlock(block_id);
  422. CloseBrace();
  423. }
  424. // Prints the contents of a name scope, with an optional label.
  425. auto FormatNameScope(NameScopeId id, llvm::StringRef label = "") -> void {
  426. const auto& scope = sem_ir_.name_scopes().Get(id);
  427. if (scope.names.empty() && scope.extended_scopes.empty() &&
  428. scope.import_ir_scopes.empty() && !scope.has_error) {
  429. // Name scope is empty.
  430. return;
  431. }
  432. if (!label.empty()) {
  433. IndentLabel();
  434. out_ << label;
  435. }
  436. for (auto [name_id, inst_id, access_kind] : scope.names) {
  437. Indent();
  438. out_ << ".";
  439. FormatName(name_id);
  440. switch (access_kind) {
  441. case SemIR::AccessKind::Public:
  442. break;
  443. case SemIR::AccessKind::Protected:
  444. out_ << " [protected]";
  445. break;
  446. case SemIR::AccessKind::Private:
  447. out_ << " [private]";
  448. break;
  449. }
  450. out_ << " = ";
  451. FormatName(inst_id);
  452. out_ << "\n";
  453. }
  454. for (auto extended_scope_id : scope.extended_scopes) {
  455. // TODO: Print this scope in a better way.
  456. Indent();
  457. out_ << "extend " << extended_scope_id << "\n";
  458. }
  459. for (auto [import_ir_id, unused] : scope.import_ir_scopes) {
  460. Indent();
  461. out_ << "import ";
  462. FormatArg(import_ir_id);
  463. out_ << "\n";
  464. }
  465. if (scope.has_error) {
  466. Indent();
  467. out_ << "has_error\n";
  468. }
  469. }
  470. auto FormatInst(InstId inst_id, Inst inst) -> void {
  471. CARBON_KIND_SWITCH(inst) {
  472. #define CARBON_SEM_IR_INST_KIND(InstT) \
  473. case CARBON_KIND(InstT typed_inst): { \
  474. FormatInst(inst_id, typed_inst); \
  475. break; \
  476. }
  477. #include "toolchain/sem_ir/inst_kind.def"
  478. }
  479. }
  480. template <typename InstT>
  481. auto FormatInst(InstId inst_id, InstT inst) -> void {
  482. Indent();
  483. FormatInstLHS(inst_id, inst);
  484. out_ << InstT::Kind.ir_name();
  485. pending_constant_value_ = sem_ir_.constant_values().Get(inst_id);
  486. pending_constant_value_is_self_ =
  487. sem_ir_.constant_values().GetInstIdIfValid(pending_constant_value_) ==
  488. inst_id;
  489. FormatInstRHS(inst);
  490. FormatPendingConstantValue(AddSpace::Before);
  491. out_ << "\n";
  492. }
  493. // Don't print a constant for ImportRefUnloaded.
  494. auto FormatInst(InstId inst_id, ImportRefUnloaded inst) -> void {
  495. Indent();
  496. FormatInstLHS(inst_id, inst);
  497. out_ << ImportRefUnloaded::Kind.ir_name();
  498. FormatInstRHS(inst);
  499. out_ << "\n";
  500. }
  501. // If there is a pending constant value attached to the current instruction,
  502. // print it now and clear it out. The constant value gets printed before the
  503. // first braced block argument, or at the end of the instruction if there are
  504. // no such arguments.
  505. auto FormatPendingConstantValue(AddSpace space_where) -> void {
  506. if (pending_constant_value_ == ConstantId::NotConstant) {
  507. return;
  508. }
  509. if (space_where == AddSpace::Before) {
  510. out_ << ' ';
  511. }
  512. out_ << '[';
  513. if (pending_constant_value_.is_valid()) {
  514. out_ << (pending_constant_value_.is_symbolic() ? "symbolic" : "template");
  515. if (!pending_constant_value_is_self_) {
  516. out_ << " = ";
  517. FormatConstant(pending_constant_value_);
  518. }
  519. } else {
  520. out_ << pending_constant_value_;
  521. }
  522. out_ << ']';
  523. if (space_where == AddSpace::After) {
  524. out_ << ' ';
  525. }
  526. pending_constant_value_ = ConstantId::NotConstant;
  527. }
  528. auto FormatInstLHS(InstId inst_id, Inst inst) -> void {
  529. switch (inst.kind().value_kind()) {
  530. case InstValueKind::Typed:
  531. FormatName(inst_id);
  532. out_ << ": ";
  533. switch (GetExprCategory(sem_ir_, inst_id)) {
  534. case ExprCategory::NotExpr:
  535. case ExprCategory::Error:
  536. case ExprCategory::Value:
  537. case ExprCategory::Mixed:
  538. break;
  539. case ExprCategory::DurableRef:
  540. case ExprCategory::EphemeralRef:
  541. out_ << "ref ";
  542. break;
  543. case ExprCategory::Initializing:
  544. out_ << "init ";
  545. break;
  546. }
  547. FormatType(inst.type_id());
  548. out_ << " = ";
  549. break;
  550. case InstValueKind::None:
  551. break;
  552. }
  553. }
  554. // Format ImportDecl with its name.
  555. auto FormatInstLHS(InstId inst_id, ImportDecl /*inst*/) -> void {
  556. FormatName(inst_id);
  557. out_ << " = ";
  558. }
  559. // Print ImportRefUnloaded with type-like semantics even though it lacks a
  560. // type_id.
  561. auto FormatInstLHS(InstId inst_id, ImportRefUnloaded /*inst*/) -> void {
  562. FormatName(inst_id);
  563. out_ << " = ";
  564. }
  565. template <typename InstT>
  566. auto FormatInstRHS(InstT inst) -> void {
  567. // By default, an instruction has a comma-separated argument list.
  568. using Info = Internal::InstLikeTypeInfo<InstT>;
  569. if constexpr (Info::NumArgs == 2) {
  570. // Several instructions have a second operand that's a specific ID. We
  571. // don't include it in the argument list if there is no corresponding
  572. // specific, that is, when we're not in a generic context.
  573. if constexpr (std::is_same_v<typename Info::template ArgType<1>,
  574. SemIR::SpecificId>) {
  575. if (!Info::template Get<1>(inst).is_valid()) {
  576. FormatArgs(Info::template Get<0>(inst));
  577. return;
  578. }
  579. }
  580. FormatArgs(Info::template Get<0>(inst), Info::template Get<1>(inst));
  581. } else if constexpr (Info::NumArgs == 1) {
  582. FormatArgs(Info::template Get<0>(inst));
  583. } else {
  584. FormatArgs();
  585. }
  586. }
  587. auto FormatInstRHS(BindSymbolicName inst) -> void {
  588. // A BindSymbolicName with no value is a purely symbolic binding, such as
  589. // the `Self` in an interface. Don't print out `invalid` for the value.
  590. if (inst.value_id.is_valid()) {
  591. FormatArgs(inst.entity_name_id, inst.value_id);
  592. } else {
  593. FormatArgs(inst.entity_name_id);
  594. }
  595. }
  596. auto FormatInstRHS(BlockArg inst) -> void {
  597. out_ << " ";
  598. FormatLabel(inst.block_id);
  599. }
  600. auto FormatInstRHS(Namespace inst) -> void {
  601. if (inst.import_id.is_valid()) {
  602. FormatArgs(inst.import_id, inst.name_scope_id);
  603. } else {
  604. FormatArgs(inst.name_scope_id);
  605. }
  606. }
  607. auto FormatInst(InstId /*inst_id*/, BranchIf inst) -> void {
  608. if (!in_terminator_sequence_) {
  609. Indent();
  610. }
  611. out_ << "if ";
  612. FormatName(inst.cond_id);
  613. out_ << " " << Branch::Kind.ir_name() << " ";
  614. FormatLabel(inst.target_id);
  615. out_ << " else ";
  616. in_terminator_sequence_ = true;
  617. }
  618. auto FormatInst(InstId /*inst_id*/, BranchWithArg inst) -> void {
  619. if (!in_terminator_sequence_) {
  620. Indent();
  621. }
  622. out_ << BranchWithArg::Kind.ir_name() << " ";
  623. FormatLabel(inst.target_id);
  624. out_ << "(";
  625. FormatName(inst.arg_id);
  626. out_ << ")\n";
  627. in_terminator_sequence_ = false;
  628. }
  629. auto FormatInst(InstId /*inst_id*/, Branch inst) -> void {
  630. if (!in_terminator_sequence_) {
  631. Indent();
  632. }
  633. out_ << Branch::Kind.ir_name() << " ";
  634. FormatLabel(inst.target_id);
  635. out_ << "\n";
  636. in_terminator_sequence_ = false;
  637. }
  638. auto FormatInstRHS(Call inst) -> void {
  639. out_ << " ";
  640. FormatArg(inst.callee_id);
  641. if (!inst.args_id.is_valid()) {
  642. out_ << "(<invalid>)";
  643. return;
  644. }
  645. llvm::ArrayRef<InstId> args = sem_ir_.inst_blocks().Get(inst.args_id);
  646. auto return_info = ReturnTypeInfo::ForType(sem_ir_, inst.type_id);
  647. bool has_return_slot = return_info.has_return_slot();
  648. InstId return_slot_id = InstId::Invalid;
  649. if (has_return_slot) {
  650. return_slot_id = args.back();
  651. args = args.drop_back();
  652. }
  653. llvm::ListSeparator sep;
  654. out_ << '(';
  655. for (auto inst_id : args) {
  656. out_ << sep;
  657. FormatArg(inst_id);
  658. }
  659. out_ << ')';
  660. if (has_return_slot) {
  661. FormatReturnSlot(return_slot_id);
  662. }
  663. }
  664. auto FormatInstRHS(ArrayInit inst) -> void {
  665. FormatArgs(inst.inits_id);
  666. FormatReturnSlot(inst.dest_id);
  667. }
  668. auto FormatInstRHS(InitializeFrom inst) -> void {
  669. FormatArgs(inst.src_id);
  670. FormatReturnSlot(inst.dest_id);
  671. }
  672. auto FormatInstRHS(Param inst) -> void {
  673. FormatArgs(inst.runtime_index);
  674. // Omit pretty_name because it's an implementation detail of
  675. // pretty-printing.
  676. }
  677. auto FormatInstRHS(ReturnExpr ret) -> void {
  678. FormatArgs(ret.expr_id);
  679. if (ret.dest_id.is_valid()) {
  680. FormatReturnSlot(ret.dest_id);
  681. }
  682. }
  683. auto FormatInstRHS(ReturnSlot inst) -> void {
  684. // Omit inst.type_inst_id because it's not semantically significant.
  685. FormatArgs(inst.storage_id);
  686. }
  687. auto FormatInstRHS(ReturnSlotPattern /*inst*/) -> void {
  688. // No-op because type_id is the only semantically significant field,
  689. // and it's handled separately.
  690. }
  691. auto FormatInstRHS(StructInit init) -> void {
  692. FormatArgs(init.elements_id);
  693. FormatReturnSlot(init.dest_id);
  694. }
  695. auto FormatInstRHS(TupleInit init) -> void {
  696. FormatArgs(init.elements_id);
  697. FormatReturnSlot(init.dest_id);
  698. }
  699. auto FormatInstRHS(FunctionDecl inst) -> void {
  700. FormatArgs(inst.function_id);
  701. llvm::SaveAndRestore class_scope(
  702. scope_, inst_namer_->GetScopeFor(inst.function_id));
  703. FormatTrailingBlock(
  704. sem_ir_.functions().Get(inst.function_id).pattern_block_id);
  705. FormatTrailingBlock(inst.decl_block_id);
  706. }
  707. auto FormatInstRHS(ClassDecl inst) -> void {
  708. FormatArgs(inst.class_id);
  709. llvm::SaveAndRestore class_scope(scope_,
  710. inst_namer_->GetScopeFor(inst.class_id));
  711. FormatTrailingBlock(sem_ir_.classes().Get(inst.class_id).pattern_block_id);
  712. FormatTrailingBlock(inst.decl_block_id);
  713. }
  714. auto FormatInstRHS(ImplDecl inst) -> void {
  715. FormatArgs(inst.impl_id);
  716. llvm::SaveAndRestore class_scope(scope_,
  717. inst_namer_->GetScopeFor(inst.impl_id));
  718. FormatTrailingBlock(sem_ir_.impls().Get(inst.impl_id).pattern_block_id);
  719. FormatTrailingBlock(inst.decl_block_id);
  720. }
  721. auto FormatInstRHS(InterfaceDecl inst) -> void {
  722. FormatArgs(inst.interface_id);
  723. llvm::SaveAndRestore class_scope(
  724. scope_, inst_namer_->GetScopeFor(inst.interface_id));
  725. FormatTrailingBlock(
  726. sem_ir_.interfaces().Get(inst.interface_id).pattern_block_id);
  727. FormatTrailingBlock(inst.decl_block_id);
  728. }
  729. auto FormatInstRHS(IntLiteral inst) -> void {
  730. out_ << " ";
  731. sem_ir_.ints()
  732. .Get(inst.int_id)
  733. .print(out_, sem_ir_.types().IsSignedInt(inst.type_id));
  734. }
  735. auto FormatInstRHS(FloatLiteral inst) -> void {
  736. llvm::SmallVector<char, 16> buffer;
  737. sem_ir_.floats().Get(inst.float_id).toString(buffer);
  738. out_ << " " << buffer;
  739. }
  740. auto FormatInstRHS(ImportRefUnloaded inst) -> void {
  741. FormatArgs(inst.import_ir_inst_id);
  742. out_ << ", unloaded";
  743. }
  744. auto FormatInstRHS(ImportRefLoaded inst) -> void {
  745. FormatArgs(inst.import_ir_inst_id);
  746. out_ << ", loaded";
  747. }
  748. auto FormatInstRHS(SpliceBlock inst) -> void {
  749. FormatArgs(inst.result_id);
  750. FormatTrailingBlock(inst.block_id);
  751. }
  752. auto FormatInstRHS(WhereExpr inst) -> void {
  753. FormatArgs(inst.period_self_id);
  754. FormatTrailingBlock(inst.requirements_id);
  755. }
  756. // StructTypeFields are formatted as part of their StructType.
  757. auto FormatInst(InstId /*inst_id*/, StructTypeField /*inst*/) -> void {}
  758. auto FormatInstRHS(StructType inst) -> void {
  759. out_ << " {";
  760. llvm::ListSeparator sep;
  761. for (auto field_id : sem_ir_.inst_blocks().Get(inst.fields_id)) {
  762. out_ << sep << ".";
  763. auto field = sem_ir_.insts().GetAs<StructTypeField>(field_id);
  764. FormatName(field.name_id);
  765. out_ << ": ";
  766. FormatType(field.field_type_id);
  767. }
  768. out_ << "}";
  769. }
  770. auto FormatArgs() -> void {}
  771. template <typename... Args>
  772. auto FormatArgs(Args... args) -> void {
  773. out_ << ' ';
  774. llvm::ListSeparator sep;
  775. FormatArgsImpl(sep, args...);
  776. }
  777. auto FormatArgsImpl(llvm::ListSeparator& /* sep */) -> void {}
  778. template <typename Arg, typename... Args>
  779. auto FormatArgsImpl(llvm::ListSeparator& sep, Arg arg, Args... args) -> void {
  780. // Suppress printing MatchingInstIds, which aren't really operands.
  781. if constexpr (!std::is_same_v<Arg, SemIR::MatchingInstId>) {
  782. out_ << sep;
  783. FormatArg(arg);
  784. }
  785. FormatArgsImpl(sep, args...);
  786. }
  787. // FormatArg variants handling printing instruction arguments. Several things
  788. // provide equivalent behavior with `FormatName`, so we provide that as the
  789. // default.
  790. template <typename IdT>
  791. auto FormatArg(IdT id) -> void {
  792. FormatName(id);
  793. }
  794. auto FormatArg(BoolValue v) -> void { out_ << v; }
  795. auto FormatArg(BuiltinInstKind kind) -> void { out_ << kind.label(); }
  796. auto FormatArg(EntityNameId id) -> void {
  797. const auto& info = sem_ir_.entity_names().Get(id);
  798. FormatName(info.name_id);
  799. if (info.bind_index.is_valid()) {
  800. out_ << ", " << info.bind_index.index;
  801. }
  802. }
  803. auto FormatArg(IntKind k) -> void { k.Print(out_); }
  804. auto FormatArg(FloatKind k) -> void { k.Print(out_); }
  805. auto FormatArg(ImportIRId id) -> void {
  806. if (!id.is_valid()) {
  807. out_ << id;
  808. return;
  809. }
  810. const auto& import_ir = *sem_ir_.import_irs().Get(id).sem_ir;
  811. if (import_ir.package_id().is_valid()) {
  812. out_ << import_ir.identifiers().Get(import_ir.package_id());
  813. } else {
  814. out_ << "Main";
  815. }
  816. out_ << "//";
  817. CARBON_CHECK(import_ir.library_id().is_valid());
  818. if (import_ir.library_id() == LibraryNameId::Default) {
  819. out_ << "default";
  820. } else {
  821. out_ << import_ir.string_literal_values().Get(
  822. import_ir.library_id().AsStringLiteralValueId());
  823. }
  824. }
  825. auto FormatArg(ImportIRInstId id) -> void {
  826. // Don't format the inst_id because it refers to a different IR.
  827. // TODO: Consider a better way to format the InstID from other IRs.
  828. auto import_ir_inst = sem_ir_.import_ir_insts().Get(id);
  829. FormatArg(import_ir_inst.ir_id);
  830. out_ << ", " << import_ir_inst.inst_id;
  831. }
  832. auto FormatArg(IntId id) -> void {
  833. // We don't know the signedness to use here. Default to unsigned.
  834. sem_ir_.ints().Get(id).print(out_, /*isSigned=*/false);
  835. }
  836. auto FormatArg(LocId id) -> void {
  837. if (id.is_import_ir_inst_id()) {
  838. out_ << "{";
  839. FormatArg(id.import_ir_inst_id());
  840. out_ << "}";
  841. } else {
  842. // TODO: For a NodeId, this prints the index of the node. Do we want it to
  843. // print a line number or something in order to make it less dependent on
  844. // parse?
  845. out_ << id;
  846. }
  847. }
  848. auto FormatArg(ElementIndex index) -> void { out_ << index; }
  849. auto FormatArg(RuntimeParamIndex index) -> void { out_ << index; }
  850. auto FormatArg(NameScopeId id) -> void {
  851. OpenBrace();
  852. FormatNameScope(id);
  853. CloseBrace();
  854. }
  855. auto FormatArg(InstBlockId id) -> void {
  856. if (!id.is_valid()) {
  857. out_ << "invalid";
  858. return;
  859. }
  860. out_ << '(';
  861. llvm::ListSeparator sep;
  862. for (auto inst_id : sem_ir_.inst_blocks().Get(id)) {
  863. out_ << sep;
  864. FormatArg(inst_id);
  865. }
  866. out_ << ')';
  867. }
  868. auto FormatArg(RealId id) -> void {
  869. // TODO: Format with a `.` when the exponent is near zero.
  870. const auto& real = sem_ir_.reals().Get(id);
  871. real.mantissa.print(out_, /*isSigned=*/false);
  872. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  873. }
  874. auto FormatArg(StringLiteralValueId id) -> void {
  875. out_ << '"';
  876. out_.write_escaped(sem_ir_.string_literal_values().Get(id),
  877. /*UseHexEscapes=*/true);
  878. out_ << '"';
  879. }
  880. auto FormatArg(TypeId id) -> void { FormatType(id); }
  881. auto FormatArg(TypeBlockId id) -> void {
  882. out_ << '(';
  883. llvm::ListSeparator sep;
  884. for (auto type_id : sem_ir_.type_blocks().Get(id)) {
  885. out_ << sep;
  886. FormatArg(type_id);
  887. }
  888. out_ << ')';
  889. }
  890. auto FormatReturnSlot(InstId dest_id) -> void {
  891. out_ << " to ";
  892. FormatArg(dest_id);
  893. }
  894. // `FormatName` is used when we need the name from an id. Most id types use
  895. // equivalent name formatting from InstNamer, although there are a few special
  896. // formats below.
  897. template <typename IdT>
  898. auto FormatName(IdT id) -> void {
  899. out_ << inst_namer_->GetNameFor(id);
  900. }
  901. auto FormatName(NameId id) -> void {
  902. out_ << sem_ir_.names().GetFormatted(id);
  903. }
  904. auto FormatName(InstId id) -> void {
  905. out_ << inst_namer_->GetNameFor(scope_, id);
  906. }
  907. auto FormatName(AbsoluteInstId id) -> void {
  908. FormatName(static_cast<InstId>(id));
  909. }
  910. auto FormatName(SpecificId id) -> void {
  911. const auto& specific = sem_ir_.specifics().Get(id);
  912. FormatName(specific.generic_id);
  913. FormatArg(specific.args_id);
  914. }
  915. auto FormatLabel(InstBlockId id) -> void {
  916. out_ << inst_namer_->GetLabelFor(scope_, id);
  917. }
  918. auto FormatConstant(ConstantId id) -> void {
  919. if (!id.is_valid()) {
  920. out_ << "<not constant>";
  921. return;
  922. }
  923. // For a symbolic constant in a generic, list the constant value in the
  924. // generic first, and the canonical constant second.
  925. if (id.is_symbolic()) {
  926. const auto& symbolic_constant =
  927. sem_ir_.constant_values().GetSymbolicConstant(id);
  928. if (symbolic_constant.generic_id.is_valid()) {
  929. const auto& generic =
  930. sem_ir_.generics().Get(symbolic_constant.generic_id);
  931. FormatName(sem_ir_.inst_blocks().Get(generic.GetEvalBlock(
  932. symbolic_constant.index
  933. .region()))[symbolic_constant.index.index()]);
  934. out_ << " (";
  935. FormatName(sem_ir_.constant_values().GetInstId(id));
  936. out_ << ")";
  937. return;
  938. }
  939. }
  940. FormatName(sem_ir_.constant_values().GetInstId(id));
  941. }
  942. auto FormatType(TypeId id) -> void {
  943. if (!id.is_valid()) {
  944. out_ << "invalid";
  945. } else {
  946. // Types are formatted in the `constants` scope because they only refer to
  947. // constants.
  948. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  949. FormatConstant(sem_ir_.types().GetConstantId(id));
  950. }
  951. }
  952. const File& sem_ir_;
  953. InstNamer* const inst_namer_;
  954. // The output stream. Set while formatting instructions.
  955. llvm::raw_ostream& out_;
  956. // The current scope that we are formatting within. References to names in
  957. // this scope will not have a `@scope.` prefix added.
  958. InstNamer::ScopeId scope_ = InstNamer::ScopeId::None;
  959. // Whether we are formatting in a terminator sequence, that is, a sequence of
  960. // branches at the end of a block. The entirety of a terminator sequence is
  961. // formatted on a single line, despite being multiple instructions.
  962. bool in_terminator_sequence_ = false;
  963. // The indent depth to use for new instructions.
  964. int indent_;
  965. // Whether we are currently formatting immediately after an open brace. If so,
  966. // a newline will be inserted before the next line indent.
  967. bool after_open_brace_ = false;
  968. // The constant value of the current instruction, if it has one that has not
  969. // yet been printed. The value `NotConstant` is used as a sentinel to indicate
  970. // there is nothing to print.
  971. ConstantId pending_constant_value_ = ConstantId::NotConstant;
  972. // Whether `pending_constant_value_`'s instruction is the same as the
  973. // instruction currently being printed. If true, only the phase of the
  974. // constant is printed, and the value is omitted.
  975. bool pending_constant_value_is_self_ = false;
  976. };
  977. Formatter::Formatter(const Lex::TokenizedBuffer& tokenized_buffer,
  978. const Parse::Tree& parse_tree, const File& sem_ir)
  979. : sem_ir_(sem_ir), inst_namer_(tokenized_buffer, parse_tree, sem_ir) {}
  980. Formatter::~Formatter() = default;
  981. auto Formatter::Print(llvm::raw_ostream& out) -> void {
  982. FormatterImpl formatter(sem_ir_, &inst_namer_, out, /*indent=*/0);
  983. formatter.Format();
  984. }
  985. auto Formatter::PrintPartialTrailingCodeBlock(
  986. llvm::ArrayRef<SemIR::InstId> block, int indent, llvm::raw_ostream& out)
  987. -> void {
  988. FormatterImpl formatter(sem_ir_, &inst_namer_, out, indent);
  989. formatter.FormatPartialTrailingCodeBlock(block);
  990. }
  991. auto Formatter::PrintInst(SemIR::InstId inst_id, int indent,
  992. llvm::raw_ostream& out) -> void {
  993. FormatterImpl formatter(sem_ir_, &inst_namer_, out, indent);
  994. formatter.FormatInst(inst_id);
  995. }
  996. } // namespace Carbon::SemIR