formatter.cpp 35 KB

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