compile_subcommand.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  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/driver/compile_subcommand.h"
  5. #include "common/vlog.h"
  6. #include "llvm/ADT/STLExtras.h"
  7. #include "llvm/ADT/ScopeExit.h"
  8. #include "toolchain/base/pretty_stack_trace_function.h"
  9. #include "toolchain/base/timings.h"
  10. #include "toolchain/check/check.h"
  11. #include "toolchain/codegen/codegen.h"
  12. #include "toolchain/diagnostics/sorting_diagnostic_consumer.h"
  13. #include "toolchain/lex/lex.h"
  14. #include "toolchain/lower/lower.h"
  15. #include "toolchain/parse/parse.h"
  16. #include "toolchain/parse/tree_and_subtrees.h"
  17. #include "toolchain/sem_ir/formatter.h"
  18. #include "toolchain/sem_ir/inst_namer.h"
  19. #include "toolchain/source/source_buffer.h"
  20. namespace Carbon {
  21. auto operator<<(llvm::raw_ostream& out, CompileOptions::Phase phase)
  22. -> llvm::raw_ostream& {
  23. switch (phase) {
  24. case CompileOptions::Phase::Lex:
  25. out << "lex";
  26. break;
  27. case CompileOptions::Phase::Parse:
  28. out << "parse";
  29. break;
  30. case CompileOptions::Phase::Check:
  31. out << "check";
  32. break;
  33. case CompileOptions::Phase::Lower:
  34. out << "lower";
  35. break;
  36. case CompileOptions::Phase::CodeGen:
  37. out << "codegen";
  38. break;
  39. }
  40. return out;
  41. }
  42. auto CompileOptions::Build(CommandLine::CommandBuilder& b) -> void {
  43. b.AddStringPositionalArg(
  44. {
  45. .name = "FILE",
  46. .help = R"""(
  47. The input Carbon source file to compile.
  48. )""",
  49. },
  50. [&](auto& arg_b) {
  51. arg_b.Required(true);
  52. arg_b.Append(&input_filenames);
  53. });
  54. b.AddOneOfOption(
  55. {
  56. .name = "phase",
  57. .help = R"""(
  58. Selects the compilation phase to run. These phases are always run in sequence,
  59. so every phase before the one selected will also be run. The default is to
  60. compile to machine code.
  61. )""",
  62. },
  63. [&](auto& arg_b) {
  64. arg_b.SetOneOf(
  65. {
  66. arg_b.OneOfValue("lex", Phase::Lex),
  67. arg_b.OneOfValue("parse", Phase::Parse),
  68. arg_b.OneOfValue("check", Phase::Check),
  69. arg_b.OneOfValue("lower", Phase::Lower),
  70. arg_b.OneOfValue("codegen", Phase::CodeGen).Default(true),
  71. },
  72. &phase);
  73. });
  74. // TODO: Rearrange the code setting this option and two related ones to
  75. // allow them to reference each other instead of hard-coding their names.
  76. b.AddStringOption(
  77. {
  78. .name = "output",
  79. .value_name = "FILE",
  80. .help = R"""(
  81. The output filename for codegen.
  82. When this is a file name, either textual assembly or a binary object will be
  83. written to it based on the flag `--asm-output`. The default is to write a binary
  84. object file.
  85. Passing `--output=-` will write the output to stdout. In that case, the flag
  86. `--asm-output` is ignored and the output defaults to textual assembly. Binary
  87. object output can be forced by enabling `--force-obj-output`.
  88. )""",
  89. },
  90. [&](auto& arg_b) { arg_b.Set(&output_filename); });
  91. // Include the common code generation options at this point to render it
  92. // after the more common options above, but before the more unusual options
  93. // below.
  94. codegen_options.Build(b);
  95. b.AddFlag(
  96. {
  97. .name = "asm-output",
  98. .help = R"""(
  99. Write textual assembly rather than a binary object file to the code generation
  100. output.
  101. This flag only applies when writing to a file. When writing to stdout, the
  102. default is textual assembly and this flag is ignored.
  103. )""",
  104. },
  105. [&](auto& arg_b) { arg_b.Set(&asm_output); });
  106. b.AddFlag(
  107. {
  108. .name = "force-obj-output",
  109. .help = R"""(
  110. Force binary object output, even with `--output=-`.
  111. When `--output=-` is set, the default is textual assembly; this forces printing
  112. of a binary object file instead. Ignored for other `--output` values.
  113. )""",
  114. },
  115. [&](auto& arg_b) { arg_b.Set(&force_obj_output); });
  116. b.AddFlag(
  117. {
  118. .name = "include-diagnostic-kind",
  119. .help = R"""(
  120. When printing diagnostics, include the diagnostic kind as part of output. This
  121. applies to each message that forms a diagnostic, not just the primary message.
  122. )""",
  123. },
  124. [&](auto& arg_b) { arg_b.Set(&include_diagnostic_kind); });
  125. b.AddFlag(
  126. {
  127. .name = "stream-errors",
  128. .help = R"""(
  129. Stream error messages to stderr as they are generated rather than sorting them
  130. and displaying them in source order.
  131. )""",
  132. },
  133. [&](auto& arg_b) { arg_b.Set(&stream_errors); });
  134. b.AddFlag(
  135. {
  136. .name = "dump-shared-values",
  137. .help = R"""(
  138. Dumps shared values. These aren't owned by any particular file or phase.
  139. )""",
  140. },
  141. [&](auto& arg_b) { arg_b.Set(&dump_shared_values); });
  142. b.AddFlag(
  143. {
  144. .name = "dump-tokens",
  145. .help = R"""(
  146. Dump the tokens to stdout when lexed.
  147. )""",
  148. },
  149. [&](auto& arg_b) { arg_b.Set(&dump_tokens); });
  150. b.AddFlag(
  151. {
  152. .name = "omit-file-boundary-tokens",
  153. .help = R"""(
  154. For `--dump-tokens`, omit file start and end boundary tokens.
  155. )""",
  156. },
  157. [&](auto& arg_b) { arg_b.Set(&omit_file_boundary_tokens); });
  158. b.AddFlag(
  159. {
  160. .name = "dump-parse-tree",
  161. .help = R"""(
  162. Dump the parse tree to stdout when parsed.
  163. )""",
  164. },
  165. [&](auto& arg_b) { arg_b.Set(&dump_parse_tree); });
  166. b.AddFlag(
  167. {
  168. .name = "preorder-parse-tree",
  169. .help = R"""(
  170. When dumping the parse tree, reorder it so that it is in preorder rather than
  171. postorder.
  172. )""",
  173. },
  174. [&](auto& arg_b) { arg_b.Set(&preorder_parse_tree); });
  175. b.AddFlag(
  176. {
  177. .name = "dump-raw-sem-ir",
  178. .help = R"""(
  179. Dump the raw JSON structure of SemIR to stdout when built.
  180. )""",
  181. },
  182. [&](auto& arg_b) { arg_b.Set(&dump_raw_sem_ir); });
  183. b.AddFlag(
  184. {
  185. .name = "dump-sem-ir",
  186. .help = R"""(
  187. Dump the SemIR to stdout when built.
  188. )""",
  189. },
  190. [&](auto& arg_b) { arg_b.Set(&dump_sem_ir); });
  191. b.AddFlag(
  192. {
  193. .name = "builtin-sem-ir",
  194. .help = R"""(
  195. Include the SemIR for builtins when dumping it.
  196. )""",
  197. },
  198. [&](auto& arg_b) { arg_b.Set(&builtin_sem_ir); });
  199. b.AddFlag(
  200. {
  201. .name = "dump-llvm-ir",
  202. .help = R"""(
  203. Dump the LLVM IR to stdout after lowering.
  204. )""",
  205. },
  206. [&](auto& arg_b) { arg_b.Set(&dump_llvm_ir); });
  207. b.AddFlag(
  208. {
  209. .name = "dump-asm",
  210. .help = R"""(
  211. Dump the generated assembly to stdout after codegen.
  212. )""",
  213. },
  214. [&](auto& arg_b) { arg_b.Set(&dump_asm); });
  215. b.AddFlag(
  216. {
  217. .name = "dump-mem-usage",
  218. .help = R"""(
  219. Dumps the amount of memory used.
  220. )""",
  221. },
  222. [&](auto& arg_b) { arg_b.Set(&dump_mem_usage); });
  223. b.AddFlag(
  224. {
  225. .name = "dump-timings",
  226. .help = R"""(
  227. Dumps the duration of each phase for each compilation unit.
  228. )""",
  229. },
  230. [&](auto& arg_b) { arg_b.Set(&dump_timings); });
  231. b.AddFlag(
  232. {
  233. .name = "prelude-import",
  234. .help = R"""(
  235. Whether to use the implicit prelude import. Enabled by default.
  236. )""",
  237. },
  238. [&](auto& arg_b) {
  239. arg_b.Default(true);
  240. arg_b.Set(&prelude_import);
  241. });
  242. b.AddStringOption(
  243. {
  244. .name = "exclude-dump-file-prefix",
  245. .value_name = "PREFIX",
  246. .help = R"""(
  247. Excludes files with the given prefix from dumps.
  248. )""",
  249. },
  250. [&](auto& arg_b) { arg_b.Set(&exclude_dump_file_prefix); });
  251. b.AddFlag(
  252. {
  253. .name = "debug-info",
  254. .help = R"""(
  255. Whether to emit DWARF debug information.
  256. )""",
  257. },
  258. [&](auto& arg_b) {
  259. arg_b.Default(true);
  260. arg_b.Set(&include_debug_info);
  261. });
  262. }
  263. static constexpr CommandLine::CommandInfo SubcommandInfo = {
  264. .name = "compile",
  265. .help = R"""(
  266. Compile Carbon source code.
  267. This subcommand runs the Carbon compiler over input source code, checking it for
  268. errors and producing the requested output.
  269. Error messages are written to the standard error stream.
  270. Different phases of the compiler can be selected to run, and intermediate state
  271. can be written to standard output as these phases progress.
  272. )""",
  273. };
  274. CompileSubcommand::CompileSubcommand() : DriverSubcommand(SubcommandInfo) {}
  275. auto CompileSubcommand::ValidateOptions(DriverEnv& driver_env) const -> bool {
  276. using Phase = CompileOptions::Phase;
  277. switch (options_.phase) {
  278. case Phase::Lex:
  279. if (options_.dump_parse_tree) {
  280. driver_env.error_stream
  281. << "error: requested dumping the parse tree but compile "
  282. "phase is limited to '"
  283. << options_.phase << "'\n";
  284. return false;
  285. }
  286. [[fallthrough]];
  287. case Phase::Parse:
  288. if (options_.dump_sem_ir) {
  289. driver_env.error_stream
  290. << "error: requested dumping the SemIR but compile phase "
  291. "is limited to '"
  292. << options_.phase << "'\n";
  293. return false;
  294. }
  295. [[fallthrough]];
  296. case Phase::Check:
  297. if (options_.dump_llvm_ir) {
  298. driver_env.error_stream
  299. << "error: requested dumping the LLVM IR but compile "
  300. "phase is limited to '"
  301. << options_.phase << "'\n";
  302. return false;
  303. }
  304. [[fallthrough]];
  305. case Phase::Lower:
  306. case Phase::CodeGen:
  307. // Everything can be dumped in these phases.
  308. break;
  309. }
  310. return true;
  311. }
  312. namespace {
  313. // Ties together information for a file being compiled.
  314. class CompilationUnit {
  315. public:
  316. explicit CompilationUnit(DriverEnv& driver_env, const CompileOptions& options,
  317. DiagnosticConsumer* consumer,
  318. llvm::StringRef input_filename);
  319. // Loads source and lexes it. Returns true on success.
  320. auto RunLex() -> void;
  321. // Parses tokens. Returns true on success.
  322. auto RunParse() -> void;
  323. auto PreCheck() -> Parse::NodeLocConverter&;
  324. // Returns information needed to check this unit.
  325. auto GetCheckUnit(SemIR::CheckIRId check_ir_id,
  326. llvm::ArrayRef<Parse::NodeLocConverter*> node_converters)
  327. -> Check::Unit;
  328. // Runs post-check logic. Returns true if checking succeeded for the IR.
  329. auto PostCheck() -> void;
  330. // Lower SemIR to LLVM IR.
  331. auto RunLower() -> void;
  332. auto RunCodeGen() -> void;
  333. // Runs post-compile logic. This is always called, and called after all other
  334. // actions on the CompilationUnit.
  335. auto PostCompile() -> void;
  336. // Flushes diagnostics, specifically as part of generating stack trace
  337. // information.
  338. auto FlushForStackTrace() -> void { consumer_->Flush(); }
  339. auto input_filename() -> llvm::StringRef { return input_filename_; }
  340. auto success() -> bool { return success_; }
  341. auto has_source() -> bool { return source_.has_value(); }
  342. private:
  343. // Do codegen. Returns true on success.
  344. auto RunCodeGenHelper() -> bool;
  345. // The TreeAndSubtrees is mainly used for debugging and diagnostics, and has
  346. // significant overhead. Avoid constructing it when unused.
  347. auto GetParseTreeAndSubtrees() -> const Parse::TreeAndSubtrees&;
  348. // Wraps a call with log statements to indicate start and end. Typically logs
  349. // with the actual function name, but marks timings with the appropriate
  350. // phase.
  351. auto LogCall(llvm::StringLiteral logging_label,
  352. llvm::StringLiteral timing_label, llvm::function_ref<void()> fn)
  353. -> void;
  354. // Returns true if the current input file can be dumped.
  355. auto IncludeInDumps() const -> bool;
  356. // Returns true if the specified input file can be dumped.
  357. auto IncludeInDumps(llvm::StringRef filename) const -> bool;
  358. DriverEnv* driver_env_;
  359. SharedValueStores value_stores_;
  360. const CompileOptions& options_;
  361. // The input filename from the command line. For most diagnostics, we
  362. // typically use `source_->filename()`, which includes a `-` -> `<stdin>`
  363. // translation. However, logging and some diagnostics use the command line
  364. // argument.
  365. std::string input_filename_;
  366. // Copied from driver_ for CARBON_VLOG.
  367. llvm::raw_pwrite_stream* vlog_stream_;
  368. // Diagnostics are sent to consumer_, with optional sorting.
  369. std::optional<SortingDiagnosticConsumer> sorting_consumer_;
  370. DiagnosticConsumer* consumer_;
  371. bool success_ = true;
  372. // Tracks memory usage of the compile.
  373. std::optional<MemUsage> mem_usage_;
  374. // Tracks timings of the compile.
  375. std::optional<Timings> timings_;
  376. // These are initialized as steps are run.
  377. std::optional<SourceBuffer> source_;
  378. std::optional<Lex::TokenizedBuffer> tokens_;
  379. std::optional<Parse::Tree> parse_tree_;
  380. std::optional<Parse::TreeAndSubtrees> parse_tree_and_subtrees_;
  381. std::optional<std::function<const Parse::TreeAndSubtrees&()>>
  382. get_parse_tree_and_subtrees_;
  383. std::optional<Parse::NodeLocConverter> node_converter_;
  384. std::optional<Check::SemIRDiagnosticConverter> sem_ir_converter_;
  385. std::optional<SemIR::File> sem_ir_;
  386. std::unique_ptr<llvm::LLVMContext> llvm_context_;
  387. std::unique_ptr<llvm::Module> module_;
  388. };
  389. CompilationUnit::CompilationUnit(DriverEnv& driver_env,
  390. const CompileOptions& options,
  391. DiagnosticConsumer* consumer,
  392. llvm::StringRef input_filename)
  393. : driver_env_(&driver_env),
  394. options_(options),
  395. input_filename_(input_filename),
  396. vlog_stream_(driver_env_->vlog_stream) {
  397. if (vlog_stream_ != nullptr || options_.stream_errors) {
  398. consumer_ = consumer;
  399. } else {
  400. sorting_consumer_ = SortingDiagnosticConsumer(*consumer);
  401. consumer_ = &*sorting_consumer_;
  402. }
  403. if (options_.dump_mem_usage && IncludeInDumps()) {
  404. mem_usage_ = MemUsage();
  405. }
  406. if (options_.dump_timings && IncludeInDumps()) {
  407. timings_ = Timings();
  408. }
  409. }
  410. auto CompilationUnit::RunLex() -> void {
  411. CARBON_CHECK(!tokens_, "Called RunLex twice");
  412. LogCall("SourceBuffer::MakeFromFileOrStdin", "source", [&] {
  413. source_ = SourceBuffer::MakeFromFileOrStdin(*driver_env_->fs,
  414. input_filename_, *consumer_);
  415. });
  416. if (!source_) {
  417. success_ = false;
  418. return;
  419. }
  420. if (mem_usage_) {
  421. mem_usage_->Add("source_", source_->text().size(), source_->text().size());
  422. }
  423. CARBON_VLOG("*** SourceBuffer ***\n```\n{0}\n```\n", source_->text());
  424. LogCall("Lex::Lex", "lex",
  425. [&] { tokens_ = Lex::Lex(value_stores_, *source_, *consumer_); });
  426. if (options_.dump_tokens && IncludeInDumps()) {
  427. consumer_->Flush();
  428. tokens_->Print(driver_env_->output_stream,
  429. options_.omit_file_boundary_tokens);
  430. }
  431. if (mem_usage_) {
  432. mem_usage_->Collect("tokens_", *tokens_);
  433. }
  434. CARBON_VLOG("*** Lex::TokenizedBuffer ***\n{0}", tokens_);
  435. if (tokens_->has_errors()) {
  436. success_ = false;
  437. }
  438. }
  439. auto CompilationUnit::RunParse() -> void {
  440. CARBON_CHECK(tokens_, "Must call RunLex first");
  441. CARBON_CHECK(!parse_tree_, "Called RunParse twice");
  442. LogCall("Parse::Parse", "parse", [&] {
  443. parse_tree_ = Parse::Parse(*tokens_, *consumer_, vlog_stream_);
  444. });
  445. if (options_.dump_parse_tree && IncludeInDumps()) {
  446. consumer_->Flush();
  447. const auto& tree_and_subtrees = GetParseTreeAndSubtrees();
  448. if (options_.preorder_parse_tree) {
  449. tree_and_subtrees.PrintPreorder(driver_env_->output_stream);
  450. } else {
  451. tree_and_subtrees.Print(driver_env_->output_stream);
  452. }
  453. }
  454. if (mem_usage_) {
  455. mem_usage_->Collect("parse_tree_", *parse_tree_);
  456. }
  457. CARBON_VLOG("*** Parse::Tree ***\n{0}", parse_tree_);
  458. if (parse_tree_->has_errors()) {
  459. success_ = false;
  460. }
  461. }
  462. auto CompilationUnit::PreCheck() -> Parse::NodeLocConverter& {
  463. CARBON_CHECK(parse_tree_, "Must call RunParse first");
  464. CARBON_CHECK(!node_converter_, "Called PreCheck twice");
  465. get_parse_tree_and_subtrees_ = [this]() -> const Parse::TreeAndSubtrees& {
  466. return this->GetParseTreeAndSubtrees();
  467. };
  468. node_converter_.emplace(&*tokens_, source_->filename(),
  469. *get_parse_tree_and_subtrees_);
  470. return *node_converter_;
  471. }
  472. auto CompilationUnit::GetCheckUnit(
  473. SemIR::CheckIRId check_ir_id,
  474. llvm::ArrayRef<Parse::NodeLocConverter*> node_converters) -> Check::Unit {
  475. CARBON_CHECK(node_converter_, "Must call PreCheck first");
  476. CARBON_CHECK(!sem_ir_converter_, "Called GetCheckUnit twice");
  477. sem_ir_.emplace(&*parse_tree_, check_ir_id, parse_tree_->packaging_decl(),
  478. value_stores_, input_filename_);
  479. sem_ir_converter_.emplace(node_converters, &*sem_ir_);
  480. return {.consumer = consumer_,
  481. .value_stores = &value_stores_,
  482. .timings = timings_ ? &*timings_ : nullptr,
  483. .get_parse_tree_and_subtrees = *get_parse_tree_and_subtrees_,
  484. .sem_ir = &*sem_ir_,
  485. .node_converter = &*node_converter_,
  486. .sem_ir_converter = &*sem_ir_converter_};
  487. }
  488. auto CompilationUnit::PostCheck() -> void {
  489. CARBON_CHECK(sem_ir_converter_, "Must call GetCheckUnit first");
  490. // We've finished all steps that can produce diagnostics. Emit the
  491. // diagnostics now, so that the developer sees them sooner and doesn't need
  492. // to wait for code generation.
  493. consumer_->Flush();
  494. if (mem_usage_) {
  495. mem_usage_->Collect("sem_ir_", *sem_ir_);
  496. }
  497. if (options_.dump_raw_sem_ir && IncludeInDumps()) {
  498. CARBON_VLOG("*** Raw SemIR::File ***\n{0}\n", *sem_ir_);
  499. sem_ir_->Print(driver_env_->output_stream, options_.builtin_sem_ir);
  500. if (options_.dump_sem_ir) {
  501. driver_env_->output_stream << "\n";
  502. }
  503. }
  504. bool print = options_.dump_sem_ir && IncludeInDumps();
  505. if (vlog_stream_ || print) {
  506. // Omit entities imported from files that we are not dumping.
  507. auto should_format_entity = [&](SemIR::InstId entity_inst_id) -> bool {
  508. // TODO: Reuse `GetCanonicalImportIRInst`. Currently it depends on
  509. // `Check::Context`, which we don't have access to here.
  510. const SemIR::File* file = &*sem_ir_;
  511. while (true) {
  512. auto loc_id = file->insts().GetLocId(entity_inst_id);
  513. if (!loc_id.is_import_ir_inst_id()) {
  514. return true;
  515. }
  516. auto import_ir_inst =
  517. file->import_ir_insts().Get(loc_id.import_ir_inst_id());
  518. const auto* import_file =
  519. file->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  520. CARBON_CHECK(import_file);
  521. if (!IncludeInDumps(import_file->filename())) {
  522. return false;
  523. }
  524. file = import_file;
  525. entity_inst_id = import_ir_inst.inst_id;
  526. }
  527. };
  528. SemIR::Formatter formatter(&*sem_ir_, should_format_entity);
  529. if (vlog_stream_) {
  530. CARBON_VLOG("*** SemIR::File ***\n");
  531. formatter.Print(*vlog_stream_);
  532. }
  533. if (print) {
  534. formatter.Print(driver_env_->output_stream);
  535. }
  536. }
  537. if (sem_ir_->has_errors()) {
  538. success_ = false;
  539. }
  540. }
  541. auto CompilationUnit::RunLower() -> void {
  542. CARBON_CHECK(sem_ir_converter_, "Must call PostCheck first");
  543. CARBON_CHECK(!module_, "Called RunLower twice");
  544. LogCall("Lower::LowerToLLVM", "lower", [&] {
  545. llvm_context_ = std::make_unique<llvm::LLVMContext>();
  546. // TODO: Consider disabling instruction naming by default if we're not
  547. // producing textual LLVM IR.
  548. SemIR::InstNamer inst_namer(&*sem_ir_);
  549. module_ = Lower::LowerToLLVM(*llvm_context_, options_.include_debug_info,
  550. *sem_ir_converter_, input_filename_, *sem_ir_,
  551. &inst_namer, vlog_stream_);
  552. });
  553. if (vlog_stream_) {
  554. CARBON_VLOG("*** llvm::Module ***\n");
  555. module_->print(*vlog_stream_, /*AAW=*/nullptr,
  556. /*ShouldPreserveUseListOrder=*/false,
  557. /*IsForDebug=*/true);
  558. }
  559. if (options_.dump_llvm_ir && IncludeInDumps()) {
  560. module_->print(driver_env_->output_stream, /*AAW=*/nullptr,
  561. /*ShouldPreserveUseListOrder=*/true);
  562. }
  563. }
  564. auto CompilationUnit::RunCodeGen() -> void {
  565. CARBON_CHECK(module_, "Must call RunLower first");
  566. LogCall("CodeGen", "codegen", [&] { success_ = RunCodeGenHelper(); });
  567. }
  568. auto CompilationUnit::PostCompile() -> void {
  569. if (options_.dump_shared_values && IncludeInDumps()) {
  570. Yaml::Print(driver_env_->output_stream,
  571. value_stores_.OutputYaml(input_filename_));
  572. }
  573. if (mem_usage_) {
  574. mem_usage_->Collect("value_stores_", value_stores_);
  575. Yaml::Print(driver_env_->output_stream,
  576. mem_usage_->OutputYaml(input_filename_));
  577. }
  578. if (timings_) {
  579. Yaml::Print(driver_env_->output_stream,
  580. timings_->OutputYaml(input_filename_));
  581. }
  582. // The diagnostics consumer must be flushed before compilation artifacts are
  583. // destructed, because diagnostics can refer to their state.
  584. consumer_->Flush();
  585. }
  586. auto CompilationUnit::RunCodeGenHelper() -> bool {
  587. std::optional<CodeGen> codegen = CodeGen::Make(
  588. *module_, options_.codegen_options.target, driver_env_->error_stream);
  589. if (!codegen) {
  590. return false;
  591. }
  592. if (vlog_stream_) {
  593. CARBON_VLOG("*** Assembly ***\n");
  594. codegen->EmitAssembly(*vlog_stream_);
  595. }
  596. if (options_.output_filename == "-") {
  597. // TODO: The output file name, forcing object output, and requesting
  598. // textual assembly output are all somewhat linked flags. We should add
  599. // some validation that they are used correctly.
  600. if (options_.force_obj_output) {
  601. if (!codegen->EmitObject(driver_env_->output_stream)) {
  602. return false;
  603. }
  604. } else {
  605. if (!codegen->EmitAssembly(driver_env_->output_stream)) {
  606. return false;
  607. }
  608. }
  609. } else {
  610. llvm::SmallString<256> output_filename = options_.output_filename;
  611. if (output_filename.empty()) {
  612. if (!source_->is_regular_file()) {
  613. // Don't invent file names like `-.o` or `/dev/stdin.o`.
  614. driver_env_->error_stream
  615. << "error: output file name must be specified for input `"
  616. << input_filename_ << "` that is not a regular file\n";
  617. return false;
  618. }
  619. output_filename = input_filename_;
  620. llvm::sys::path::replace_extension(output_filename,
  621. options_.asm_output ? ".s" : ".o");
  622. } else {
  623. // TODO: Handle the case where multiple input files were specified
  624. // along with an output file name. That should either be an error or
  625. // should produce a single LLVM IR module containing all inputs.
  626. // Currently each unit overwrites the output from the previous one in
  627. // this case.
  628. }
  629. CARBON_VLOG("Writing output to: {0}\n", output_filename);
  630. std::error_code ec;
  631. llvm::raw_fd_ostream output_file(output_filename, ec,
  632. llvm::sys::fs::OF_None);
  633. if (ec) {
  634. driver_env_->error_stream << "error: could not open output file '"
  635. << output_filename << "': " << ec.message()
  636. << "\n";
  637. return false;
  638. }
  639. if (options_.asm_output) {
  640. if (!codegen->EmitAssembly(output_file)) {
  641. return false;
  642. }
  643. } else {
  644. if (!codegen->EmitObject(output_file)) {
  645. return false;
  646. }
  647. }
  648. }
  649. return true;
  650. }
  651. auto CompilationUnit::GetParseTreeAndSubtrees()
  652. -> const Parse::TreeAndSubtrees& {
  653. if (!parse_tree_and_subtrees_) {
  654. parse_tree_and_subtrees_ = Parse::TreeAndSubtrees(*tokens_, *parse_tree_);
  655. if (mem_usage_) {
  656. mem_usage_->Collect("parse_tree_and_subtrees_",
  657. *parse_tree_and_subtrees_);
  658. }
  659. }
  660. return *parse_tree_and_subtrees_;
  661. }
  662. auto CompilationUnit::LogCall(llvm::StringLiteral logging_label,
  663. llvm::StringLiteral timing_label,
  664. llvm::function_ref<void()> fn) -> void {
  665. CARBON_VLOG("*** {0}: {1} ***\n", logging_label, input_filename_);
  666. Timings::ScopedTiming timing(timings_ ? &*timings_ : nullptr, timing_label);
  667. fn();
  668. CARBON_VLOG("*** {0} done ***\n", logging_label);
  669. }
  670. auto CompilationUnit::IncludeInDumps() const -> bool {
  671. return IncludeInDumps(input_filename_);
  672. }
  673. auto CompilationUnit::IncludeInDumps(llvm::StringRef filename) const -> bool {
  674. return options_.exclude_dump_file_prefix.empty() ||
  675. !filename.starts_with(options_.exclude_dump_file_prefix);
  676. }
  677. } // namespace
  678. auto CompileSubcommand::Run(DriverEnv& driver_env) -> DriverResult {
  679. if (!ValidateOptions(driver_env)) {
  680. return {.success = false};
  681. }
  682. // Find the files comprising the prelude if we are importing it.
  683. // TODO: Replace this with a search for library api files in a
  684. // package-specific search path based on the library name.
  685. llvm::SmallVector<std::string> prelude;
  686. if (options_.prelude_import &&
  687. options_.phase >= CompileOptions::Phase::Check) {
  688. if (auto find = driver_env.installation->ReadPreludeManifest(); find.ok()) {
  689. prelude = std::move(*find);
  690. } else {
  691. driver_env.error_stream << "error: " << find.error() << "\n";
  692. return {.success = false};
  693. }
  694. }
  695. // Prepare CompilationUnits before building scope exit handlers.
  696. StreamDiagnosticConsumer stream_consumer(driver_env.error_stream,
  697. options_.include_diagnostic_kind);
  698. llvm::SmallVector<std::unique_ptr<CompilationUnit>> units;
  699. units.reserve(prelude.size() + options_.input_filenames.size());
  700. // Add the prelude files.
  701. for (const auto& input_filename : prelude) {
  702. units.push_back(std::make_unique<CompilationUnit>(
  703. driver_env, options_, &stream_consumer, input_filename));
  704. }
  705. // Add the input source files.
  706. for (const auto& input_filename : options_.input_filenames) {
  707. units.push_back(std::make_unique<CompilationUnit>(
  708. driver_env, options_, &stream_consumer, input_filename));
  709. }
  710. auto on_exit = llvm::make_scope_exit([&]() {
  711. // Finish compilation units. This flushes their diagnostics in the order in
  712. // which they were specified on the command line.
  713. for (auto& unit : units) {
  714. unit->PostCompile();
  715. }
  716. stream_consumer.Flush();
  717. });
  718. PrettyStackTraceFunction flush_on_crash([&](llvm::raw_ostream& out) {
  719. // When crashing, flush diagnostics. If sorting diagnostics, they can be
  720. // redirected to the crash stream; if streaming, the original stream is
  721. // flushed.
  722. // TODO: Eventually we'll want to limit the count.
  723. if (options_.stream_errors) {
  724. out << "Flushing diagnostics\n";
  725. } else {
  726. out << "Pending diagnostics:\n";
  727. stream_consumer.set_stream(&out);
  728. }
  729. for (auto& unit : units) {
  730. unit->FlushForStackTrace();
  731. }
  732. stream_consumer.Flush();
  733. stream_consumer.set_stream(&driver_env.error_stream);
  734. });
  735. // Returns a DriverResult object. Called whenever Compile returns.
  736. auto make_result = [&]() {
  737. DriverResult result = {.success = true};
  738. for (const auto& unit : units) {
  739. result.success &= unit->success();
  740. result.per_file_success.push_back(
  741. {unit->input_filename().str(), unit->success()});
  742. }
  743. return result;
  744. };
  745. // Lex.
  746. for (auto& unit : units) {
  747. unit->RunLex();
  748. }
  749. if (options_.phase == CompileOptions::Phase::Lex) {
  750. return make_result();
  751. }
  752. // Parse and check phases examine `has_source` because they want to proceed if
  753. // lex failed, but not if source doesn't exist. Later steps are skipped if
  754. // anything failed, so don't need this.
  755. // Parse.
  756. for (auto& unit : units) {
  757. if (unit->has_source()) {
  758. unit->RunParse();
  759. }
  760. }
  761. if (options_.phase == CompileOptions::Phase::Parse) {
  762. return make_result();
  763. }
  764. // Pre-check assigns IR IDs and constructs node converters.
  765. llvm::SmallVector<Parse::NodeLocConverter*> node_converters;
  766. // This size may not match due to units that are missing source, but that's an
  767. // error case and not worth extra work.
  768. node_converters.reserve(units.size());
  769. for (auto& unit : units) {
  770. if (unit->has_source()) {
  771. node_converters.push_back(&unit->PreCheck());
  772. }
  773. }
  774. // Gather Check::Units.
  775. llvm::SmallVector<Check::Unit> check_units;
  776. check_units.reserve(node_converters.size());
  777. for (auto& unit : units) {
  778. if (unit->has_source()) {
  779. SemIR::CheckIRId check_ir_id(check_units.size());
  780. check_units.push_back(unit->GetCheckUnit(check_ir_id, node_converters));
  781. }
  782. }
  783. // Execute the actual checking.
  784. CARBON_VLOG_TO(driver_env.vlog_stream, "*** Check::CheckParseTrees ***\n");
  785. Check::CheckParseTrees(check_units, options_.prelude_import, driver_env.fs,
  786. driver_env.vlog_stream, driver_env.fuzzing);
  787. CARBON_VLOG_TO(driver_env.vlog_stream,
  788. "*** Check::CheckParseTrees done ***\n");
  789. for (auto& unit : units) {
  790. if (unit->has_source()) {
  791. unit->PostCheck();
  792. }
  793. }
  794. if (options_.phase == CompileOptions::Phase::Check) {
  795. return make_result();
  796. }
  797. // Unlike previous steps, errors block further progress.
  798. if (llvm::any_of(units, [&](const auto& unit) { return !unit->success(); })) {
  799. CARBON_VLOG_TO(driver_env.vlog_stream,
  800. "*** Stopping before lowering due to errors ***\n");
  801. return make_result();
  802. }
  803. // Lower.
  804. for (const auto& unit : units) {
  805. unit->RunLower();
  806. }
  807. if (options_.phase == CompileOptions::Phase::Lower) {
  808. return make_result();
  809. }
  810. CARBON_CHECK(options_.phase == CompileOptions::Phase::CodeGen,
  811. "CodeGen should be the last stage");
  812. // Codegen.
  813. for (auto& unit : units) {
  814. unit->RunCodeGen();
  815. }
  816. return make_result();
  817. }
  818. } // namespace Carbon