formatter.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657
  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 <string>
  6. #include <utility>
  7. #include "common/ostream.h"
  8. #include "llvm/ADT/Sequence.h"
  9. #include "llvm/ADT/StringExtras.h"
  10. #include "llvm/Support/SaveAndRestore.h"
  11. #include "toolchain/base/fixed_size_value_store.h"
  12. #include "toolchain/base/kind_switch.h"
  13. #include "toolchain/base/shared_value_stores.h"
  14. #include "toolchain/lex/tokenized_buffer.h"
  15. #include "toolchain/parse/tree.h"
  16. #include "toolchain/parse/tree_and_subtrees.h"
  17. #include "toolchain/sem_ir/builtin_function_kind.h"
  18. #include "toolchain/sem_ir/constant.h"
  19. #include "toolchain/sem_ir/entity_with_params_base.h"
  20. #include "toolchain/sem_ir/expr_info.h"
  21. #include "toolchain/sem_ir/function.h"
  22. #include "toolchain/sem_ir/ids.h"
  23. #include "toolchain/sem_ir/name_scope.h"
  24. #include "toolchain/sem_ir/typed_insts.h"
  25. #include "toolchain/sem_ir/vtable.h"
  26. // TODO: Consider addressing recursion here, although it's not critical because
  27. // the formatter isn't required to work on arbitrary code. Still, it may help
  28. // in the future to debug complex code.
  29. // NOLINTBEGIN(misc-no-recursion)
  30. namespace Carbon::SemIR {
  31. Formatter::Formatter(
  32. const File* sem_ir, int total_ir_count,
  33. Parse::GetTreeAndSubtreesFn get_tree_and_subtrees,
  34. const FixedSizeValueStore<CheckIRId, bool>* include_ir_in_dumps,
  35. bool use_dump_sem_ir_ranges)
  36. : sem_ir_(sem_ir),
  37. inst_namer_(sem_ir_, total_ir_count),
  38. get_tree_and_subtrees_(get_tree_and_subtrees),
  39. include_ir_in_dumps_(include_ir_in_dumps),
  40. use_dump_sem_ir_ranges_(use_dump_sem_ir_ranges),
  41. // Create a placeholder visible chunk and assign it to all instructions
  42. // that don't have a chunk of their own.
  43. tentative_inst_chunks_(sem_ir_->insts(), AddChunkNoFlush(true)) {
  44. if (use_dump_sem_ir_ranges_) {
  45. ComputeNodeParents();
  46. }
  47. // Create empty placeholder chunks for instructions that we output lazily.
  48. for (auto inst_id : llvm::concat<const InstId>(
  49. sem_ir_->constants().array_ref(),
  50. sem_ir_->inst_blocks().Get(InstBlockId::Imports))) {
  51. tentative_inst_chunks_.Set(inst_id, AddChunkNoFlush(false));
  52. }
  53. // Create a real chunk for the start of the output.
  54. AddChunkNoFlush(true);
  55. }
  56. auto Formatter::Format() -> void {
  57. out_ << "--- " << sem_ir_->filename() << "\n";
  58. FormatTopLevelScopeIfUsed(InstNamer::ScopeId::Constants,
  59. sem_ir_->constants().array_ref(),
  60. /*use_tentative_output_scopes=*/true);
  61. FormatTopLevelScopeIfUsed(InstNamer::ScopeId::Imports,
  62. sem_ir_->inst_blocks().Get(InstBlockId::Imports),
  63. /*use_tentative_output_scopes=*/true);
  64. FormatTopLevelScopeIfUsed(
  65. InstNamer::ScopeId::File,
  66. sem_ir_->inst_blocks().GetOrEmpty(sem_ir_->top_inst_block_id()),
  67. /*use_tentative_output_scopes=*/false);
  68. for (const auto& [id, interface] : sem_ir_->interfaces().enumerate()) {
  69. FormatInterface(id, interface);
  70. }
  71. for (const auto& [id, constraint] :
  72. sem_ir_->named_constraints().enumerate()) {
  73. FormatNamedConstraint(id, constraint);
  74. }
  75. for (const auto& [id, require] : sem_ir_->require_impls().enumerate()) {
  76. FormatRequireImpls(id, require);
  77. }
  78. for (const auto& [id, assoc_const] :
  79. sem_ir_->associated_constants().enumerate()) {
  80. FormatAssociatedConstant(id, assoc_const);
  81. }
  82. for (const auto& [id, impl] : sem_ir_->impls().enumerate()) {
  83. FormatImpl(id, impl);
  84. }
  85. for (const auto& [id, class_info] : sem_ir_->classes().enumerate()) {
  86. FormatClass(id, class_info);
  87. }
  88. for (const auto& [id, vtable] : sem_ir_->vtables().enumerate()) {
  89. FormatVtable(id, vtable);
  90. }
  91. for (const auto& [id, function] : sem_ir_->functions().enumerate()) {
  92. FormatFunction(id, function);
  93. }
  94. for (const auto& [id, specific] : sem_ir_->specifics().enumerate()) {
  95. FormatSpecific(id, specific);
  96. }
  97. out_ << "\n";
  98. }
  99. auto Formatter::ComputeNodeParents() -> void {
  100. CARBON_CHECK(!node_parents_);
  101. node_parents_ = NodeParentStore::MakeWithExplicitSize(
  102. sem_ir_->parse_tree().size(), Parse::NodeId::None);
  103. for (auto n : sem_ir_->parse_tree().postorder()) {
  104. for (auto child : get_tree_and_subtrees_().children(n)) {
  105. node_parents_->Set(child, n);
  106. }
  107. }
  108. }
  109. auto Formatter::Write(llvm::raw_ostream& out) -> void {
  110. FlushChunk();
  111. for (const auto& chunk : output_chunks_) {
  112. if (chunk.include_in_output) {
  113. out << chunk.chunk;
  114. }
  115. }
  116. }
  117. auto Formatter::FlushChunk() -> void {
  118. CARBON_CHECK(output_chunks_.back().chunk.empty());
  119. output_chunks_.back().chunk = std::move(buffer_);
  120. buffer_.clear();
  121. }
  122. auto Formatter::AddChunkNoFlush(bool include_in_output) -> size_t {
  123. CARBON_CHECK(buffer_.empty());
  124. output_chunks_.push_back({.include_in_output = include_in_output});
  125. return output_chunks_.size() - 1;
  126. }
  127. auto Formatter::AddChunk(bool include_in_output) -> size_t {
  128. FlushChunk();
  129. return AddChunkNoFlush(include_in_output);
  130. }
  131. auto Formatter::IncludeChunkInOutput(size_t chunk) -> void {
  132. if (chunk == output_chunks_.size() - 1) {
  133. return;
  134. }
  135. if (auto& current_chunk = output_chunks_.back();
  136. !current_chunk.include_in_output) {
  137. current_chunk.dependencies.push_back(chunk);
  138. return;
  139. }
  140. llvm::SmallVector<size_t> to_add = {chunk};
  141. while (!to_add.empty()) {
  142. auto& chunk = output_chunks_[to_add.pop_back_val()];
  143. if (chunk.include_in_output) {
  144. continue;
  145. }
  146. chunk.include_in_output = true;
  147. to_add.append(chunk.dependencies);
  148. chunk.dependencies.clear();
  149. }
  150. }
  151. auto Formatter::ShouldIncludeInstByIR(InstId inst_id) -> bool {
  152. const auto* import_ir = GetCanonicalFileAndInstId(sem_ir_, inst_id).first;
  153. return include_ir_in_dumps_->Get(import_ir->check_ir_id());
  154. }
  155. // Returns true for a `DefinitionStart` node.
  156. static auto IsDefinitionStart(Parse::NodeKind node_kind) -> bool {
  157. switch (node_kind) {
  158. case Parse::NodeKind::BuiltinFunctionDefinitionStart:
  159. case Parse::NodeKind::ChoiceDefinitionStart:
  160. case Parse::NodeKind::ClassDefinitionStart:
  161. case Parse::NodeKind::FunctionDefinitionStart:
  162. case Parse::NodeKind::ImplDefinitionStart:
  163. case Parse::NodeKind::InterfaceDefinitionStart:
  164. case Parse::NodeKind::NamedConstraintDefinitionStart:
  165. return true;
  166. default:
  167. return false;
  168. }
  169. }
  170. auto Formatter::ShouldFormatEntity(InstId decl_id) -> bool {
  171. if (!decl_id.has_value()) {
  172. return true;
  173. }
  174. if (!ShouldIncludeInstByIR(decl_id)) {
  175. return false;
  176. }
  177. if (!use_dump_sem_ir_ranges_) {
  178. return true;
  179. }
  180. // When there are dump ranges, ignore imported instructions.
  181. auto loc_id = sem_ir_->insts().GetCanonicalLocId(decl_id);
  182. if (loc_id.kind() != LocId::Kind::NodeId) {
  183. return false;
  184. }
  185. const auto& tree_and_subtrees = get_tree_and_subtrees_();
  186. // This takes the earliest token from either the node or its first postorder
  187. // child. The first postorder child isn't necessarily the earliest token in
  188. // the subtree (for example, it can miss modifiers), but finding the earliest
  189. // token requires walking *all* children, whereas this approach is
  190. // constant-time.
  191. auto begin_node_id = *tree_and_subtrees.postorder(loc_id.node_id()).begin();
  192. // Non-defining declarations will be associated with a `Decl` node.
  193. // Definitions will have a `DefinitionStart` for which we can use the parent
  194. // to find the `Definition`, giving a range that includes the definition's
  195. // body.
  196. auto end_node_id = loc_id.node_id();
  197. if (IsDefinitionStart(sem_ir_->parse_tree().node_kind(end_node_id))) {
  198. end_node_id = node_parents_->Get(end_node_id);
  199. }
  200. Lex::InclusiveTokenRange range = {
  201. .begin = sem_ir_->parse_tree().node_token(begin_node_id),
  202. .end = sem_ir_->parse_tree().node_token(end_node_id)};
  203. return sem_ir_->parse_tree().tokens().OverlapsWithDumpSemIRRange(range);
  204. }
  205. auto Formatter::ShouldFormatEntity(const EntityWithParamsBase& entity) -> bool {
  206. return ShouldFormatEntity(entity.latest_decl_id());
  207. }
  208. auto Formatter::ShouldFormatInst(InstId inst_id) -> bool {
  209. if (!use_dump_sem_ir_ranges_) {
  210. return true;
  211. }
  212. // When there are dump ranges, ignore imported instructions.
  213. auto loc_id = sem_ir_->insts().GetCanonicalLocId(inst_id);
  214. if (loc_id.kind() != LocId::Kind::NodeId) {
  215. return false;
  216. }
  217. auto token = sem_ir_->parse_tree().node_token(loc_id.node_id());
  218. return sem_ir_->parse_tree().tokens().OverlapsWithDumpSemIRRange(
  219. Lex::InclusiveTokenRange{.begin = token, .end = token});
  220. }
  221. auto Formatter::OpenBrace() -> void {
  222. // Put the constant value of an instruction before any braced block, rather
  223. // than at the end.
  224. FormatPendingConstantValue(AddSpace::After);
  225. // Put the imported-from library name before the definition of the entity.
  226. FormatPendingImportedFrom(AddSpace::After);
  227. out_ << '{';
  228. indent_ += 2;
  229. after_open_brace_ = true;
  230. }
  231. auto Formatter::CloseBrace() -> void {
  232. indent_ -= 2;
  233. if (!after_open_brace_) {
  234. Indent();
  235. }
  236. out_ << '}';
  237. after_open_brace_ = false;
  238. }
  239. auto Formatter::Semicolon() -> void {
  240. FormatPendingImportedFrom(AddSpace::Before);
  241. out_ << ';';
  242. }
  243. auto Formatter::Indent(int offset) -> void {
  244. if (after_open_brace_) {
  245. out_ << '\n';
  246. after_open_brace_ = false;
  247. }
  248. out_.indent(indent_ + offset);
  249. }
  250. auto Formatter::IndentLabel() -> void {
  251. CARBON_CHECK(indent_ >= 2);
  252. if (!after_open_brace_) {
  253. out_ << '\n';
  254. }
  255. Indent(-2);
  256. }
  257. auto Formatter::FormatTopLevelScopeIfUsed(InstNamer::ScopeId scope_id,
  258. llvm::ArrayRef<InstId> block,
  259. bool use_tentative_output_scopes)
  260. -> void {
  261. if (!use_tentative_output_scopes && use_dump_sem_ir_ranges_) {
  262. // Don't format the scope if no instructions are in a dump range.
  263. block = block.drop_while(
  264. [&](InstId inst_id) { return !ShouldFormatInst(inst_id); });
  265. }
  266. if (block.empty()) {
  267. return;
  268. }
  269. llvm::SaveAndRestore scope(scope_, scope_id);
  270. // Note, we don't use OpenBrace() / CloseBrace() here because we always want
  271. // a newline to avoid misformatting if the first instruction is omitted.
  272. out_ << "\n" << inst_namer_.GetScopeName(scope_id) << " {\n";
  273. indent_ += 2;
  274. for (const InstId inst_id : block) {
  275. // Format instructions when needed, but do nothing for elided entries;
  276. // unlike normal code blocks, scopes are non-sequential so skipped
  277. // instructions are assumed to be uninteresting.
  278. if (use_tentative_output_scopes) {
  279. // This is for constants and imports. These use tentative logic to
  280. // determine whether an instruction is printed.
  281. TentativeOutputScope scope(*this, tentative_inst_chunks_.Get(inst_id));
  282. FormatInst(inst_id);
  283. } else if (ShouldFormatInst(inst_id)) {
  284. // This is for the file scope. It uses only the range-based filtering.
  285. FormatInst(inst_id);
  286. }
  287. }
  288. out_ << "}\n";
  289. indent_ -= 2;
  290. }
  291. auto Formatter::FormatClass(ClassId id, const Class& class_info) -> void {
  292. if (!ShouldFormatEntity(class_info)) {
  293. return;
  294. }
  295. PrepareToFormatDecl(class_info.first_owning_decl_id);
  296. FormatEntityStart("class", class_info, id);
  297. llvm::SaveAndRestore class_scope(scope_, inst_namer_.GetScopeFor(id));
  298. if (class_info.scope_id.has_value()) {
  299. out_ << ' ';
  300. OpenBrace();
  301. FormatCodeBlock(class_info.body_block_id);
  302. Indent();
  303. out_ << "complete_type_witness = ";
  304. FormatName(class_info.complete_type_witness_id);
  305. out_ << "\n";
  306. if (class_info.vtable_decl_id.has_value()) {
  307. Indent();
  308. out_ << "vtable_decl = ";
  309. FormatName(class_info.vtable_decl_id);
  310. out_ << "\n";
  311. }
  312. FormatNameScope(class_info.scope_id, "!members:\n");
  313. CloseBrace();
  314. } else {
  315. Semicolon();
  316. }
  317. out_ << '\n';
  318. FormatEntityEnd(class_info.generic_id);
  319. }
  320. auto Formatter::FormatVtable(VtableId id, const Vtable& vtable_info) -> void {
  321. out_ << '\n';
  322. Indent();
  323. out_ << "vtable ";
  324. FormatName(id);
  325. out_ << ' ';
  326. OpenBrace();
  327. for (auto function_id :
  328. sem_ir_->inst_blocks().Get(vtable_info.virtual_functions_id)) {
  329. Indent();
  330. FormatArg(function_id);
  331. out_ << '\n';
  332. }
  333. CloseBrace();
  334. out_ << '\n';
  335. }
  336. auto Formatter::FormatInterface(InterfaceId id, const Interface& interface_info)
  337. -> void {
  338. if (!ShouldFormatEntity(interface_info)) {
  339. return;
  340. }
  341. PrepareToFormatDecl(interface_info.first_owning_decl_id);
  342. FormatEntityStart("interface", interface_info, id);
  343. llvm::SaveAndRestore interface_scope(scope_, inst_namer_.GetScopeFor(id));
  344. if (interface_info.scope_id.has_value()) {
  345. out_ << ' ';
  346. OpenBrace();
  347. FormatCodeBlock(interface_info.body_block_id);
  348. // Always include the !members label because we always list the witness in
  349. // this section.
  350. IndentLabel();
  351. out_ << "!members:\n";
  352. FormatNameScope(interface_info.scope_id);
  353. Indent();
  354. out_ << "witness = ";
  355. FormatArg(interface_info.associated_entities_id);
  356. out_ << "\n";
  357. FormatRequireImplsBlock(interface_info.require_impls_block_id);
  358. CloseBrace();
  359. } else {
  360. Semicolon();
  361. }
  362. out_ << '\n';
  363. FormatEntityEnd(interface_info.generic_id);
  364. }
  365. auto Formatter::FormatNamedConstraint(NamedConstraintId id,
  366. const NamedConstraint& constraint_info)
  367. -> void {
  368. if (!ShouldFormatEntity(constraint_info)) {
  369. return;
  370. }
  371. PrepareToFormatDecl(constraint_info.first_owning_decl_id);
  372. FormatEntityStart("constraint", constraint_info, id);
  373. llvm::SaveAndRestore constraint_scope(scope_, inst_namer_.GetScopeFor(id));
  374. if (constraint_info.scope_id.has_value()) {
  375. out_ << ' ';
  376. OpenBrace();
  377. FormatCodeBlock(constraint_info.body_block_id);
  378. // Always include the !members label because we always list the witness in
  379. // this section.
  380. IndentLabel();
  381. out_ << "!members:\n";
  382. FormatNameScope(constraint_info.scope_id);
  383. FormatRequireImplsBlock(constraint_info.require_impls_block_id);
  384. CloseBrace();
  385. } else {
  386. Semicolon();
  387. }
  388. out_ << '\n';
  389. FormatEntityEnd(constraint_info.generic_id);
  390. }
  391. auto Formatter::FormatRequireImpls(RequireImplsId /*id*/,
  392. const RequireImpls& require) -> void {
  393. if (!ShouldFormatEntity(require.decl_id)) {
  394. return;
  395. }
  396. PrepareToFormatDecl(require.decl_id);
  397. FormatGenericStart("require", require.generic_id);
  398. FormatGenericEnd();
  399. }
  400. auto Formatter::FormatAssociatedConstant(AssociatedConstantId id,
  401. const AssociatedConstant& assoc_const)
  402. -> void {
  403. if (!ShouldFormatEntity(assoc_const.decl_id)) {
  404. return;
  405. }
  406. PrepareToFormatDecl(assoc_const.decl_id);
  407. FormatEntityStart("assoc_const", assoc_const.generic_id, id);
  408. llvm::SaveAndRestore assoc_const_scope(scope_, inst_namer_.GetScopeFor(id));
  409. out_ << " ";
  410. FormatName(assoc_const.name_id);
  411. out_ << ":! ";
  412. FormatTypeOfInst(assoc_const.decl_id);
  413. if (assoc_const.default_value_id.has_value()) {
  414. out_ << " = ";
  415. FormatArg(assoc_const.default_value_id);
  416. }
  417. out_ << ";\n";
  418. FormatEntityEnd(assoc_const.generic_id);
  419. }
  420. auto Formatter::FormatImpl(ImplId id, const Impl& impl_info) -> void {
  421. if (!ShouldFormatEntity(impl_info)) {
  422. return;
  423. }
  424. PrepareToFormatDecl(impl_info.first_owning_decl_id);
  425. FormatEntityStart("impl", impl_info, id);
  426. llvm::SaveAndRestore impl_scope(scope_, inst_namer_.GetScopeFor(id));
  427. out_ << ": ";
  428. FormatName(impl_info.self_id);
  429. out_ << " as ";
  430. FormatName(impl_info.constraint_id);
  431. if (impl_info.is_complete()) {
  432. out_ << ' ';
  433. OpenBrace();
  434. FormatCodeBlock(impl_info.body_block_id);
  435. FormatCodeBlock(impl_info.witness_block_id);
  436. // Print the !members label even if the name scope is empty because we
  437. // always list the witness in this section.
  438. IndentLabel();
  439. out_ << "!members:\n";
  440. if (impl_info.scope_id.has_value()) {
  441. FormatNameScope(impl_info.scope_id);
  442. }
  443. Indent();
  444. out_ << "witness = ";
  445. FormatArg(impl_info.witness_id);
  446. out_ << "\n";
  447. CloseBrace();
  448. } else {
  449. Semicolon();
  450. }
  451. out_ << '\n';
  452. FormatEntityEnd(impl_info.generic_id);
  453. }
  454. auto Formatter::FormatFunction(FunctionId id, const Function& fn) -> void {
  455. if (!ShouldFormatEntity(fn)) {
  456. return;
  457. }
  458. std::string function_start;
  459. switch (fn.virtual_modifier) {
  460. case FunctionFields::VirtualModifier::Virtual:
  461. function_start += "virtual ";
  462. break;
  463. case FunctionFields::VirtualModifier::Abstract:
  464. function_start += "abstract ";
  465. break;
  466. case FunctionFields::VirtualModifier::Override:
  467. function_start += "override ";
  468. break;
  469. case FunctionFields::VirtualModifier::None:
  470. break;
  471. }
  472. if (fn.is_extern) {
  473. function_start += "extern ";
  474. }
  475. function_start += "fn";
  476. PrepareToFormatDecl(fn.first_owning_decl_id);
  477. FormatEntityStart(function_start, fn, id);
  478. llvm::SaveAndRestore function_scope(scope_, inst_namer_.GetScopeFor(id));
  479. auto return_type_info = ReturnTypeInfo::ForFunction(*sem_ir_, fn);
  480. FormatParamList(fn.call_params_id, return_type_info.is_valid() &&
  481. return_type_info.has_return_slot());
  482. if (fn.builtin_function_kind() != BuiltinFunctionKind::None) {
  483. out_ << " = \""
  484. << FormatEscaped(fn.builtin_function_kind().name(),
  485. /*use_hex_escapes=*/true)
  486. << "\"";
  487. }
  488. if (fn.thunk_decl_id().has_value()) {
  489. out_ << " [thunk ";
  490. FormatArg(fn.thunk_decl_id());
  491. out_ << "]";
  492. }
  493. if (!fn.body_block_ids.empty()) {
  494. out_ << ' ';
  495. OpenBrace();
  496. for (auto block_id : fn.body_block_ids) {
  497. IndentLabel();
  498. FormatLabel(block_id);
  499. out_ << ":\n";
  500. FormatCodeBlock(block_id);
  501. }
  502. CloseBrace();
  503. } else {
  504. Semicolon();
  505. }
  506. out_ << '\n';
  507. FormatEntityEnd(fn.generic_id);
  508. }
  509. auto Formatter::FormatSpecificRegion(const Generic& generic,
  510. const Specific& specific,
  511. GenericInstIndex::Region region,
  512. llvm::StringRef region_name) -> void {
  513. if (!specific.GetValueBlock(region).has_value()) {
  514. return;
  515. }
  516. if (!region_name.empty()) {
  517. IndentLabel();
  518. out_ << "!" << region_name << ":\n";
  519. }
  520. for (auto [generic_inst_id, specific_inst_id] : llvm::zip_longest(
  521. sem_ir_->inst_blocks().GetOrEmpty(generic.GetEvalBlock(region)),
  522. sem_ir_->inst_blocks().GetOrEmpty(specific.GetValueBlock(region)))) {
  523. Indent();
  524. if (generic_inst_id) {
  525. FormatName(*generic_inst_id);
  526. } else {
  527. out_ << "<missing>";
  528. }
  529. out_ << " => ";
  530. if (specific_inst_id) {
  531. FormatName(*specific_inst_id);
  532. } else {
  533. out_ << "<missing>";
  534. }
  535. out_ << "\n";
  536. }
  537. }
  538. auto Formatter::FormatSpecific(SpecificId id, const Specific& specific)
  539. -> void {
  540. const auto& generic = sem_ir_->generics().Get(specific.generic_id);
  541. if (!ShouldFormatEntity(generic.decl_id)) {
  542. // Omit specifics if we also omitted the generic.
  543. return;
  544. }
  545. if (specific.IsUnresolved()) {
  546. // Omit specifics that were never resolved. Such specifics exist only to
  547. // track the way the arguments were spelled, and that information is
  548. // conveyed entirely by the name of the specific. These specifics may also
  549. // not be referenced by any SemIR that we format, so including them adds
  550. // clutter and possibly emits references to instructions we didn't name.
  551. return;
  552. }
  553. llvm::SaveAndRestore generic_scope(
  554. scope_, inst_namer_.GetScopeFor(specific.generic_id));
  555. out_ << "\n";
  556. out_ << "specific ";
  557. FormatName(id);
  558. out_ << " ";
  559. OpenBrace();
  560. FormatSpecificRegion(generic, specific, GenericInstIndex::Region::Declaration,
  561. "");
  562. FormatSpecificRegion(generic, specific, GenericInstIndex::Region::Definition,
  563. "definition");
  564. CloseBrace();
  565. out_ << "\n";
  566. }
  567. auto Formatter::PrepareToFormatDecl(InstId first_owning_decl_id) -> void {
  568. // If this decl was imported from a different IR, annotate the name of
  569. // that IR in the output before the `{` or `;`.
  570. if (first_owning_decl_id.has_value()) {
  571. auto import_ir_inst_id =
  572. sem_ir_->insts().GetImportSource(first_owning_decl_id);
  573. if (import_ir_inst_id.has_value()) {
  574. auto import_ir_id =
  575. sem_ir_->import_ir_insts().Get(import_ir_inst_id).ir_id();
  576. if (const auto* import_file =
  577. sem_ir_->import_irs().Get(import_ir_id).sem_ir) {
  578. pending_imported_from_ = import_file->filename();
  579. }
  580. }
  581. }
  582. }
  583. auto Formatter::FormatGenericStart(llvm::StringRef entity_kind,
  584. GenericId generic_id) -> void {
  585. const auto& generic = sem_ir_->generics().Get(generic_id);
  586. out_ << "\n";
  587. Indent();
  588. out_ << "generic " << entity_kind << " ";
  589. FormatName(generic_id);
  590. llvm::SaveAndRestore generic_scope(scope_,
  591. inst_namer_.GetScopeFor(generic_id));
  592. FormatParamList(generic.bindings_id);
  593. out_ << " ";
  594. OpenBrace();
  595. FormatCodeBlock(generic.decl_block_id);
  596. if (generic.definition_block_id.has_value()) {
  597. IndentLabel();
  598. out_ << "!definition:\n";
  599. FormatCodeBlock(generic.definition_block_id);
  600. }
  601. }
  602. auto Formatter::FormatEntityEnd(GenericId generic_id) -> void {
  603. if (generic_id.has_value()) {
  604. FormatGenericEnd();
  605. }
  606. }
  607. auto Formatter::FormatGenericEnd() -> void {
  608. CloseBrace();
  609. out_ << '\n';
  610. }
  611. auto Formatter::FormatParamList(InstBlockId params_id, bool has_return_slot)
  612. -> void {
  613. if (!params_id.has_value()) {
  614. // TODO: This happens for imported functions, for which we don't currently
  615. // import the call parameters list.
  616. return;
  617. }
  618. llvm::StringLiteral close = ")";
  619. out_ << "(";
  620. llvm::ListSeparator sep;
  621. for (InstId param_id : sem_ir_->inst_blocks().Get(params_id)) {
  622. auto is_out_param = sem_ir_->insts().Is<OutParam>(param_id);
  623. if (is_out_param) {
  624. // TODO: An input parameter following an output parameter is formatted a
  625. // bit strangely. For example, alternating input and output parameters
  626. // produces:
  627. //
  628. // fn @F(%in1: %t) -> %out1: %t, %in2: %t -> %out2: %t
  629. //
  630. // This doesn't actually happen right now, though.
  631. out_ << std::exchange(close, llvm::StringLiteral(""));
  632. out_ << " -> ";
  633. } else {
  634. out_ << sep;
  635. }
  636. if (!param_id.has_value()) {
  637. out_ << "invalid";
  638. continue;
  639. }
  640. // Don't include the name of the return slot parameter if the function
  641. // doesn't have a return slot; the name won't be used for anything in that
  642. // case.
  643. // TODO: Should the call parameter even exist in that case? There isn't a
  644. // corresponding argument in a `call` instruction.
  645. if (!is_out_param || has_return_slot) {
  646. FormatName(param_id);
  647. out_ << ": ";
  648. }
  649. FormatTypeOfInst(param_id);
  650. }
  651. out_ << close;
  652. }
  653. auto Formatter::FormatCodeBlock(InstBlockId block_id) -> void {
  654. bool elided = false;
  655. for (const InstId inst_id : sem_ir_->inst_blocks().GetOrEmpty(block_id)) {
  656. if (ShouldFormatInst(inst_id)) {
  657. FormatInst(inst_id);
  658. elided = false;
  659. } else if (!elided) {
  660. // When formatting a block, leave a hint that instructions were elided.
  661. Indent();
  662. out_ << "<elided>\n";
  663. elided = true;
  664. }
  665. }
  666. }
  667. auto Formatter::FormatTrailingBlock(InstBlockId block_id) -> void {
  668. out_ << ' ';
  669. OpenBrace();
  670. FormatCodeBlock(block_id);
  671. CloseBrace();
  672. }
  673. auto Formatter::FormatNameScope(NameScopeId id, llvm::StringRef label) -> void {
  674. const auto& scope = sem_ir_->name_scopes().Get(id);
  675. if (scope.entries().empty() && scope.extended_scopes().empty() &&
  676. scope.import_ir_scopes().empty() && !scope.is_cpp_scope() &&
  677. !scope.has_error()) {
  678. // Name scope is empty.
  679. return;
  680. }
  681. if (!label.empty()) {
  682. IndentLabel();
  683. out_ << label;
  684. }
  685. for (auto [name_id, result] : scope.entries()) {
  686. Indent();
  687. out_ << ".";
  688. FormatName(name_id);
  689. switch (result.access_kind()) {
  690. case AccessKind::Public:
  691. break;
  692. case AccessKind::Protected:
  693. out_ << " [protected]";
  694. break;
  695. case AccessKind::Private:
  696. out_ << " [private]";
  697. break;
  698. }
  699. out_ << " = ";
  700. if (result.is_poisoned()) {
  701. out_ << "<poisoned>";
  702. } else {
  703. FormatName(result.is_found() ? result.target_inst_id() : InstId::None);
  704. }
  705. out_ << "\n";
  706. }
  707. for (auto extended_scope_id : scope.extended_scopes()) {
  708. Indent();
  709. out_ << "extend ";
  710. FormatName(extended_scope_id);
  711. out_ << "\n";
  712. }
  713. // This is used to cluster all "Core//prelude/..." imports, but not
  714. // "Core//prelude" itself. This avoids unrelated churn in test files when we
  715. // add or remove an unused prelude file, but is intended to still show the
  716. // existence of indirect imports.
  717. bool has_prelude_components = false;
  718. for (auto [import_ir_id, unused] : scope.import_ir_scopes()) {
  719. auto label = GetImportIRLabel(import_ir_id);
  720. if (label.starts_with("Core//prelude/")) {
  721. if (has_prelude_components) {
  722. // Only print the existence once.
  723. continue;
  724. } else {
  725. has_prelude_components = true;
  726. label = "Core//prelude/...";
  727. }
  728. }
  729. Indent();
  730. out_ << "import " << label << "\n";
  731. }
  732. if (scope.is_cpp_scope()) {
  733. Indent();
  734. out_ << "import Cpp//...\n";
  735. }
  736. if (scope.has_error()) {
  737. Indent();
  738. out_ << "has_error\n";
  739. }
  740. }
  741. auto Formatter::FormatInst(InstId inst_id) -> void {
  742. if (!inst_id.has_value()) {
  743. Indent();
  744. out_ << "none\n";
  745. return;
  746. }
  747. if (!in_terminator_sequence_) {
  748. Indent();
  749. }
  750. auto inst = sem_ir_->insts().GetWithAttachedType(inst_id);
  751. CARBON_KIND_SWITCH(inst) {
  752. case CARBON_KIND(Branch branch): {
  753. out_ << Branch::Kind.ir_name() << " ";
  754. FormatLabel(branch.target_id);
  755. out_ << "\n";
  756. in_terminator_sequence_ = false;
  757. return;
  758. }
  759. case CARBON_KIND(BranchIf branch_if): {
  760. out_ << "if ";
  761. FormatName(branch_if.cond_id);
  762. out_ << " " << Branch::Kind.ir_name() << " ";
  763. FormatLabel(branch_if.target_id);
  764. out_ << " else ";
  765. in_terminator_sequence_ = true;
  766. return;
  767. }
  768. case CARBON_KIND(BranchWithArg branch_with_arg): {
  769. out_ << BranchWithArg::Kind.ir_name() << " ";
  770. FormatLabel(branch_with_arg.target_id);
  771. out_ << "(";
  772. FormatName(branch_with_arg.arg_id);
  773. out_ << ")\n";
  774. in_terminator_sequence_ = false;
  775. return;
  776. }
  777. default: {
  778. FormatInstLhs(inst_id, inst);
  779. out_ << inst.kind().ir_name();
  780. // Add constants for everything except `ImportRefUnloaded`.
  781. if (!inst.Is<ImportRefUnloaded>()) {
  782. pending_constant_value_ =
  783. sem_ir_->constant_values().GetAttached(inst_id);
  784. pending_constant_value_is_self_ =
  785. sem_ir_->constant_values().GetInstIdIfValid(
  786. pending_constant_value_) == inst_id;
  787. }
  788. FormatInstRhs(inst);
  789. // This usually prints the constant, but when `FormatInstRhs` prints it
  790. // first (or for `ImportRefUnloaded`), this does nothing.
  791. FormatPendingConstantValue(AddSpace::Before);
  792. out_ << "\n";
  793. return;
  794. }
  795. }
  796. }
  797. auto Formatter::FormatPendingImportedFrom(AddSpace space_where) -> void {
  798. if (pending_imported_from_.empty()) {
  799. return;
  800. }
  801. if (space_where == AddSpace::Before) {
  802. out_ << ' ';
  803. }
  804. out_ << "[from \"" << FormatEscaped(pending_imported_from_) << "\"]";
  805. if (space_where == AddSpace::After) {
  806. out_ << ' ';
  807. }
  808. pending_imported_from_ = llvm::StringRef();
  809. }
  810. auto Formatter::FormatPendingConstantValue(AddSpace space_where) -> void {
  811. if (pending_constant_value_ == ConstantId::NotConstant) {
  812. return;
  813. }
  814. if (space_where == AddSpace::Before) {
  815. out_ << ' ';
  816. }
  817. out_ << '[';
  818. if (pending_constant_value_.has_value()) {
  819. switch (sem_ir_->constant_values().GetDependence(pending_constant_value_)) {
  820. case ConstantDependence::None:
  821. out_ << "concrete";
  822. break;
  823. case ConstantDependence::PeriodSelf:
  824. out_ << "symbolic_self";
  825. break;
  826. // TODO: Consider renaming this. This will cause a lot of SemIR churn.
  827. case ConstantDependence::Checked:
  828. out_ << "symbolic";
  829. break;
  830. case ConstantDependence::Template:
  831. out_ << "template";
  832. break;
  833. }
  834. if (!pending_constant_value_is_self_) {
  835. out_ << " = ";
  836. FormatConstant(pending_constant_value_);
  837. }
  838. } else {
  839. out_ << pending_constant_value_;
  840. }
  841. out_ << ']';
  842. if (space_where == AddSpace::After) {
  843. out_ << ' ';
  844. }
  845. pending_constant_value_ = ConstantId::NotConstant;
  846. }
  847. auto Formatter::FormatInstLhs(InstId inst_id, Inst inst) -> void {
  848. // Every typed instruction is named, and there are some untyped instructions
  849. // that have names (such as `ImportRefUnloaded`). When there's a typed
  850. // instruction with no name, it means an instruction is incorrectly not named
  851. // -- but should be printed as such.
  852. bool has_name = inst_namer_.has_name(inst_id);
  853. if (!has_name && !inst.kind().has_type()) {
  854. return;
  855. }
  856. FormatName(inst_id);
  857. if (inst.kind().has_type()) {
  858. out_ << ": ";
  859. switch (GetExprCategory(*sem_ir_, inst_id)) {
  860. case ExprCategory::NotExpr:
  861. case ExprCategory::Error:
  862. case ExprCategory::Value:
  863. case ExprCategory::Pattern:
  864. case ExprCategory::Mixed:
  865. case ExprCategory::RefTagged:
  866. break;
  867. case ExprCategory::DurableRef:
  868. case ExprCategory::EphemeralRef:
  869. out_ << "ref ";
  870. break;
  871. case ExprCategory::Initializing:
  872. out_ << "init ";
  873. break;
  874. }
  875. FormatTypeOfInst(inst_id);
  876. }
  877. out_ << " = ";
  878. }
  879. auto Formatter::FormatInstArgAndKind(Inst::ArgAndKind arg_and_kind) -> void {
  880. GetFormatArgFn(arg_and_kind.kind())(*this, arg_and_kind.value());
  881. }
  882. auto Formatter::FormatInstRhs(Inst inst) -> void {
  883. CARBON_KIND_SWITCH(inst) {
  884. case InstKind::ArrayInit:
  885. case InstKind::StructInit:
  886. case InstKind::TupleInit: {
  887. auto init = inst.As<AnyAggregateInit>();
  888. FormatArgs(init.elements_id);
  889. FormatReturnSlotArg(init.dest_id);
  890. return;
  891. }
  892. case InstKind::ImportRefLoaded:
  893. case InstKind::ImportRefUnloaded:
  894. FormatImportRefRhs(inst.As<AnyImportRef>());
  895. return;
  896. case InstKind::OutParam:
  897. case InstKind::RefParam:
  898. case InstKind::ValueParam: {
  899. auto param = inst.As<AnyParam>();
  900. FormatArgs(param.index);
  901. // Omit pretty_name because it's an implementation detail of
  902. // pretty-printing.
  903. return;
  904. }
  905. case CARBON_KIND(AssociatedConstantDecl decl): {
  906. FormatArgs(decl.assoc_const_id);
  907. llvm::SaveAndRestore scope(scope_,
  908. inst_namer_.GetScopeFor(decl.assoc_const_id));
  909. FormatTrailingBlock(decl.decl_block_id);
  910. return;
  911. }
  912. case CARBON_KIND(SymbolicBinding bind): {
  913. // A SymbolicBinding with no value is a purely symbolic binding, such as
  914. // the `Self` in an interface. Don't print out `none` for the value.
  915. if (bind.value_id.has_value()) {
  916. FormatArgs(bind.entity_name_id, bind.value_id);
  917. } else {
  918. FormatArgs(bind.entity_name_id);
  919. }
  920. return;
  921. }
  922. case CARBON_KIND(BlockArg block): {
  923. out_ << " ";
  924. FormatLabel(block.block_id);
  925. return;
  926. }
  927. case CARBON_KIND(Call call): {
  928. FormatCallRhs(call);
  929. return;
  930. }
  931. case CARBON_KIND(ClassDecl decl): {
  932. FormatDeclRhs(decl.class_id,
  933. sem_ir_->classes().Get(decl.class_id).pattern_block_id,
  934. decl.decl_block_id);
  935. return;
  936. }
  937. case CARBON_KIND(CppTemplateNameType type): {
  938. // Omit the Clang declaration. We don't have a good way to format it, and
  939. // the entity name should suffice to identify the template.
  940. FormatArgs(type.name_id);
  941. return;
  942. }
  943. case CARBON_KIND(CustomLayoutType type): {
  944. out_ << " {";
  945. auto layout = sem_ir_->custom_layouts().Get(type.layout_id);
  946. out_ << "size=" << layout[CustomLayoutId::SizeIndex]
  947. << ", align=" << layout[CustomLayoutId::AlignIndex];
  948. for (auto [field, offset] : llvm::zip_equal(
  949. sem_ir_->struct_type_fields().Get(type.fields_id),
  950. layout.drop_front(CustomLayoutId::FirstFieldIndex))) {
  951. out_ << ", .";
  952. FormatName(field.name_id);
  953. out_ << "@" << offset << ": ";
  954. FormatInstAsType(field.type_inst_id);
  955. }
  956. out_ << "}";
  957. return;
  958. }
  959. case CARBON_KIND(FloatValue value): {
  960. llvm::SmallVector<char, 16> buffer;
  961. sem_ir_->floats().Get(value.float_id).toString(buffer);
  962. out_ << " " << buffer;
  963. return;
  964. }
  965. case CARBON_KIND(FunctionDecl decl): {
  966. FormatDeclRhs(decl.function_id,
  967. sem_ir_->functions().Get(decl.function_id).pattern_block_id,
  968. decl.decl_block_id);
  969. return;
  970. }
  971. case InstKind::ImportCppDecl: {
  972. FormatImportCppDeclRhs();
  973. return;
  974. }
  975. case CARBON_KIND(ImplDecl decl): {
  976. FormatDeclRhs(decl.impl_id,
  977. sem_ir_->impls().Get(decl.impl_id).pattern_block_id,
  978. decl.decl_block_id);
  979. return;
  980. }
  981. case CARBON_KIND(InitializeFrom init): {
  982. FormatArgs(init.src_id);
  983. FormatReturnSlotArg(init.dest_id);
  984. return;
  985. }
  986. case CARBON_KIND(InstValue inst): {
  987. out_ << ' ';
  988. OpenBrace();
  989. // TODO: Should we use a more compact representation in the case where the
  990. // inst is a SpliceBlock?
  991. FormatInst(inst.inst_id);
  992. CloseBrace();
  993. return;
  994. }
  995. case CARBON_KIND(InterfaceDecl decl): {
  996. FormatDeclRhs(
  997. decl.interface_id,
  998. sem_ir_->interfaces().Get(decl.interface_id).pattern_block_id,
  999. decl.decl_block_id);
  1000. return;
  1001. }
  1002. case CARBON_KIND(IntValue value): {
  1003. out_ << " ";
  1004. sem_ir_->ints()
  1005. .Get(value.int_id)
  1006. .print(out_, sem_ir_->types().IsSignedInt(value.type_id));
  1007. return;
  1008. }
  1009. case CARBON_KIND(NameBindingDecl name): {
  1010. FormatTrailingBlock(name.pattern_block_id);
  1011. return;
  1012. }
  1013. case CARBON_KIND(NamedConstraintDecl decl): {
  1014. FormatDeclRhs(decl.named_constraint_id,
  1015. sem_ir_->named_constraints()
  1016. .Get(decl.named_constraint_id)
  1017. .pattern_block_id,
  1018. decl.decl_block_id);
  1019. return;
  1020. }
  1021. case CARBON_KIND(Namespace ns): {
  1022. if (ns.import_id.has_value()) {
  1023. FormatArgs(ns.import_id, ns.name_scope_id);
  1024. } else {
  1025. FormatArgs(ns.name_scope_id);
  1026. }
  1027. return;
  1028. }
  1029. case CARBON_KIND(RequireImplsDecl decl): {
  1030. FormatArgs(decl.require_impls_id);
  1031. llvm::SaveAndRestore scope(
  1032. scope_, inst_namer_.GetScopeFor(decl.require_impls_id));
  1033. FormatRequireImpls(decl.require_impls_id);
  1034. FormatTrailingBlock(decl.decl_block_id);
  1035. return;
  1036. }
  1037. case CARBON_KIND(ReturnExpr ret): {
  1038. FormatArgs(ret.expr_id);
  1039. if (ret.dest_id.has_value()) {
  1040. FormatReturnSlotArg(ret.dest_id);
  1041. }
  1042. return;
  1043. }
  1044. case CARBON_KIND(ReturnSlot ret): {
  1045. // Omit inst.type_inst_id because it's not semantically significant.
  1046. FormatArgs(ret.storage_id);
  1047. return;
  1048. }
  1049. case InstKind::ReturnSlotPattern:
  1050. // No-op because type_id is the only semantically significant field,
  1051. // and it's handled separately.
  1052. return;
  1053. case CARBON_KIND(SpliceBlock splice): {
  1054. FormatArgs(splice.result_id);
  1055. FormatTrailingBlock(splice.block_id);
  1056. return;
  1057. }
  1058. case CARBON_KIND(StructType struct_type): {
  1059. out_ << " {";
  1060. llvm::ListSeparator sep;
  1061. for (auto field :
  1062. sem_ir_->struct_type_fields().Get(struct_type.fields_id)) {
  1063. out_ << sep << ".";
  1064. FormatName(field.name_id);
  1065. out_ << ": ";
  1066. FormatInstAsType(field.type_inst_id);
  1067. }
  1068. out_ << "}";
  1069. return;
  1070. }
  1071. case CARBON_KIND(WhereExpr where): {
  1072. FormatArgs(where.period_self_id);
  1073. FormatTrailingBlock(where.requirements_id);
  1074. return;
  1075. }
  1076. default:
  1077. FormatInstRhsDefault(inst);
  1078. return;
  1079. }
  1080. }
  1081. auto Formatter::FormatInstRhsDefault(Inst inst) -> void {
  1082. auto arg0 = inst.arg0_and_kind();
  1083. if (arg0.kind() == IdKind::None) {
  1084. return;
  1085. }
  1086. out_ << " ";
  1087. FormatInstArgAndKind(arg0);
  1088. auto arg1 = inst.arg1_and_kind();
  1089. if (arg1.kind() == IdKind::None) {
  1090. return;
  1091. }
  1092. // Several instructions have a second operand that's a specific ID. We
  1093. // don't include it in the argument list if there is no corresponding
  1094. // specific, that is, when we're not in a generic context.
  1095. if (auto arg1_specific_id = arg1.TryAs<SpecificId>();
  1096. arg1_specific_id && !arg1_specific_id->has_value()) {
  1097. return;
  1098. }
  1099. out_ << ", ";
  1100. FormatInstArgAndKind(arg1);
  1101. }
  1102. auto Formatter::FormatCallRhs(Call inst) -> void {
  1103. out_ << " ";
  1104. FormatArg(inst.callee_id);
  1105. if (!inst.args_id.has_value()) {
  1106. out_ << "(<none>)";
  1107. return;
  1108. }
  1109. llvm::ArrayRef<InstId> args = sem_ir_->inst_blocks().Get(inst.args_id);
  1110. auto return_info = ReturnTypeInfo::ForCallee(*sem_ir_, inst.callee_id);
  1111. if (!return_info.is_valid()) {
  1112. out_ << "(<invalid return info>)";
  1113. return;
  1114. }
  1115. // Error in the inst type may indicate that the return type was incomplete
  1116. // when the inst was created, and so no return slot was added.
  1117. bool has_return_slot =
  1118. return_info.has_return_slot() && inst.type_id != SemIR::ErrorInst::TypeId;
  1119. InstId return_slot_arg_id = InstId::None;
  1120. if (has_return_slot) {
  1121. return_slot_arg_id = args.consume_back();
  1122. }
  1123. llvm::ListSeparator sep;
  1124. out_ << '(';
  1125. for (auto inst_id : args) {
  1126. out_ << sep;
  1127. FormatArg(inst_id);
  1128. }
  1129. out_ << ')';
  1130. if (has_return_slot) {
  1131. FormatReturnSlotArg(return_slot_arg_id);
  1132. }
  1133. }
  1134. auto Formatter::FormatImportCppDeclRhs() -> void {
  1135. out_ << " ";
  1136. OpenBrace();
  1137. for (const Parse::Tree::PackagingNames& import :
  1138. sem_ir_->parse_tree().imports()) {
  1139. if (import.package_id != PackageNameId::Cpp) {
  1140. continue;
  1141. }
  1142. Indent();
  1143. out_ << "import Cpp";
  1144. if (import.library_id.has_value()) {
  1145. out_ << " \""
  1146. << FormatEscaped(
  1147. sem_ir_->string_literal_values().Get(import.library_id))
  1148. << "\"";
  1149. } else if (import.inline_body_id.has_value()) {
  1150. out_ << " inline";
  1151. }
  1152. out_ << "\n";
  1153. }
  1154. CloseBrace();
  1155. }
  1156. auto Formatter::FormatImportRefRhs(AnyImportRef inst) -> void {
  1157. out_ << " ";
  1158. auto import_ir_inst = sem_ir_->import_ir_insts().Get(inst.import_ir_inst_id);
  1159. FormatArg(import_ir_inst.ir_id());
  1160. out_ << ", ";
  1161. if (inst.entity_name_id.has_value()) {
  1162. // Prefer to show the entity name when possible.
  1163. FormatArg(inst.entity_name_id);
  1164. } else {
  1165. // Show a name based on the location when possible, or the numeric
  1166. // instruction as a last resort.
  1167. const auto& import_ir = sem_ir_->import_irs().Get(import_ir_inst.ir_id());
  1168. auto loc_id =
  1169. import_ir.sem_ir->insts().GetCanonicalLocId(import_ir_inst.inst_id());
  1170. switch (loc_id.kind()) {
  1171. case LocId::Kind::None: {
  1172. out_ << import_ir_inst.inst_id() << " [no loc]";
  1173. break;
  1174. }
  1175. case LocId::Kind::ImportIRInstId: {
  1176. // TODO: Probably don't want to format each indirection, but maybe
  1177. // reuse GetCanonicalImportIRInst?
  1178. out_ << import_ir_inst.inst_id() << " [indirect]";
  1179. break;
  1180. }
  1181. case LocId::Kind::NodeId: {
  1182. // Formats a NodeId from the import.
  1183. const auto& tree = import_ir.sem_ir->parse_tree();
  1184. auto token = tree.node_token(loc_id.node_id());
  1185. out_ << "loc" << tree.tokens().GetLineNumber(token) << "_"
  1186. << tree.tokens().GetColumnNumber(token);
  1187. break;
  1188. }
  1189. case LocId::Kind::InstId:
  1190. CARBON_FATAL("Unexpected LocId: {0}", loc_id);
  1191. }
  1192. }
  1193. out_ << ", "
  1194. << (inst.kind == InstKind::ImportRefLoaded ? "loaded" : "unloaded");
  1195. }
  1196. auto Formatter::FormatRequireImpls(RequireImplsId id) -> void {
  1197. out_ << ' ';
  1198. const auto& require = sem_ir_->require_impls().Get(id);
  1199. OpenBrace();
  1200. Indent();
  1201. out_ << "require ";
  1202. FormatArg(require.self_id);
  1203. out_ << " impls ";
  1204. FormatArg(require.facet_type_inst_id);
  1205. out_ << "\n";
  1206. CloseBrace();
  1207. }
  1208. auto Formatter::FormatRequireImplsBlock(RequireImplsBlockId block_id) -> void {
  1209. IndentLabel();
  1210. out_ << "!requires:\n";
  1211. if (!block_id.has_value()) {
  1212. return;
  1213. }
  1214. for (auto require_impls_id : sem_ir_->require_impls_blocks().Get(block_id)) {
  1215. Indent();
  1216. FormatArg(require_impls_id);
  1217. FormatRequireImpls(require_impls_id);
  1218. out_ << "\n";
  1219. }
  1220. }
  1221. auto Formatter::FormatArg(EntityNameId id) -> void {
  1222. if (!id.has_value()) {
  1223. out_ << "_";
  1224. return;
  1225. }
  1226. const auto& info = sem_ir_->entity_names().Get(id);
  1227. FormatName(info.name_id);
  1228. if (info.bind_index().has_value()) {
  1229. out_ << ", " << info.bind_index().index;
  1230. }
  1231. if (info.is_template) {
  1232. out_ << ", template";
  1233. }
  1234. }
  1235. auto Formatter::FormatArg(FacetTypeId id) -> void {
  1236. const auto& info = sem_ir_->facet_types().Get(id);
  1237. // Nothing output to indicate that this is a facet type since this is only
  1238. // used as the argument to a `facet_type` instruction.
  1239. out_ << "<";
  1240. llvm::ListSeparator sep(" & ");
  1241. if (info.extend_constraints.empty() &&
  1242. info.extend_named_constraints.empty()) {
  1243. out_ << "type";
  1244. } else {
  1245. for (auto extend : info.extend_constraints) {
  1246. out_ << sep;
  1247. FormatName(extend.interface_id);
  1248. if (extend.specific_id.has_value()) {
  1249. out_ << ", ";
  1250. FormatName(extend.specific_id);
  1251. }
  1252. }
  1253. for (auto extend : info.extend_named_constraints) {
  1254. out_ << sep;
  1255. FormatName(extend.named_constraint_id);
  1256. if (extend.specific_id.has_value()) {
  1257. out_ << ", ";
  1258. FormatName(extend.specific_id);
  1259. }
  1260. }
  1261. }
  1262. if (info.other_requirements || !info.self_impls_constraints.empty() ||
  1263. !info.rewrite_constraints.empty()) {
  1264. out_ << " where ";
  1265. llvm::ListSeparator and_sep(" and ");
  1266. if (!info.self_impls_constraints.empty() ||
  1267. !info.self_impls_named_constraints.empty()) {
  1268. out_ << and_sep << ".Self impls ";
  1269. llvm::ListSeparator amp_sep(" & ");
  1270. for (auto self_impls : info.self_impls_constraints) {
  1271. out_ << amp_sep;
  1272. FormatName(self_impls.interface_id);
  1273. if (self_impls.specific_id.has_value()) {
  1274. out_ << ", ";
  1275. FormatName(self_impls.specific_id);
  1276. }
  1277. }
  1278. for (auto self_impls : info.self_impls_named_constraints) {
  1279. out_ << amp_sep;
  1280. FormatName(self_impls.named_constraint_id);
  1281. if (self_impls.specific_id.has_value()) {
  1282. out_ << ", ";
  1283. FormatName(self_impls.specific_id);
  1284. }
  1285. }
  1286. }
  1287. for (auto rewrite : info.rewrite_constraints) {
  1288. out_ << and_sep;
  1289. FormatArg(rewrite.lhs_id);
  1290. out_ << " = ";
  1291. FormatArg(rewrite.rhs_id);
  1292. }
  1293. if (info.other_requirements) {
  1294. out_ << and_sep << "TODO";
  1295. }
  1296. }
  1297. out_ << ">";
  1298. }
  1299. auto Formatter::FormatArg(ImportIRId id) -> void {
  1300. if (id.has_value()) {
  1301. out_ << GetImportIRLabel(id);
  1302. } else {
  1303. out_ << id;
  1304. }
  1305. }
  1306. auto Formatter::FormatArg(IntId id) -> void {
  1307. // We don't know the signedness to use here. Default to unsigned.
  1308. sem_ir_->ints().Get(id).print(out_, /*isSigned=*/false);
  1309. }
  1310. auto Formatter::FormatArg(NameScopeId id) -> void {
  1311. OpenBrace();
  1312. FormatNameScope(id);
  1313. CloseBrace();
  1314. }
  1315. auto Formatter::FormatArg(InstBlockId id) -> void {
  1316. if (!id.has_value()) {
  1317. out_ << "invalid";
  1318. return;
  1319. }
  1320. out_ << '(';
  1321. llvm::ListSeparator sep;
  1322. for (auto inst_id : sem_ir_->inst_blocks().Get(id)) {
  1323. out_ << sep;
  1324. FormatArg(inst_id);
  1325. }
  1326. out_ << ')';
  1327. }
  1328. auto Formatter::FormatArg(AbsoluteInstBlockId id) -> void {
  1329. FormatArg(static_cast<InstBlockId>(id));
  1330. }
  1331. auto Formatter::FormatArg(RealId id) -> void {
  1332. // TODO: Format with a `.` when the exponent is near zero.
  1333. const auto& real = sem_ir_->reals().Get(id);
  1334. real.mantissa.print(out_, /*isSigned=*/false);
  1335. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1336. }
  1337. auto Formatter::FormatArg(StringLiteralValueId id) -> void {
  1338. out_ << '"'
  1339. << FormatEscaped(sem_ir_->string_literal_values().Get(id),
  1340. /*use_hex_escapes=*/true)
  1341. << '"';
  1342. }
  1343. auto Formatter::FormatReturnSlotArg(InstId dest_id) -> void {
  1344. if (dest_id.has_value()) {
  1345. out_ << " to ";
  1346. FormatArg(dest_id);
  1347. }
  1348. }
  1349. auto Formatter::FormatName(NameId id) -> void {
  1350. out_ << sem_ir_->names().GetFormatted(id);
  1351. }
  1352. auto Formatter::FormatName(InstId id) -> void {
  1353. if (id.has_value()) {
  1354. IncludeChunkInOutput(tentative_inst_chunks_.Get(id));
  1355. }
  1356. out_ << inst_namer_.GetNameFor(scope_, id);
  1357. }
  1358. auto Formatter::FormatName(SpecificId id) -> void {
  1359. const auto& specific = sem_ir_->specifics().Get(id);
  1360. FormatName(specific.generic_id);
  1361. FormatArg(specific.args_id);
  1362. }
  1363. auto Formatter::FormatName(SpecificInterfaceId id) -> void {
  1364. const auto& interface = sem_ir_->specific_interfaces().Get(id);
  1365. FormatName(interface.interface_id);
  1366. if (interface.specific_id.has_value()) {
  1367. out_ << ", ";
  1368. FormatArg(interface.specific_id);
  1369. }
  1370. }
  1371. auto Formatter::FormatLabel(InstBlockId id) -> void {
  1372. out_ << inst_namer_.GetLabelFor(scope_, id);
  1373. }
  1374. auto Formatter::FormatConstant(ConstantId id) -> void {
  1375. if (!id.has_value()) {
  1376. out_ << "<not constant>";
  1377. return;
  1378. }
  1379. auto inst_id = GetInstWithConstantValue(*sem_ir_, id);
  1380. FormatName(inst_id);
  1381. // For an attached constant, also list the unattached constant.
  1382. if (id.is_symbolic() && sem_ir_->constant_values()
  1383. .GetSymbolicConstant(id)
  1384. .generic_id.has_value()) {
  1385. // TODO: Skip printing this if it's the same as `inst_id`.
  1386. auto unattached_inst_id = sem_ir_->constant_values().GetInstId(id);
  1387. out_ << " (";
  1388. FormatName(unattached_inst_id);
  1389. out_ << ")";
  1390. }
  1391. }
  1392. auto Formatter::FormatInstAsType(InstId id) -> void {
  1393. if (!id.has_value()) {
  1394. out_ << "invalid";
  1395. return;
  1396. }
  1397. // Types are formatted in the `constants` scope because they typically refer
  1398. // to constants.
  1399. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1400. if (auto const_id = sem_ir_->constant_values().GetAttached(id);
  1401. const_id.has_value()) {
  1402. FormatConstant(const_id);
  1403. } else {
  1404. // Type instruction didn't have a constant value. Fall back to printing
  1405. // the instruction name.
  1406. FormatArg(id);
  1407. }
  1408. }
  1409. auto Formatter::FormatTypeOfInst(InstId id) -> void {
  1410. auto type_id = sem_ir_->insts().GetAttachedType(id);
  1411. if (!type_id.has_value()) {
  1412. out_ << "invalid";
  1413. return;
  1414. }
  1415. // Types are formatted in the `constants` scope because they typically refer
  1416. // to constants.
  1417. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1418. FormatConstant(sem_ir_->types().GetConstantId(type_id));
  1419. }
  1420. auto Formatter::GetImportIRLabel(ImportIRId id) -> std::string {
  1421. CARBON_CHECK(id.has_value(),
  1422. "Callers are responsible for checking `id.has_value`");
  1423. const auto& import_ir = *sem_ir_->import_irs().Get(id).sem_ir;
  1424. CARBON_CHECK(import_ir.library_id().has_value());
  1425. auto package_id = import_ir.package_id();
  1426. llvm::StringRef package_name =
  1427. package_id.AsIdentifierId().has_value()
  1428. ? import_ir.identifiers().Get(package_id.AsIdentifierId())
  1429. : package_id.AsSpecialName();
  1430. llvm::StringRef library_name =
  1431. (import_ir.library_id() != LibraryNameId::Default)
  1432. ? import_ir.string_literal_values().Get(
  1433. import_ir.library_id().AsStringLiteralValueId())
  1434. : "default";
  1435. return llvm::formatv("{0}//{1}", package_name, library_name);
  1436. }
  1437. } // namespace Carbon::SemIR
  1438. // NOLINTEND(misc-no-recursion)