driver.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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/driver.h"
  5. #include <memory>
  6. #include <optional>
  7. #include "common/command_line.h"
  8. #include "common/vlog.h"
  9. #include "llvm/ADT/ArrayRef.h"
  10. #include "llvm/ADT/ScopeExit.h"
  11. #include "llvm/ADT/StringExtras.h"
  12. #include "llvm/ADT/StringRef.h"
  13. #include "llvm/IR/LLVMContext.h"
  14. #include "llvm/Support/Path.h"
  15. #include "llvm/TargetParser/Host.h"
  16. #include "toolchain/check/check.h"
  17. #include "toolchain/codegen/codegen.h"
  18. #include "toolchain/diagnostics/diagnostic_emitter.h"
  19. #include "toolchain/diagnostics/sorting_diagnostic_consumer.h"
  20. #include "toolchain/lex/tokenized_buffer.h"
  21. #include "toolchain/lower/lower.h"
  22. #include "toolchain/parse/tree.h"
  23. #include "toolchain/sem_ir/formatter.h"
  24. #include "toolchain/source/source_buffer.h"
  25. namespace Carbon {
  26. struct Driver::CompileOptions {
  27. static constexpr CommandLine::CommandInfo Info = {
  28. .name = "compile",
  29. .help = R"""(
  30. Compile Carbon source code.
  31. This subcommand runs the Carbon compiler over input source code, checking it for
  32. errors and producing the requested output.
  33. Error messages are written to the standard error stream.
  34. Different phases of the compiler can be selected to run, and intermediate state
  35. can be written to standard output as these phases progress.
  36. )""",
  37. };
  38. enum class Phase : int8_t {
  39. Lex,
  40. Parse,
  41. Check,
  42. Lower,
  43. CodeGen,
  44. };
  45. friend auto operator<<(llvm::raw_ostream& out, Phase phase)
  46. -> llvm::raw_ostream& {
  47. switch (phase) {
  48. case Phase::Lex:
  49. out << "lex";
  50. break;
  51. case Phase::Parse:
  52. out << "parse";
  53. break;
  54. case Phase::Check:
  55. out << "check";
  56. break;
  57. case Phase::Lower:
  58. out << "lower";
  59. break;
  60. case Phase::CodeGen:
  61. out << "codegen";
  62. break;
  63. }
  64. return out;
  65. }
  66. void Build(CommandLine::CommandBuilder& b) {
  67. b.AddStringPositionalArg(
  68. {
  69. .name = "FILE",
  70. .help = R"""(
  71. The input Carbon source file to compile.
  72. )""",
  73. },
  74. [&](auto& arg_b) {
  75. arg_b.Required(true);
  76. arg_b.Append(&input_file_names);
  77. });
  78. b.AddOneOfOption(
  79. {
  80. .name = "phase",
  81. .help = R"""(
  82. Selects the compilation phase to run. These phases are always run in sequence,
  83. so every phase before the one selected will also be run. The default is to
  84. compile to machine code.
  85. )""",
  86. },
  87. [&](auto& arg_b) {
  88. arg_b.SetOneOf(
  89. {
  90. arg_b.OneOfValue("lex", Phase::Lex),
  91. arg_b.OneOfValue("parse", Phase::Parse),
  92. arg_b.OneOfValue("check", Phase::Check),
  93. arg_b.OneOfValue("lower", Phase::Lower),
  94. arg_b.OneOfValue("codegen", Phase::CodeGen).Default(true),
  95. },
  96. &phase);
  97. });
  98. // TODO: Rearrange the code setting this option and two related ones to
  99. // allow them to reference each other instead of hard-coding their names.
  100. b.AddStringOption(
  101. {
  102. .name = "output",
  103. .value_name = "FILE",
  104. .help = R"""(
  105. The output filename for codegen.
  106. When this is a file name, either textual assembly or a binary object will be
  107. written to it based on the flag `--asm-output`. The default is to write a binary
  108. object file.
  109. Passing `--output=-` will write the output to stdout. In that
  110. case, the flag `--asm-output` is ignored and the output defaults to textual
  111. assembly. Binary object output can be forced by enabling `--force-obj-output`.
  112. )""",
  113. },
  114. [&](auto& arg_b) { arg_b.Set(&output_file_name); });
  115. b.AddStringOption(
  116. {
  117. .name = "target",
  118. .help = R"""(
  119. Select a target platform. Uses the LLVM target syntax. Also known as a "triple"
  120. for historical reasons.
  121. This corresponds to the `target` flag to Clang and accepts the same strings
  122. documented there:
  123. https://clang.llvm.org/docs/CrossCompilation.html#target-triple
  124. )""",
  125. },
  126. [&](auto& arg_b) {
  127. arg_b.Default(host);
  128. arg_b.Set(&target);
  129. });
  130. b.AddFlag(
  131. {
  132. .name = "asm-output",
  133. .help = R"""(
  134. Write textual assembly rather than a binary object file to the code generation
  135. output.
  136. This flag only applies when writing to a file. When writing to stdout, the
  137. default is textual assembly and this flag is ignored.
  138. )""",
  139. },
  140. [&](auto& arg_b) { arg_b.Set(&asm_output); });
  141. b.AddFlag(
  142. {
  143. .name = "force-obj-output",
  144. .help = R"""(
  145. Force binary object output, even with `--output=-`.
  146. When `--output=-` is set, the default is textual assembly; this forces printing
  147. of a binary object file instead. Ignored for other `--output` values.
  148. )""",
  149. },
  150. [&](auto& arg_b) { arg_b.Set(&force_obj_output); });
  151. b.AddFlag(
  152. {
  153. .name = "stream-errors",
  154. .help = R"""(
  155. Stream error messages to stderr as they are generated rather than sorting them
  156. and displaying them in source order.
  157. )""",
  158. },
  159. [&](auto& arg_b) { arg_b.Set(&stream_errors); });
  160. b.AddFlag(
  161. {
  162. .name = "dump-tokens",
  163. .help = R"""(
  164. Dump the tokens to stdout when lexed.
  165. )""",
  166. },
  167. [&](auto& arg_b) { arg_b.Set(&dump_tokens); });
  168. b.AddFlag(
  169. {
  170. .name = "dump-parse-tree",
  171. .help = R"""(
  172. Dump the parse tree to stdout when parsed.
  173. )""",
  174. },
  175. [&](auto& arg_b) { arg_b.Set(&dump_parse_tree); });
  176. b.AddFlag(
  177. {
  178. .name = "preorder-parse-tree",
  179. .help = R"""(
  180. When dumping the parse tree, reorder it so that it is in preorder rather than
  181. postorder.
  182. )""",
  183. },
  184. [&](auto& arg_b) { arg_b.Set(&preorder_parse_tree); });
  185. b.AddFlag(
  186. {
  187. .name = "dump-raw-sem-ir",
  188. .help = R"""(
  189. Dump the raw JSON structure of SemIR to stdout when built.
  190. )""",
  191. },
  192. [&](auto& arg_b) { arg_b.Set(&dump_raw_sem_ir); });
  193. b.AddFlag(
  194. {
  195. .name = "dump-sem-ir",
  196. .help = R"""(
  197. Dump the SemIR to stdout when built.
  198. )""",
  199. },
  200. [&](auto& arg_b) { arg_b.Set(&dump_sem_ir); });
  201. b.AddFlag(
  202. {
  203. .name = "builtin-sem-ir",
  204. .help = R"""(
  205. Include the SemIR for builtins when dumping it.
  206. )""",
  207. },
  208. [&](auto& arg_b) { arg_b.Set(&builtin_sem_ir); });
  209. b.AddFlag(
  210. {
  211. .name = "dump-llvm-ir",
  212. .help = R"""(
  213. Dump the LLVM IR to stdout after lowering.
  214. )""",
  215. },
  216. [&](auto& arg_b) { arg_b.Set(&dump_llvm_ir); });
  217. b.AddFlag(
  218. {
  219. .name = "dump-asm",
  220. .help = R"""(
  221. Dump the generated assembly to stdout after codegen.
  222. )""",
  223. },
  224. [&](auto& arg_b) { arg_b.Set(&dump_asm); });
  225. }
  226. Phase phase;
  227. std::string host = llvm::sys::getDefaultTargetTriple();
  228. llvm::StringRef target;
  229. llvm::StringRef output_file_name;
  230. llvm::SmallVector<llvm::StringRef> input_file_names;
  231. bool asm_output = false;
  232. bool force_obj_output = false;
  233. bool dump_tokens = false;
  234. bool dump_parse_tree = false;
  235. bool dump_raw_sem_ir = false;
  236. bool dump_sem_ir = false;
  237. bool dump_llvm_ir = false;
  238. bool dump_asm = false;
  239. bool stream_errors = false;
  240. bool preorder_parse_tree = false;
  241. bool builtin_sem_ir = false;
  242. };
  243. struct Driver::Options {
  244. static constexpr CommandLine::CommandInfo Info = {
  245. .name = "carbon",
  246. // TODO: Setup more detailed version information and use that here.
  247. .version = R"""(
  248. Carbon Language toolchain -- version 0.0.0
  249. )""",
  250. .help = R"""(
  251. This is the unified Carbon Language toolchain driver. It's subcommands provide
  252. all of the core behavior of the toolchain, including compilation, linking, and
  253. developer tools. Each of these has its own subcommand, and you can pass a
  254. specific subcommand to the `help` subcommand to get details about is usage.
  255. )""",
  256. .help_epilogue = R"""(
  257. For questions, issues, or bug reports, please use our GitHub project:
  258. https://github.com/carbon-language/carbon-lang
  259. )""",
  260. };
  261. enum class Subcommand : int8_t {
  262. Compile,
  263. };
  264. void Build(CommandLine::CommandBuilder& b) {
  265. b.AddFlag(
  266. {
  267. .name = "verbose",
  268. .short_name = "v",
  269. .help = "Enable verbose logging to the stderr stream.",
  270. },
  271. [&](CommandLine::FlagBuilder& arg_b) { arg_b.Set(&verbose); });
  272. b.AddSubcommand(CompileOptions::Info,
  273. [&](CommandLine::CommandBuilder& sub_b) {
  274. compile_options.Build(sub_b);
  275. sub_b.Do([&] { subcommand = Subcommand::Compile; });
  276. });
  277. b.RequiresSubcommand();
  278. }
  279. bool verbose;
  280. Subcommand subcommand;
  281. CompileOptions compile_options;
  282. };
  283. auto Driver::ParseArgs(llvm::ArrayRef<llvm::StringRef> args, Options& options)
  284. -> CommandLine::ParseResult {
  285. return CommandLine::Parse(
  286. args, output_stream_, error_stream_, Options::Info,
  287. [&](CommandLine::CommandBuilder& b) { options.Build(b); });
  288. }
  289. auto Driver::RunCommand(llvm::ArrayRef<llvm::StringRef> args) -> bool {
  290. Options options;
  291. CommandLine::ParseResult result = ParseArgs(args, options);
  292. if (result == CommandLine::ParseResult::Error) {
  293. return false;
  294. } else if (result == CommandLine::ParseResult::MetaSuccess) {
  295. return true;
  296. }
  297. if (options.verbose) {
  298. // Note this implies streamed output in order to interleave.
  299. vlog_stream_ = &error_stream_;
  300. }
  301. switch (options.subcommand) {
  302. case Options::Subcommand::Compile:
  303. return Compile(options.compile_options);
  304. }
  305. llvm_unreachable("All subcommands handled!");
  306. }
  307. auto Driver::ValidateCompileOptions(const CompileOptions& options) const
  308. -> bool {
  309. using Phase = CompileOptions::Phase;
  310. switch (options.phase) {
  311. case Phase::Lex:
  312. if (options.dump_parse_tree) {
  313. error_stream_ << "ERROR: Requested dumping the parse tree but compile "
  314. "phase is limited to '"
  315. << options.phase << "'\n";
  316. return false;
  317. }
  318. [[clang::fallthrough]];
  319. case Phase::Parse:
  320. if (options.dump_sem_ir) {
  321. error_stream_ << "ERROR: Requested dumping the SemIR but compile phase "
  322. "is limited to '"
  323. << options.phase << "'\n";
  324. return false;
  325. }
  326. [[clang::fallthrough]];
  327. case Phase::Check:
  328. if (options.dump_llvm_ir) {
  329. error_stream_ << "ERROR: Requested dumping the LLVM IR but compile "
  330. "phase is limited to '"
  331. << options.phase << "'\n";
  332. return false;
  333. }
  334. [[clang::fallthrough]];
  335. case Phase::Lower:
  336. case Phase::CodeGen:
  337. // Everything can be dumped in these phases.
  338. break;
  339. }
  340. return true;
  341. }
  342. // Ties together information for a file being compiled.
  343. class Driver::CompilationUnit {
  344. public:
  345. explicit CompilationUnit(Driver* driver, const CompileOptions& options,
  346. llvm::StringRef input_file_name)
  347. : driver_(driver),
  348. options_(options),
  349. input_file_name_(input_file_name),
  350. vlog_stream_(driver_->vlog_stream_),
  351. stream_consumer_(driver_->error_stream_) {
  352. if (vlog_stream_ != nullptr || options_.stream_errors) {
  353. consumer_ = &stream_consumer_;
  354. } else {
  355. sorting_consumer_ = SortingDiagnosticConsumer(stream_consumer_);
  356. consumer_ = &*sorting_consumer_;
  357. }
  358. }
  359. // Loads source and lexes it. Returns true on success.
  360. auto RunLex() -> bool {
  361. LogCall("SourceBuffer::CreateFromFile", [&] {
  362. source_ = SourceBuffer::CreateFromFile(driver_->fs_, input_file_name_,
  363. *consumer_);
  364. });
  365. if (!source_) {
  366. return false;
  367. }
  368. CARBON_VLOG() << "*** SourceBuffer ***\n```\n"
  369. << source_->text() << "\n```\n";
  370. LogCall("Lex::TokenizedBuffer::Lex",
  371. [&] { tokens_ = Lex::TokenizedBuffer::Lex(*source_, *consumer_); });
  372. if (options_.dump_tokens) {
  373. consumer_->Flush();
  374. driver_->output_stream_ << tokens_;
  375. }
  376. CARBON_VLOG() << "*** Lex::TokenizedBuffer ***\n" << tokens_;
  377. return !tokens_->has_errors();
  378. }
  379. // Parses tokens. Returns true on success.
  380. auto RunParse() -> bool {
  381. LogCall("Parse::Tree::Parse", [&] {
  382. parse_tree_ = Parse::Tree::Parse(*tokens_, *consumer_, vlog_stream_);
  383. });
  384. if (options_.dump_parse_tree) {
  385. consumer_->Flush();
  386. parse_tree_->Print(driver_->output_stream_, options_.preorder_parse_tree);
  387. }
  388. CARBON_VLOG() << "*** Parse::Tree ***\n" << parse_tree_;
  389. return !parse_tree_->has_errors();
  390. }
  391. // Check the parse tree and produce SemIR. Returns true on success.
  392. auto RunCheck(const SemIR::File& builtins) -> bool {
  393. LogCall("Check::CheckParseTree", [&] {
  394. sem_ir_ = Check::CheckParseTree(builtins, *tokens_, *parse_tree_,
  395. *consumer_, vlog_stream_);
  396. });
  397. // We've finished all steps that can produce diagnostics. Emit the
  398. // diagnostics now, so that the developer sees them sooner and doesn't need
  399. // to wait for code generation.
  400. consumer_->Flush();
  401. CARBON_VLOG() << "*** Raw SemIR::File ***\n" << *sem_ir_ << "\n";
  402. if (options_.dump_raw_sem_ir) {
  403. sem_ir_->Print(driver_->output_stream_, options_.builtin_sem_ir);
  404. if (options_.dump_sem_ir) {
  405. driver_->output_stream_ << "\n";
  406. }
  407. }
  408. if (vlog_stream_) {
  409. CARBON_VLOG() << "*** SemIR::File ***\n";
  410. SemIR::FormatFile(*tokens_, *parse_tree_, *sem_ir_, *vlog_stream_);
  411. }
  412. if (options_.dump_sem_ir) {
  413. SemIR::FormatFile(*tokens_, *parse_tree_, *sem_ir_,
  414. driver_->output_stream_);
  415. }
  416. return !sem_ir_->has_errors();
  417. }
  418. // Lower SemIR to LLVM IR.
  419. auto RunLower() -> void {
  420. LogCall("Lower::LowerToLLVM", [&] {
  421. llvm_context_ = std::make_unique<llvm::LLVMContext>();
  422. module_ = Lower::LowerToLLVM(*llvm_context_, input_file_name_, *sem_ir_,
  423. vlog_stream_);
  424. });
  425. if (vlog_stream_) {
  426. CARBON_VLOG() << "*** llvm::Module ***\n";
  427. module_->print(*vlog_stream_, /*AAW=*/nullptr,
  428. /*ShouldPreserveUseListOrder=*/false,
  429. /*IsForDebug=*/true);
  430. }
  431. if (options_.dump_llvm_ir) {
  432. module_->print(driver_->output_stream_, /*AAW=*/nullptr,
  433. /*ShouldPreserveUseListOrder=*/true);
  434. }
  435. }
  436. // Do codegen. Returns true on success.
  437. auto RunCodeGen() -> bool {
  438. CARBON_VLOG() << "*** CodeGen ***\n";
  439. std::optional<CodeGen> codegen =
  440. CodeGen::Create(*module_, options_.target, driver_->error_stream_);
  441. if (!codegen) {
  442. return false;
  443. }
  444. if (vlog_stream_) {
  445. CARBON_VLOG() << "*** Assembly ***\n";
  446. codegen->EmitAssembly(*vlog_stream_);
  447. }
  448. if (options_.output_file_name == "-") {
  449. // TODO: the output file name, forcing object output, and requesting
  450. // textual assembly output are all somewhat linked flags. We should add
  451. // some validation that they are used correctly.
  452. if (options_.force_obj_output) {
  453. if (!codegen->EmitObject(driver_->output_stream_)) {
  454. return false;
  455. }
  456. } else {
  457. if (!codegen->EmitAssembly(driver_->output_stream_)) {
  458. return false;
  459. }
  460. }
  461. } else {
  462. llvm::SmallString<256> output_file_name = options_.output_file_name;
  463. if (output_file_name.empty()) {
  464. output_file_name = input_file_name_;
  465. llvm::sys::path::replace_extension(output_file_name,
  466. options_.asm_output ? ".s" : ".o");
  467. }
  468. CARBON_VLOG() << "Writing output to: " << output_file_name << "\n";
  469. std::error_code ec;
  470. llvm::raw_fd_ostream output_file(output_file_name, ec,
  471. llvm::sys::fs::OF_None);
  472. if (ec) {
  473. driver_->error_stream_ << "ERROR: Could not open output file '"
  474. << output_file_name << "': " << ec.message()
  475. << "\n";
  476. return false;
  477. }
  478. if (options_.asm_output) {
  479. if (!codegen->EmitAssembly(output_file)) {
  480. return false;
  481. }
  482. } else {
  483. if (!codegen->EmitObject(output_file)) {
  484. return false;
  485. }
  486. }
  487. }
  488. CARBON_VLOG() << "*** CodeGen done ***\n";
  489. return true;
  490. }
  491. // Flushes output.
  492. auto Flush() -> void { consumer_->Flush(); }
  493. private:
  494. // Wraps a call with log statements to indicate start and end.
  495. auto LogCall(llvm::StringLiteral label, llvm::function_ref<void()> fn)
  496. -> void {
  497. CARBON_VLOG() << "*** " << label << ": " << input_file_name_ << " ***\n";
  498. fn();
  499. CARBON_VLOG() << "*** " << label << " done ***\n";
  500. }
  501. Driver* driver_;
  502. const CompileOptions& options_;
  503. llvm::StringRef input_file_name_;
  504. // Copied from driver_ for CARBON_VLOG.
  505. llvm::raw_pwrite_stream* vlog_stream_;
  506. // Diagnostics are sent to consumer_, with optional sorting.
  507. StreamDiagnosticConsumer stream_consumer_;
  508. std::optional<SortingDiagnosticConsumer> sorting_consumer_;
  509. DiagnosticConsumer* consumer_;
  510. // These are initialized as steps are run.
  511. std::optional<SourceBuffer> source_;
  512. std::optional<Lex::TokenizedBuffer> tokens_;
  513. std::optional<Parse::Tree> parse_tree_;
  514. std::optional<SemIR::File> sem_ir_;
  515. std::unique_ptr<llvm::LLVMContext> llvm_context_;
  516. std::unique_ptr<llvm::Module> module_;
  517. };
  518. auto Driver::Compile(const CompileOptions& options) -> bool {
  519. if (!ValidateCompileOptions(options)) {
  520. return false;
  521. }
  522. llvm::SmallVector<std::unique_ptr<CompilationUnit>> units;
  523. auto flush = llvm::make_scope_exit([&]() {
  524. // The diagnostics consumer must be flushed before compilation artifacts are
  525. // destructed, because diagnostics can refer to their state. This ensures
  526. // they're flushed in order of arguments, rather than order of destruction.
  527. for (auto& unit : units) {
  528. unit->Flush();
  529. }
  530. });
  531. for (const auto& input_file_name : options.input_file_names) {
  532. units.push_back(
  533. std::make_unique<CompilationUnit>(this, options, input_file_name));
  534. }
  535. // Lex.
  536. bool success_before_lower = true;
  537. for (auto& unit : units) {
  538. success_before_lower &= unit->RunLex();
  539. }
  540. if (options.phase == CompileOptions::Phase::Lex) {
  541. return success_before_lower;
  542. }
  543. // Parse.
  544. for (auto& unit : units) {
  545. success_before_lower &= unit->RunParse();
  546. }
  547. if (options.phase == CompileOptions::Phase::Parse) {
  548. return success_before_lower;
  549. }
  550. // Check.
  551. auto builtins = Check::MakeBuiltins();
  552. // TODO: Organize units to compile in dependency order.
  553. for (auto& unit : units) {
  554. success_before_lower &= unit->RunCheck(builtins);
  555. }
  556. if (options.phase == CompileOptions::Phase::Check) {
  557. return success_before_lower;
  558. }
  559. // Unlike previous steps, errors block further progress.
  560. if (!success_before_lower) {
  561. CARBON_VLOG() << "*** Stopping before lowering due to errors ***";
  562. return false;
  563. }
  564. // Lower.
  565. for (auto& unit : units) {
  566. unit->RunLower();
  567. }
  568. if (options.phase == CompileOptions::Phase::Lower) {
  569. return true;
  570. }
  571. CARBON_CHECK(options.phase == CompileOptions::Phase::CodeGen)
  572. << "CodeGen should be the last stage";
  573. // Codegen.
  574. bool codegen_success = true;
  575. for (auto& unit : units) {
  576. codegen_success &= unit->RunCodeGen();
  577. }
  578. return codegen_success;
  579. }
  580. } // namespace Carbon