compile_subcommand.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  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. // TODO: Refactor this because it's a long class to have function definitions
  315. // inline.
  316. class CompilationUnit {
  317. public:
  318. explicit CompilationUnit(DriverEnv& driver_env, const CompileOptions& options,
  319. DiagnosticConsumer* consumer,
  320. llvm::StringRef input_filename)
  321. : driver_env_(&driver_env),
  322. options_(options),
  323. input_filename_(input_filename),
  324. vlog_stream_(driver_env_->vlog_stream) {
  325. if (vlog_stream_ != nullptr || options_.stream_errors) {
  326. consumer_ = consumer;
  327. } else {
  328. sorting_consumer_ = SortingDiagnosticConsumer(*consumer);
  329. consumer_ = &*sorting_consumer_;
  330. }
  331. if (options_.dump_mem_usage && IncludeInDumps()) {
  332. mem_usage_ = MemUsage();
  333. }
  334. if (options_.dump_timings && IncludeInDumps()) {
  335. timings_ = Timings();
  336. }
  337. }
  338. // Loads source and lexes it. Returns true on success.
  339. auto RunLex() -> void {
  340. CARBON_CHECK(!tokens_, "Called RunLex twice");
  341. LogCall("SourceBuffer::MakeFromFileOrStdin", "source", [&] {
  342. source_ = SourceBuffer::MakeFromFileOrStdin(*driver_env_->fs,
  343. input_filename_, *consumer_);
  344. });
  345. if (mem_usage_) {
  346. mem_usage_->Add("source_", source_->text().size(),
  347. source_->text().size());
  348. }
  349. if (!source_) {
  350. success_ = false;
  351. return;
  352. }
  353. CARBON_VLOG("*** SourceBuffer ***\n```\n{0}\n```\n", source_->text());
  354. LogCall("Lex::Lex", "lex",
  355. [&] { tokens_ = Lex::Lex(value_stores_, *source_, *consumer_); });
  356. if (options_.dump_tokens && IncludeInDumps()) {
  357. consumer_->Flush();
  358. tokens_->Print(driver_env_->output_stream,
  359. options_.omit_file_boundary_tokens);
  360. }
  361. if (mem_usage_) {
  362. mem_usage_->Collect("tokens_", *tokens_);
  363. }
  364. CARBON_VLOG("*** Lex::TokenizedBuffer ***\n{0}", tokens_);
  365. if (tokens_->has_errors()) {
  366. success_ = false;
  367. }
  368. }
  369. // Parses tokens. Returns true on success.
  370. auto RunParse() -> void {
  371. CARBON_CHECK(tokens_, "Must call RunLex first");
  372. CARBON_CHECK(!parse_tree_, "Called RunParse twice");
  373. LogCall("Parse::Parse", "parse", [&] {
  374. parse_tree_ = Parse::Parse(*tokens_, *consumer_, vlog_stream_);
  375. });
  376. if (options_.dump_parse_tree && IncludeInDumps()) {
  377. consumer_->Flush();
  378. const auto& tree_and_subtrees = GetParseTreeAndSubtrees();
  379. if (options_.preorder_parse_tree) {
  380. tree_and_subtrees.PrintPreorder(driver_env_->output_stream);
  381. } else {
  382. tree_and_subtrees.Print(driver_env_->output_stream);
  383. }
  384. }
  385. if (mem_usage_) {
  386. mem_usage_->Collect("parse_tree_", *parse_tree_);
  387. }
  388. CARBON_VLOG("*** Parse::Tree ***\n{0}", parse_tree_);
  389. if (parse_tree_->has_errors()) {
  390. success_ = false;
  391. }
  392. }
  393. auto PreCheck() -> Parse::NodeLocConverter& {
  394. CARBON_CHECK(parse_tree_, "Must call RunParse first");
  395. CARBON_CHECK(!node_converter_, "Called PreCheck twice");
  396. get_parse_tree_and_subtrees_ = [this]() -> const Parse::TreeAndSubtrees& {
  397. return this->GetParseTreeAndSubtrees();
  398. };
  399. node_converter_.emplace(&*tokens_, source_->filename(),
  400. *get_parse_tree_and_subtrees_);
  401. return *node_converter_;
  402. }
  403. // Returns information needed to check this unit.
  404. auto GetCheckUnit(SemIR::CheckIRId check_ir_id,
  405. llvm::ArrayRef<Parse::NodeLocConverter*> node_converters)
  406. -> Check::Unit {
  407. CARBON_CHECK(node_converter_, "Must call PreCheck first");
  408. CARBON_CHECK(!sem_ir_converter_, "Called GetCheckUnit twice");
  409. sem_ir_.emplace(&*parse_tree_, check_ir_id, parse_tree_->packaging_decl(),
  410. value_stores_, input_filename_);
  411. sem_ir_converter_.emplace(node_converters, &*sem_ir_);
  412. return {.consumer = consumer_,
  413. .value_stores = &value_stores_,
  414. .timings = timings_ ? &*timings_ : nullptr,
  415. .get_parse_tree_and_subtrees = *get_parse_tree_and_subtrees_,
  416. .sem_ir = &*sem_ir_,
  417. .node_converter = &*node_converter_,
  418. .sem_ir_converter = &*sem_ir_converter_};
  419. }
  420. // Runs post-check logic. Returns true if checking succeeded for the IR.
  421. auto PostCheck() -> void {
  422. CARBON_CHECK(sem_ir_converter_, "Must call GetCheckUnit first");
  423. // We've finished all steps that can produce diagnostics. Emit the
  424. // diagnostics now, so that the developer sees them sooner and doesn't need
  425. // to wait for code generation.
  426. consumer_->Flush();
  427. if (mem_usage_) {
  428. mem_usage_->Collect("sem_ir_", *sem_ir_);
  429. }
  430. if (options_.dump_raw_sem_ir && IncludeInDumps()) {
  431. CARBON_VLOG("*** Raw SemIR::File ***\n{0}\n", *sem_ir_);
  432. sem_ir_->Print(driver_env_->output_stream, options_.builtin_sem_ir);
  433. if (options_.dump_sem_ir) {
  434. driver_env_->output_stream << "\n";
  435. }
  436. }
  437. bool print = options_.dump_sem_ir && IncludeInDumps();
  438. if (vlog_stream_ || print) {
  439. // Omit entities imported from files that we are not dumping.
  440. auto should_format_entity = [&](SemIR::InstId entity_inst_id) -> bool {
  441. // TODO: Reuse `GetCanonicalImportIRInst`. Currently it depends on
  442. // `Check::Context`, which we don't have access to here.
  443. const SemIR::File* file = &*sem_ir_;
  444. while (true) {
  445. auto loc_id = file->insts().GetLocId(entity_inst_id);
  446. if (!loc_id.is_import_ir_inst_id()) {
  447. return true;
  448. }
  449. auto import_ir_inst =
  450. file->import_ir_insts().Get(loc_id.import_ir_inst_id());
  451. const auto* import_file =
  452. file->import_irs().Get(import_ir_inst.ir_id).sem_ir;
  453. CARBON_CHECK(import_file);
  454. if (!IncludeInDumps(import_file->filename())) {
  455. return false;
  456. }
  457. file = import_file;
  458. entity_inst_id = import_ir_inst.inst_id;
  459. }
  460. };
  461. SemIR::Formatter formatter(&*sem_ir_, should_format_entity);
  462. if (vlog_stream_) {
  463. CARBON_VLOG("*** SemIR::File ***\n");
  464. formatter.Print(*vlog_stream_);
  465. }
  466. if (print) {
  467. formatter.Print(driver_env_->output_stream);
  468. }
  469. }
  470. if (sem_ir_->has_errors()) {
  471. success_ = false;
  472. }
  473. }
  474. // Lower SemIR to LLVM IR.
  475. auto RunLower() -> void {
  476. CARBON_CHECK(sem_ir_converter_, "Must call PostCheck first");
  477. CARBON_CHECK(!module_, "Called RunLower twice");
  478. LogCall("Lower::LowerToLLVM", "lower", [&] {
  479. llvm_context_ = std::make_unique<llvm::LLVMContext>();
  480. // TODO: Consider disabling instruction naming by default if we're not
  481. // producing textual LLVM IR.
  482. SemIR::InstNamer inst_namer(&*sem_ir_);
  483. module_ = Lower::LowerToLLVM(*llvm_context_, options_.include_debug_info,
  484. *sem_ir_converter_, input_filename_,
  485. *sem_ir_, &inst_namer, vlog_stream_);
  486. });
  487. if (vlog_stream_) {
  488. CARBON_VLOG("*** llvm::Module ***\n");
  489. module_->print(*vlog_stream_, /*AAW=*/nullptr,
  490. /*ShouldPreserveUseListOrder=*/false,
  491. /*IsForDebug=*/true);
  492. }
  493. if (options_.dump_llvm_ir && IncludeInDumps()) {
  494. module_->print(driver_env_->output_stream, /*AAW=*/nullptr,
  495. /*ShouldPreserveUseListOrder=*/true);
  496. }
  497. }
  498. auto RunCodeGen() -> void {
  499. CARBON_CHECK(module_, "Must call RunLower first");
  500. LogCall("CodeGen", "codegen", [&] { success_ = RunCodeGenHelper(); });
  501. }
  502. // Runs post-compile logic. This is always called, and called after all other
  503. // actions on the CompilationUnit.
  504. auto PostCompile() -> void {
  505. if (options_.dump_shared_values && IncludeInDumps()) {
  506. Yaml::Print(driver_env_->output_stream,
  507. value_stores_.OutputYaml(input_filename_));
  508. }
  509. if (mem_usage_) {
  510. mem_usage_->Collect("value_stores_", value_stores_);
  511. Yaml::Print(driver_env_->output_stream,
  512. mem_usage_->OutputYaml(input_filename_));
  513. }
  514. if (timings_) {
  515. Yaml::Print(driver_env_->output_stream,
  516. timings_->OutputYaml(input_filename_));
  517. }
  518. // The diagnostics consumer must be flushed before compilation artifacts are
  519. // destructed, because diagnostics can refer to their state.
  520. consumer_->Flush();
  521. }
  522. // Flushes diagnostics, specifically as part of generating stack trace
  523. // information.
  524. auto FlushForStackTrace() -> void { consumer_->Flush(); }
  525. auto input_filename() -> llvm::StringRef { return input_filename_; }
  526. auto success() -> bool { return success_; }
  527. auto has_source() -> bool { return source_.has_value(); }
  528. private:
  529. // Do codegen. Returns true on success.
  530. auto RunCodeGenHelper() -> bool {
  531. std::optional<CodeGen> codegen = CodeGen::Make(
  532. *module_, options_.codegen_options.target, driver_env_->error_stream);
  533. if (!codegen) {
  534. return false;
  535. }
  536. if (vlog_stream_) {
  537. CARBON_VLOG("*** Assembly ***\n");
  538. codegen->EmitAssembly(*vlog_stream_);
  539. }
  540. if (options_.output_filename == "-") {
  541. // TODO: The output file name, forcing object output, and requesting
  542. // textual assembly output are all somewhat linked flags. We should add
  543. // some validation that they are used correctly.
  544. if (options_.force_obj_output) {
  545. if (!codegen->EmitObject(driver_env_->output_stream)) {
  546. return false;
  547. }
  548. } else {
  549. if (!codegen->EmitAssembly(driver_env_->output_stream)) {
  550. return false;
  551. }
  552. }
  553. } else {
  554. llvm::SmallString<256> output_filename = options_.output_filename;
  555. if (output_filename.empty()) {
  556. if (!source_->is_regular_file()) {
  557. // Don't invent file names like `-.o` or `/dev/stdin.o`.
  558. driver_env_->error_stream
  559. << "error: output file name must be specified for input `"
  560. << input_filename_ << "` that is not a regular file\n";
  561. return false;
  562. }
  563. output_filename = input_filename_;
  564. llvm::sys::path::replace_extension(output_filename,
  565. options_.asm_output ? ".s" : ".o");
  566. } else {
  567. // TODO: Handle the case where multiple input files were specified
  568. // along with an output file name. That should either be an error or
  569. // should produce a single LLVM IR module containing all inputs.
  570. // Currently each unit overwrites the output from the previous one in
  571. // this case.
  572. }
  573. CARBON_VLOG("Writing output to: {0}\n", output_filename);
  574. std::error_code ec;
  575. llvm::raw_fd_ostream output_file(output_filename, ec,
  576. llvm::sys::fs::OF_None);
  577. if (ec) {
  578. driver_env_->error_stream << "error: could not open output file '"
  579. << output_filename << "': " << ec.message()
  580. << "\n";
  581. return false;
  582. }
  583. if (options_.asm_output) {
  584. if (!codegen->EmitAssembly(output_file)) {
  585. return false;
  586. }
  587. } else {
  588. if (!codegen->EmitObject(output_file)) {
  589. return false;
  590. }
  591. }
  592. }
  593. return true;
  594. }
  595. // The TreeAndSubtrees is mainly used for debugging and diagnostics, and has
  596. // significant overhead. Avoid constructing it when unused.
  597. auto GetParseTreeAndSubtrees() -> const Parse::TreeAndSubtrees& {
  598. if (!parse_tree_and_subtrees_) {
  599. parse_tree_and_subtrees_ = Parse::TreeAndSubtrees(*tokens_, *parse_tree_);
  600. if (mem_usage_) {
  601. mem_usage_->Collect("parse_tree_and_subtrees_",
  602. *parse_tree_and_subtrees_);
  603. }
  604. }
  605. return *parse_tree_and_subtrees_;
  606. }
  607. // Wraps a call with log statements to indicate start and end. Typically logs
  608. // with the actual function name, but marks timings with the appropriate
  609. // phase.
  610. auto LogCall(llvm::StringLiteral logging_label,
  611. llvm::StringLiteral timing_label, llvm::function_ref<void()> fn)
  612. -> void {
  613. CARBON_VLOG("*** {0}: {1} ***\n", logging_label, input_filename_);
  614. Timings::ScopedTiming timing(timings_ ? &*timings_ : nullptr, timing_label);
  615. fn();
  616. CARBON_VLOG("*** {0} done ***\n", logging_label);
  617. }
  618. // Returns true if the current input file can be dumped.
  619. auto IncludeInDumps() const -> bool {
  620. return IncludeInDumps(input_filename_);
  621. }
  622. // Returns true if the specified input file can be dumped.
  623. auto IncludeInDumps(llvm::StringRef filename) const -> bool {
  624. return options_.exclude_dump_file_prefix.empty() ||
  625. !filename.starts_with(options_.exclude_dump_file_prefix);
  626. }
  627. DriverEnv* driver_env_;
  628. SharedValueStores value_stores_;
  629. const CompileOptions& options_;
  630. // The input filename from the command line. For most diagnostics, we
  631. // typically use `source_->filename()`, which includes a `-` -> `<stdin>`
  632. // translation. However, logging and some diagnostics use the command line
  633. // argument.
  634. std::string input_filename_;
  635. // Copied from driver_ for CARBON_VLOG.
  636. llvm::raw_pwrite_stream* vlog_stream_;
  637. // Diagnostics are sent to consumer_, with optional sorting.
  638. std::optional<SortingDiagnosticConsumer> sorting_consumer_;
  639. DiagnosticConsumer* consumer_;
  640. bool success_ = true;
  641. // Tracks memory usage of the compile.
  642. std::optional<MemUsage> mem_usage_;
  643. // Tracks timings of the compile.
  644. std::optional<Timings> timings_;
  645. // These are initialized as steps are run.
  646. std::optional<SourceBuffer> source_;
  647. std::optional<Lex::TokenizedBuffer> tokens_;
  648. std::optional<Parse::Tree> parse_tree_;
  649. std::optional<Parse::TreeAndSubtrees> parse_tree_and_subtrees_;
  650. std::optional<std::function<const Parse::TreeAndSubtrees&()>>
  651. get_parse_tree_and_subtrees_;
  652. std::optional<Parse::NodeLocConverter> node_converter_;
  653. std::optional<Check::SemIRDiagnosticConverter> sem_ir_converter_;
  654. std::optional<SemIR::File> sem_ir_;
  655. std::unique_ptr<llvm::LLVMContext> llvm_context_;
  656. std::unique_ptr<llvm::Module> module_;
  657. };
  658. } // namespace
  659. auto CompileSubcommand::Run(DriverEnv& driver_env) -> DriverResult {
  660. if (!ValidateOptions(driver_env)) {
  661. return {.success = false};
  662. }
  663. // Find the files comprising the prelude if we are importing it.
  664. // TODO: Replace this with a search for library api files in a
  665. // package-specific search path based on the library name.
  666. llvm::SmallVector<std::string> prelude;
  667. if (options_.prelude_import &&
  668. options_.phase >= CompileOptions::Phase::Check) {
  669. if (auto find = driver_env.installation->ReadPreludeManifest(); find.ok()) {
  670. prelude = std::move(*find);
  671. } else {
  672. driver_env.error_stream << "error: " << find.error() << "\n";
  673. return {.success = false};
  674. }
  675. }
  676. // Prepare CompilationUnits before building scope exit handlers.
  677. StreamDiagnosticConsumer stream_consumer(driver_env.error_stream,
  678. options_.include_diagnostic_kind);
  679. llvm::SmallVector<std::unique_ptr<CompilationUnit>> units;
  680. units.reserve(prelude.size() + options_.input_filenames.size());
  681. // Add the prelude files.
  682. for (const auto& input_filename : prelude) {
  683. units.push_back(std::make_unique<CompilationUnit>(
  684. driver_env, options_, &stream_consumer, input_filename));
  685. }
  686. // Add the input source files.
  687. for (const auto& input_filename : options_.input_filenames) {
  688. units.push_back(std::make_unique<CompilationUnit>(
  689. driver_env, options_, &stream_consumer, input_filename));
  690. }
  691. auto on_exit = llvm::make_scope_exit([&]() {
  692. // Finish compilation units. This flushes their diagnostics in the order in
  693. // which they were specified on the command line.
  694. for (auto& unit : units) {
  695. unit->PostCompile();
  696. }
  697. stream_consumer.Flush();
  698. });
  699. PrettyStackTraceFunction flush_on_crash([&](llvm::raw_ostream& out) {
  700. // When crashing, flush diagnostics. If sorting diagnostics, they can be
  701. // redirected to the crash stream; if streaming, the original stream is
  702. // flushed.
  703. // TODO: Eventually we'll want to limit the count.
  704. if (options_.stream_errors) {
  705. out << "Flushing diagnostics\n";
  706. } else {
  707. out << "Pending diagnostics:\n";
  708. stream_consumer.set_stream(&out);
  709. }
  710. for (auto& unit : units) {
  711. unit->FlushForStackTrace();
  712. }
  713. stream_consumer.Flush();
  714. stream_consumer.set_stream(&driver_env.error_stream);
  715. });
  716. // Returns a DriverResult object. Called whenever Compile returns.
  717. auto make_result = [&]() {
  718. DriverResult result = {.success = true};
  719. for (const auto& unit : units) {
  720. result.success &= unit->success();
  721. result.per_file_success.push_back(
  722. {unit->input_filename().str(), unit->success()});
  723. }
  724. return result;
  725. };
  726. // Lex.
  727. for (auto& unit : units) {
  728. unit->RunLex();
  729. }
  730. if (options_.phase == CompileOptions::Phase::Lex) {
  731. return make_result();
  732. }
  733. // Parse and check phases examine `has_source` because they want to proceed if
  734. // lex failed, but not if source doesn't exist. Later steps are skipped if
  735. // anything failed, so don't need this.
  736. // Parse.
  737. for (auto& unit : units) {
  738. if (unit->has_source()) {
  739. unit->RunParse();
  740. }
  741. }
  742. if (options_.phase == CompileOptions::Phase::Parse) {
  743. return make_result();
  744. }
  745. // Pre-check assigns IR IDs and constructs node converters.
  746. llvm::SmallVector<Parse::NodeLocConverter*> node_converters;
  747. // This size may not match due to units that are missing source, but that's an
  748. // error case and not worth extra work.
  749. node_converters.reserve(units.size());
  750. for (auto& unit : units) {
  751. if (unit->has_source()) {
  752. node_converters.push_back(&unit->PreCheck());
  753. }
  754. }
  755. // Gather Check::Units.
  756. llvm::SmallVector<Check::Unit> check_units;
  757. check_units.reserve(node_converters.size());
  758. for (auto& unit : units) {
  759. if (unit->has_source()) {
  760. SemIR::CheckIRId check_ir_id(check_units.size());
  761. check_units.push_back(unit->GetCheckUnit(check_ir_id, node_converters));
  762. }
  763. }
  764. // Execute the actual checking.
  765. CARBON_VLOG_TO(driver_env.vlog_stream, "*** Check::CheckParseTrees ***\n");
  766. Check::CheckParseTrees(check_units, options_.prelude_import,
  767. driver_env.vlog_stream);
  768. CARBON_VLOG_TO(driver_env.vlog_stream,
  769. "*** Check::CheckParseTrees done ***\n");
  770. for (auto& unit : units) {
  771. if (unit->has_source()) {
  772. unit->PostCheck();
  773. }
  774. }
  775. if (options_.phase == CompileOptions::Phase::Check) {
  776. return make_result();
  777. }
  778. // Unlike previous steps, errors block further progress.
  779. if (llvm::any_of(units, [&](const auto& unit) { return !unit->success(); })) {
  780. CARBON_VLOG_TO(driver_env.vlog_stream,
  781. "*** Stopping before lowering due to errors ***");
  782. return make_result();
  783. }
  784. // Lower.
  785. for (const auto& unit : units) {
  786. unit->RunLower();
  787. }
  788. if (options_.phase == CompileOptions::Phase::Lower) {
  789. return make_result();
  790. }
  791. CARBON_CHECK(options_.phase == CompileOptions::Phase::CodeGen,
  792. "CodeGen should be the last stage");
  793. // Codegen.
  794. for (auto& unit : units) {
  795. unit->RunCodeGen();
  796. }
  797. return make_result();
  798. }
  799. } // namespace Carbon