formatter.cpp 42 KB

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