compile_subcommand.cpp 24 KB

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