driver.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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 <algorithm>
  6. #include <memory>
  7. #include <optional>
  8. #include "common/command_line.h"
  9. #include "common/vlog.h"
  10. #include "llvm/ADT/ArrayRef.h"
  11. #include "llvm/ADT/ScopeExit.h"
  12. #include "llvm/ADT/StringExtras.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/IR/LLVMContext.h"
  15. #include "llvm/Support/Path.h"
  16. #include "llvm/TargetParser/Host.h"
  17. #include "llvm/TargetParser/Triple.h"
  18. #include "toolchain/base/value_store.h"
  19. #include "toolchain/check/check.h"
  20. #include "toolchain/codegen/codegen.h"
  21. #include "toolchain/diagnostics/sorting_diagnostic_consumer.h"
  22. #include "toolchain/driver/clang_runner.h"
  23. #include "toolchain/lex/lex.h"
  24. #include "toolchain/lower/lower.h"
  25. #include "toolchain/parse/parse.h"
  26. #include "toolchain/sem_ir/formatter.h"
  27. #include "toolchain/sem_ir/inst_namer.h"
  28. #include "toolchain/source/source_buffer.h"
  29. namespace Carbon {
  30. auto Driver::FindPreludeFiles(llvm::StringRef core_package_dir,
  31. llvm::raw_ostream& error_stream)
  32. -> llvm::SmallVector<std::string> {
  33. llvm::SmallVector<std::string> result;
  34. // Include <data>/core/prelude.carbon, which is the entry point into the
  35. // prelude.
  36. {
  37. llvm::SmallString<256> prelude_file(core_package_dir);
  38. llvm::sys::path::append(prelude_file, llvm::sys::path::Style::posix,
  39. "prelude.carbon");
  40. result.push_back(prelude_file.str().str());
  41. }
  42. // Glob for <data>/core/prelude/**/*.carbon and add all the files we find.
  43. llvm::SmallString<256> prelude_dir(core_package_dir);
  44. llvm::sys::path::append(prelude_dir, llvm::sys::path::Style::posix,
  45. "prelude");
  46. std::error_code ec;
  47. for (llvm::sys::fs::recursive_directory_iterator prelude_files_it(
  48. prelude_dir, ec, /*follow_symlinks=*/false);
  49. prelude_files_it != llvm::sys::fs::recursive_directory_iterator();
  50. prelude_files_it.increment(ec)) {
  51. if (ec) {
  52. error_stream << "ERROR: Could not find prelude: " << ec.message() << "\n";
  53. result.clear();
  54. return result;
  55. }
  56. auto prelude_file = prelude_files_it->path();
  57. if (llvm::sys::path::extension(prelude_file) == ".carbon") {
  58. result.push_back(prelude_file);
  59. }
  60. }
  61. return result;
  62. }
  63. struct Driver::CodegenOptions {
  64. void Build(CommandLine::CommandBuilder& b) {
  65. b.AddStringOption(
  66. {
  67. .name = "target",
  68. .help = R"""(
  69. Select a target platform. Uses the LLVM target syntax. Also known as a "triple"
  70. for historical reasons.
  71. This corresponds to the `target` flag to Clang and accepts the same strings
  72. documented there:
  73. https://clang.llvm.org/docs/CrossCompilation.html#target-triple
  74. )""",
  75. },
  76. [&](auto& arg_b) {
  77. arg_b.Default(host);
  78. arg_b.Set(&target);
  79. });
  80. }
  81. std::string host = llvm::sys::getDefaultTargetTriple();
  82. llvm::StringRef target;
  83. };
  84. struct Driver::CompileOptions {
  85. static constexpr CommandLine::CommandInfo Info = {
  86. .name = "compile",
  87. .help = R"""(
  88. Compile Carbon source code.
  89. This subcommand runs the Carbon compiler over input source code, checking it for
  90. errors and producing the requested output.
  91. Error messages are written to the standard error stream.
  92. Different phases of the compiler can be selected to run, and intermediate state
  93. can be written to standard output as these phases progress.
  94. )""",
  95. };
  96. enum class Phase : int8_t {
  97. Lex,
  98. Parse,
  99. Check,
  100. Lower,
  101. CodeGen,
  102. };
  103. friend auto operator<<(llvm::raw_ostream& out, Phase phase)
  104. -> llvm::raw_ostream& {
  105. switch (phase) {
  106. case Phase::Lex:
  107. out << "lex";
  108. break;
  109. case Phase::Parse:
  110. out << "parse";
  111. break;
  112. case Phase::Check:
  113. out << "check";
  114. break;
  115. case Phase::Lower:
  116. out << "lower";
  117. break;
  118. case Phase::CodeGen:
  119. out << "codegen";
  120. break;
  121. }
  122. return out;
  123. }
  124. void Build(CommandLine::CommandBuilder& b, CodegenOptions& codegen_options) {
  125. b.AddStringPositionalArg(
  126. {
  127. .name = "FILE",
  128. .help = R"""(
  129. The input Carbon source file to compile.
  130. )""",
  131. },
  132. [&](auto& arg_b) {
  133. arg_b.Required(true);
  134. arg_b.Append(&input_filenames);
  135. });
  136. b.AddOneOfOption(
  137. {
  138. .name = "phase",
  139. .help = R"""(
  140. Selects the compilation phase to run. These phases are always run in sequence,
  141. so every phase before the one selected will also be run. The default is to
  142. compile to machine code.
  143. )""",
  144. },
  145. [&](auto& arg_b) {
  146. arg_b.SetOneOf(
  147. {
  148. arg_b.OneOfValue("lex", Phase::Lex),
  149. arg_b.OneOfValue("parse", Phase::Parse),
  150. arg_b.OneOfValue("check", Phase::Check),
  151. arg_b.OneOfValue("lower", Phase::Lower),
  152. arg_b.OneOfValue("codegen", Phase::CodeGen).Default(true),
  153. },
  154. &phase);
  155. });
  156. // TODO: Rearrange the code setting this option and two related ones to
  157. // allow them to reference each other instead of hard-coding their names.
  158. b.AddStringOption(
  159. {
  160. .name = "output",
  161. .value_name = "FILE",
  162. .help = R"""(
  163. The output filename for codegen.
  164. When this is a file name, either textual assembly or a binary object will be
  165. written to it based on the flag `--asm-output`. The default is to write a binary
  166. object file.
  167. Passing `--output=-` will write the output to stdout. In that case, the flag
  168. `--asm-output` is ignored and the output defaults to textual assembly. Binary
  169. object output can be forced by enabling `--force-obj-output`.
  170. )""",
  171. },
  172. [&](auto& arg_b) { arg_b.Set(&output_filename); });
  173. // Include the common code generation options at this point to render it
  174. // after the more common options above, but before the more unusual options
  175. // below.
  176. codegen_options.Build(b);
  177. b.AddFlag(
  178. {
  179. .name = "asm-output",
  180. .help = R"""(
  181. Write textual assembly rather than a binary object file to the code generation
  182. output.
  183. This flag only applies when writing to a file. When writing to stdout, the
  184. default is textual assembly and this flag is ignored.
  185. )""",
  186. },
  187. [&](auto& arg_b) { arg_b.Set(&asm_output); });
  188. b.AddFlag(
  189. {
  190. .name = "force-obj-output",
  191. .help = R"""(
  192. Force binary object output, even with `--output=-`.
  193. When `--output=-` is set, the default is textual assembly; this forces printing
  194. of a binary object file instead. Ignored for other `--output` values.
  195. )""",
  196. },
  197. [&](auto& arg_b) { arg_b.Set(&force_obj_output); });
  198. b.AddFlag(
  199. {
  200. .name = "stream-errors",
  201. .help = R"""(
  202. Stream error messages to stderr as they are generated rather than sorting them
  203. and displaying them in source order.
  204. )""",
  205. },
  206. [&](auto& arg_b) { arg_b.Set(&stream_errors); });
  207. b.AddFlag(
  208. {
  209. .name = "dump-shared-values",
  210. .help = R"""(
  211. Dumps shared values. These aren't owned by any particular file or phase.
  212. )""",
  213. },
  214. [&](auto& arg_b) { arg_b.Set(&dump_shared_values); });
  215. b.AddFlag(
  216. {
  217. .name = "dump-tokens",
  218. .help = R"""(
  219. Dump the tokens to stdout when lexed.
  220. )""",
  221. },
  222. [&](auto& arg_b) { arg_b.Set(&dump_tokens); });
  223. b.AddFlag(
  224. {
  225. .name = "dump-parse-tree",
  226. .help = R"""(
  227. Dump the parse tree to stdout when parsed.
  228. )""",
  229. },
  230. [&](auto& arg_b) { arg_b.Set(&dump_parse_tree); });
  231. b.AddFlag(
  232. {
  233. .name = "preorder-parse-tree",
  234. .help = R"""(
  235. When dumping the parse tree, reorder it so that it is in preorder rather than
  236. postorder.
  237. )""",
  238. },
  239. [&](auto& arg_b) { arg_b.Set(&preorder_parse_tree); });
  240. b.AddFlag(
  241. {
  242. .name = "dump-raw-sem-ir",
  243. .help = R"""(
  244. Dump the raw JSON structure of SemIR to stdout when built.
  245. )""",
  246. },
  247. [&](auto& arg_b) { arg_b.Set(&dump_raw_sem_ir); });
  248. b.AddFlag(
  249. {
  250. .name = "dump-sem-ir",
  251. .help = R"""(
  252. Dump the SemIR to stdout when built.
  253. )""",
  254. },
  255. [&](auto& arg_b) { arg_b.Set(&dump_sem_ir); });
  256. b.AddFlag(
  257. {
  258. .name = "builtin-sem-ir",
  259. .help = R"""(
  260. Include the SemIR for builtins when dumping it.
  261. )""",
  262. },
  263. [&](auto& arg_b) { arg_b.Set(&builtin_sem_ir); });
  264. b.AddFlag(
  265. {
  266. .name = "dump-llvm-ir",
  267. .help = R"""(
  268. Dump the LLVM IR to stdout after lowering.
  269. )""",
  270. },
  271. [&](auto& arg_b) { arg_b.Set(&dump_llvm_ir); });
  272. b.AddFlag(
  273. {
  274. .name = "dump-asm",
  275. .help = R"""(
  276. Dump the generated assembly to stdout after codegen.
  277. )""",
  278. },
  279. [&](auto& arg_b) { arg_b.Set(&dump_asm); });
  280. b.AddFlag(
  281. {
  282. .name = "prelude-import",
  283. .help = R"""(
  284. Whether to use the implicit prelude import. Enabled by default.
  285. )""",
  286. },
  287. [&](auto& arg_b) {
  288. arg_b.Default(true);
  289. arg_b.Set(&prelude_import);
  290. });
  291. b.AddStringOption(
  292. {
  293. .name = "exclude-dump-file-prefix",
  294. .value_name = "PREFIX",
  295. .help = R"""(
  296. Excludes files with the given prefix from dumps.
  297. )""",
  298. },
  299. [&](auto& arg_b) { arg_b.Set(&exclude_dump_file_prefix); });
  300. }
  301. Phase phase;
  302. llvm::StringRef output_filename;
  303. llvm::SmallVector<llvm::StringRef> input_filenames;
  304. bool asm_output = false;
  305. bool force_obj_output = false;
  306. bool dump_shared_values = false;
  307. bool dump_tokens = false;
  308. bool dump_parse_tree = false;
  309. bool dump_raw_sem_ir = false;
  310. bool dump_sem_ir = false;
  311. bool dump_llvm_ir = false;
  312. bool dump_asm = false;
  313. bool stream_errors = false;
  314. bool preorder_parse_tree = false;
  315. bool builtin_sem_ir = false;
  316. bool prelude_import = false;
  317. llvm::StringRef exclude_dump_file_prefix;
  318. };
  319. struct Driver::LinkOptions {
  320. static constexpr CommandLine::CommandInfo Info = {
  321. .name = "link",
  322. .help = R"""(
  323. Link Carbon executables.
  324. This subcommand links Carbon executables by combining object files.
  325. TODO: Support linking binary libraries, both archives and shared libraries.
  326. TODO: Support linking against binary libraries.
  327. )""",
  328. };
  329. void Build(CommandLine::CommandBuilder& b, CodegenOptions& codegen_options) {
  330. b.AddStringPositionalArg(
  331. {
  332. .name = "OBJECT_FILE",
  333. .help = R"""(
  334. The input object files.
  335. )""",
  336. },
  337. [&](auto& arg_b) {
  338. arg_b.Required(true);
  339. arg_b.Append(&object_filenames);
  340. });
  341. b.AddStringOption(
  342. {
  343. .name = "output",
  344. .value_name = "FILE",
  345. .help = R"""(
  346. The linked file name. The output is always a linked binary.
  347. )""",
  348. },
  349. [&](auto& arg_b) {
  350. arg_b.Required(true);
  351. arg_b.Set(&output_filename);
  352. });
  353. codegen_options.Build(b);
  354. }
  355. llvm::StringRef output_filename;
  356. llvm::SmallVector<llvm::StringRef> object_filenames;
  357. };
  358. struct Driver::Options {
  359. static constexpr CommandLine::CommandInfo Info = {
  360. .name = "carbon",
  361. // TODO: Set up more detailed version information and use that here.
  362. .version = R"""(
  363. Carbon Language toolchain -- version 0.0.0
  364. )""",
  365. .help = R"""(
  366. This is the unified Carbon Language toolchain driver. Its subcommands provide
  367. all of the core behavior of the toolchain, including compilation, linking, and
  368. developer tools. Each of these has its own subcommand, and you can pass a
  369. specific subcommand to the `help` subcommand to get details about its usage.
  370. )""",
  371. .help_epilogue = R"""(
  372. For questions, issues, or bug reports, please use our GitHub project:
  373. https://github.com/carbon-language/carbon-lang
  374. )""",
  375. };
  376. enum class Subcommand : int8_t {
  377. Compile,
  378. Link,
  379. };
  380. void Build(CommandLine::CommandBuilder& b) {
  381. b.AddFlag(
  382. {
  383. .name = "verbose",
  384. .short_name = "v",
  385. .help = "Enable verbose logging to the stderr stream.",
  386. },
  387. [&](CommandLine::FlagBuilder& arg_b) { arg_b.Set(&verbose); });
  388. b.AddSubcommand(CompileOptions::Info,
  389. [&](CommandLine::CommandBuilder& sub_b) {
  390. compile_options.Build(sub_b, codegen_options);
  391. sub_b.Do([&] { subcommand = Subcommand::Compile; });
  392. });
  393. b.AddSubcommand(LinkOptions::Info, [&](CommandLine::CommandBuilder& sub_b) {
  394. link_options.Build(sub_b, codegen_options);
  395. sub_b.Do([&] { subcommand = Subcommand::Link; });
  396. });
  397. b.RequiresSubcommand();
  398. }
  399. bool verbose;
  400. Subcommand subcommand;
  401. CodegenOptions codegen_options;
  402. CompileOptions compile_options;
  403. LinkOptions link_options;
  404. };
  405. auto Driver::ParseArgs(llvm::ArrayRef<llvm::StringRef> args, Options& options)
  406. -> CommandLine::ParseResult {
  407. return CommandLine::Parse(
  408. args, output_stream_, error_stream_, Options::Info,
  409. [&](CommandLine::CommandBuilder& b) { options.Build(b); });
  410. }
  411. auto Driver::RunCommand(llvm::ArrayRef<llvm::StringRef> args) -> RunResult {
  412. Options options;
  413. CommandLine::ParseResult result = ParseArgs(args, options);
  414. if (result == CommandLine::ParseResult::Error) {
  415. return {.success = false};
  416. } else if (result == CommandLine::ParseResult::MetaSuccess) {
  417. return {.success = true};
  418. }
  419. if (options.verbose) {
  420. // Note this implies streamed output in order to interleave.
  421. vlog_stream_ = &error_stream_;
  422. }
  423. switch (options.subcommand) {
  424. case Options::Subcommand::Compile:
  425. return Compile(options.compile_options, options.codegen_options);
  426. case Options::Subcommand::Link:
  427. return Link(options.link_options, options.codegen_options);
  428. }
  429. llvm_unreachable("All subcommands handled!");
  430. }
  431. auto Driver::ValidateCompileOptions(const CompileOptions& options) const
  432. -> bool {
  433. using Phase = CompileOptions::Phase;
  434. switch (options.phase) {
  435. case Phase::Lex:
  436. if (options.dump_parse_tree) {
  437. error_stream_ << "ERROR: Requested dumping the parse tree but compile "
  438. "phase is limited to '"
  439. << options.phase << "'.\n";
  440. return false;
  441. }
  442. [[fallthrough]];
  443. case Phase::Parse:
  444. if (options.dump_sem_ir) {
  445. error_stream_ << "ERROR: Requested dumping the SemIR but compile phase "
  446. "is limited to '"
  447. << options.phase << "'.\n";
  448. return false;
  449. }
  450. [[fallthrough]];
  451. case Phase::Check:
  452. if (options.dump_llvm_ir) {
  453. error_stream_ << "ERROR: Requested dumping the LLVM IR but compile "
  454. "phase is limited to '"
  455. << options.phase << "'.\n";
  456. return false;
  457. }
  458. [[fallthrough]];
  459. case Phase::Lower:
  460. case Phase::CodeGen:
  461. // Everything can be dumped in these phases.
  462. break;
  463. }
  464. return true;
  465. }
  466. // Ties together information for a file being compiled.
  467. class Driver::CompilationUnit {
  468. public:
  469. explicit CompilationUnit(Driver* driver, const CompileOptions& options,
  470. const CodegenOptions& codegen_options,
  471. DiagnosticConsumer* consumer,
  472. llvm::StringRef input_filename)
  473. : driver_(driver),
  474. options_(options),
  475. codegen_options_(codegen_options),
  476. input_filename_(input_filename),
  477. vlog_stream_(driver_->vlog_stream_) {
  478. if (vlog_stream_ != nullptr || options_.stream_errors) {
  479. consumer_ = consumer;
  480. } else {
  481. sorting_consumer_ = SortingDiagnosticConsumer(*consumer);
  482. consumer_ = &*sorting_consumer_;
  483. }
  484. }
  485. // Loads source and lexes it. Returns true on success.
  486. auto RunLex() -> void {
  487. LogCall("SourceBuffer::MakeFromFile", [&] {
  488. if (input_filename_ == "-") {
  489. source_ = SourceBuffer::MakeFromStdin(*consumer_);
  490. } else {
  491. source_ = SourceBuffer::MakeFromFile(driver_->fs_, input_filename_,
  492. *consumer_);
  493. }
  494. });
  495. if (!source_) {
  496. success_ = false;
  497. return;
  498. }
  499. CARBON_VLOG() << "*** SourceBuffer ***\n```\n"
  500. << source_->text() << "\n```\n";
  501. LogCall("Lex::Lex",
  502. [&] { tokens_ = Lex::Lex(value_stores_, *source_, *consumer_); });
  503. if (options_.dump_tokens && IncludeInDumps()) {
  504. consumer_->Flush();
  505. driver_->output_stream_ << tokens_;
  506. }
  507. CARBON_VLOG() << "*** Lex::TokenizedBuffer ***\n" << tokens_;
  508. if (tokens_->has_errors()) {
  509. success_ = false;
  510. }
  511. }
  512. // Parses tokens. Returns true on success.
  513. auto RunParse() -> void {
  514. CARBON_CHECK(tokens_);
  515. LogCall("Parse::Parse", [&] {
  516. parse_tree_ = Parse::Parse(*tokens_, *consumer_, vlog_stream_);
  517. });
  518. if (options_.dump_parse_tree && IncludeInDumps()) {
  519. consumer_->Flush();
  520. parse_tree_->Print(driver_->output_stream_, options_.preorder_parse_tree);
  521. }
  522. CARBON_VLOG() << "*** Parse::Tree ***\n" << parse_tree_;
  523. if (parse_tree_->has_errors()) {
  524. success_ = false;
  525. }
  526. }
  527. // Returns information needed to check this unit.
  528. auto GetCheckUnit() -> Check::Unit {
  529. CARBON_CHECK(parse_tree_);
  530. return {.value_stores = &value_stores_,
  531. .tokens = &*tokens_,
  532. .parse_tree = &*parse_tree_,
  533. .consumer = consumer_,
  534. .sem_ir = &sem_ir_};
  535. }
  536. // Runs post-check logic. Returns true if checking succeeded for the IR.
  537. auto PostCheck() -> void {
  538. CARBON_CHECK(sem_ir_);
  539. // We've finished all steps that can produce diagnostics. Emit the
  540. // diagnostics now, so that the developer sees them sooner and doesn't need
  541. // to wait for code generation.
  542. consumer_->Flush();
  543. CARBON_VLOG() << "*** Raw SemIR::File ***\n" << *sem_ir_ << "\n";
  544. if (options_.dump_raw_sem_ir && IncludeInDumps()) {
  545. sem_ir_->Print(driver_->output_stream_, options_.builtin_sem_ir);
  546. if (options_.dump_sem_ir) {
  547. driver_->output_stream_ << "\n";
  548. }
  549. }
  550. if (vlog_stream_) {
  551. CARBON_VLOG() << "*** SemIR::File ***\n";
  552. SemIR::FormatFile(*tokens_, *parse_tree_, *sem_ir_, *vlog_stream_);
  553. }
  554. if (options_.dump_sem_ir && IncludeInDumps()) {
  555. SemIR::FormatFile(*tokens_, *parse_tree_, *sem_ir_,
  556. driver_->output_stream_);
  557. }
  558. if (sem_ir_->has_errors()) {
  559. success_ = false;
  560. }
  561. }
  562. // Lower SemIR to LLVM IR.
  563. auto RunLower() -> void {
  564. CARBON_CHECK(sem_ir_);
  565. LogCall("Lower::LowerToLLVM", [&] {
  566. llvm_context_ = std::make_unique<llvm::LLVMContext>();
  567. // TODO: Consider disabling instruction naming by default if we're not
  568. // producing textual LLVM IR.
  569. SemIR::InstNamer inst_namer(*tokens_, *parse_tree_, *sem_ir_);
  570. module_ = Lower::LowerToLLVM(*llvm_context_, input_filename_, *sem_ir_,
  571. &inst_namer, vlog_stream_);
  572. });
  573. if (vlog_stream_) {
  574. CARBON_VLOG() << "*** llvm::Module ***\n";
  575. module_->print(*vlog_stream_, /*AAW=*/nullptr,
  576. /*ShouldPreserveUseListOrder=*/false,
  577. /*IsForDebug=*/true);
  578. }
  579. if (options_.dump_llvm_ir && IncludeInDumps()) {
  580. module_->print(driver_->output_stream_, /*AAW=*/nullptr,
  581. /*ShouldPreserveUseListOrder=*/true);
  582. }
  583. }
  584. auto RunCodeGen() -> void {
  585. CARBON_CHECK(module_);
  586. LogCall("CodeGen", [&] { success_ = RunCodeGenHelper(); });
  587. }
  588. // Runs post-compile logic. This is always called, and called after all other
  589. // actions on the CompilationUnit.
  590. auto PostCompile() const -> void {
  591. if (options_.dump_shared_values && IncludeInDumps()) {
  592. Yaml::Print(driver_->output_stream_,
  593. value_stores_.OutputYaml(input_filename_));
  594. }
  595. // The diagnostics consumer must be flushed before compilation artifacts are
  596. // destructed, because diagnostics can refer to their state.
  597. consumer_->Flush();
  598. }
  599. auto input_filename() -> llvm::StringRef { return input_filename_; }
  600. auto success() -> bool { return success_; }
  601. auto has_source() -> bool { return source_.has_value(); }
  602. private:
  603. // Do codegen. Returns true on success.
  604. auto RunCodeGenHelper() -> bool {
  605. std::optional<CodeGen> codegen = CodeGen::Make(
  606. *module_, codegen_options_.target, driver_->error_stream_);
  607. if (!codegen) {
  608. return false;
  609. }
  610. if (vlog_stream_) {
  611. CARBON_VLOG() << "*** Assembly ***\n";
  612. codegen->EmitAssembly(*vlog_stream_);
  613. }
  614. if (options_.output_filename == "-") {
  615. // TODO: the output file name, forcing object output, and requesting
  616. // textual assembly output are all somewhat linked flags. We should add
  617. // some validation that they are used correctly.
  618. if (options_.force_obj_output) {
  619. if (!codegen->EmitObject(driver_->output_stream_)) {
  620. return false;
  621. }
  622. } else {
  623. if (!codegen->EmitAssembly(driver_->output_stream_)) {
  624. return false;
  625. }
  626. }
  627. } else {
  628. llvm::SmallString<256> output_filename = options_.output_filename;
  629. if (output_filename.empty()) {
  630. if (!source_->is_regular_file()) {
  631. // Don't invent file names like `-.o` or `/dev/stdin.o`.
  632. driver_->error_stream_
  633. << "ERROR: Output file name must be specified for input '"
  634. << input_filename_ << "' that is not a regular file.\n";
  635. return false;
  636. }
  637. output_filename = input_filename_;
  638. llvm::sys::path::replace_extension(output_filename,
  639. options_.asm_output ? ".s" : ".o");
  640. } else {
  641. // TODO: Handle the case where multiple input files were specified
  642. // along with an output file name. That should either be an error or
  643. // should produce a single LLVM IR module containing all inputs.
  644. // Currently each unit overwrites the output from the previous one in
  645. // this case.
  646. }
  647. CARBON_VLOG() << "Writing output to: " << output_filename << "\n";
  648. std::error_code ec;
  649. llvm::raw_fd_ostream output_file(output_filename, ec,
  650. llvm::sys::fs::OF_None);
  651. if (ec) {
  652. driver_->error_stream_ << "ERROR: Could not open output file '"
  653. << output_filename << "': " << ec.message()
  654. << "\n";
  655. return false;
  656. }
  657. if (options_.asm_output) {
  658. if (!codegen->EmitAssembly(output_file)) {
  659. return false;
  660. }
  661. } else {
  662. if (!codegen->EmitObject(output_file)) {
  663. return false;
  664. }
  665. }
  666. }
  667. return true;
  668. }
  669. // Wraps a call with log statements to indicate start and end.
  670. auto LogCall(llvm::StringLiteral label, llvm::function_ref<void()> fn)
  671. -> void {
  672. CARBON_VLOG() << "*** " << label << ": " << input_filename_ << " ***\n";
  673. fn();
  674. CARBON_VLOG() << "*** " << label << " done ***\n";
  675. }
  676. // Returns true if the file can be dumped.
  677. auto IncludeInDumps() const -> bool {
  678. return options_.exclude_dump_file_prefix.empty() ||
  679. !input_filename_.starts_with(options_.exclude_dump_file_prefix);
  680. }
  681. Driver* driver_;
  682. SharedValueStores value_stores_;
  683. const CompileOptions& options_;
  684. const CodegenOptions& codegen_options_;
  685. std::string input_filename_;
  686. // Copied from driver_ for CARBON_VLOG.
  687. llvm::raw_pwrite_stream* vlog_stream_;
  688. // Diagnostics are sent to consumer_, with optional sorting.
  689. std::optional<SortingDiagnosticConsumer> sorting_consumer_;
  690. DiagnosticConsumer* consumer_;
  691. bool success_ = true;
  692. // These are initialized as steps are run.
  693. std::optional<SourceBuffer> source_;
  694. std::optional<Lex::TokenizedBuffer> tokens_;
  695. std::optional<Parse::Tree> parse_tree_;
  696. std::optional<SemIR::File> sem_ir_;
  697. std::unique_ptr<llvm::LLVMContext> llvm_context_;
  698. std::unique_ptr<llvm::Module> module_;
  699. };
  700. auto Driver::Compile(const CompileOptions& options,
  701. const CodegenOptions& codegen_options) -> RunResult {
  702. if (!ValidateCompileOptions(options)) {
  703. return {.success = false};
  704. }
  705. // Find the files comprising the prelude if we are importing it.
  706. // TODO: Replace this with a search for library api files in a
  707. // package-specific search path based on the library name.
  708. bool want_prelude =
  709. options.prelude_import && options.phase >= CompileOptions::Phase::Check;
  710. auto prelude = want_prelude ? FindPreludeFiles(installation_->core_package(),
  711. error_stream_)
  712. : llvm::SmallVector<std::string>{};
  713. if (want_prelude && prelude.empty()) {
  714. return {.success = false};
  715. }
  716. // Prepare CompilationUnits before building scope exit handlers.
  717. StreamDiagnosticConsumer stream_consumer(error_stream_);
  718. llvm::SmallVector<std::unique_ptr<CompilationUnit>> units;
  719. units.reserve(prelude.size() + options.input_filenames.size());
  720. // Add the prelude files.
  721. for (const auto& input_filename : prelude) {
  722. units.push_back(std::make_unique<CompilationUnit>(
  723. this, options, codegen_options, &stream_consumer, input_filename));
  724. }
  725. // Add the input source files.
  726. for (const auto& input_filename : options.input_filenames) {
  727. units.push_back(std::make_unique<CompilationUnit>(
  728. this, options, codegen_options, &stream_consumer, input_filename));
  729. }
  730. auto on_exit = llvm::make_scope_exit([&]() {
  731. // Finish compilation units. This flushes their diagnostics in the order in
  732. // which they were specified on the command line.
  733. for (auto& unit : units) {
  734. unit->PostCompile();
  735. }
  736. stream_consumer.Flush();
  737. });
  738. // Returns a RunResult object. Called whenever Compile returns.
  739. auto make_result = [&]() {
  740. RunResult result = {.success = true};
  741. for (const auto& unit : units) {
  742. result.success &= unit->success();
  743. result.per_file_success.push_back(
  744. {unit->input_filename().str(), unit->success()});
  745. }
  746. return result;
  747. };
  748. // Lex.
  749. for (auto& unit : units) {
  750. unit->RunLex();
  751. }
  752. if (options.phase == CompileOptions::Phase::Lex) {
  753. return make_result();
  754. }
  755. // Parse and check phases examine `has_source` because they want to proceed if
  756. // lex failed, but not if source doesn't exist. Later steps are skipped if
  757. // anything failed, so don't need this.
  758. // Parse.
  759. for (auto& unit : units) {
  760. if (unit->has_source()) {
  761. unit->RunParse();
  762. }
  763. }
  764. if (options.phase == CompileOptions::Phase::Parse) {
  765. return make_result();
  766. }
  767. // Check.
  768. SharedValueStores builtin_value_stores;
  769. llvm::SmallVector<Check::Unit> check_units;
  770. for (auto& unit : units) {
  771. if (unit->has_source()) {
  772. check_units.push_back(unit->GetCheckUnit());
  773. }
  774. }
  775. CARBON_VLOG() << "*** Check::CheckParseTrees ***\n";
  776. Check::CheckParseTrees(llvm::MutableArrayRef(check_units),
  777. options.prelude_import, vlog_stream_);
  778. CARBON_VLOG() << "*** Check::CheckParseTrees done ***\n";
  779. for (auto& unit : units) {
  780. if (unit->has_source()) {
  781. unit->PostCheck();
  782. }
  783. }
  784. if (options.phase == CompileOptions::Phase::Check) {
  785. return make_result();
  786. }
  787. // Unlike previous steps, errors block further progress.
  788. if (std::any_of(units.begin(), units.end(),
  789. [&](const auto& unit) { return !unit->success(); })) {
  790. CARBON_VLOG() << "*** Stopping before lowering due to errors ***";
  791. return make_result();
  792. }
  793. // Lower.
  794. for (auto& unit : units) {
  795. unit->RunLower();
  796. }
  797. if (options.phase == CompileOptions::Phase::Lower) {
  798. return make_result();
  799. }
  800. CARBON_CHECK(options.phase == CompileOptions::Phase::CodeGen)
  801. << "CodeGen should be the last stage";
  802. // Codegen.
  803. for (auto& unit : units) {
  804. unit->RunCodeGen();
  805. }
  806. return make_result();
  807. }
  808. static void AddOSFlags(llvm::StringRef target,
  809. llvm::SmallVectorImpl<llvm::StringRef>& args) {
  810. llvm::Triple triple(target);
  811. switch (triple.getOS()) {
  812. case llvm::Triple::Darwin:
  813. case llvm::Triple::MacOSX:
  814. // On macOS we need to set the sysroot to a viable SDK. Currently, this
  815. // hard codes the path to be the unversioned symlink. The prefix is also
  816. // hard coded in Homebrew and so this seems likely to work reasonably
  817. // well. Homebrew and I suspect the Xcode Clang both have this hard coded
  818. // at build time, so this seems reasonably safe but we can revisit if/when
  819. // needed.
  820. args.push_back(
  821. "--sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk");
  822. // We also need to insist on a modern linker, otherwise the driver tries
  823. // too old and deprecated flags. The specific number here comes from an
  824. // inspection of the Clang driver source code to understand where features
  825. // were enabled, and this appears to be the latest version to control
  826. // driver behavior.
  827. //
  828. // TODO: We should replace this with use of `lld` eventually.
  829. args.push_back("-mlinker-version=705");
  830. break;
  831. default:
  832. // By default, just let the Clang driver handle everything.
  833. break;
  834. }
  835. }
  836. auto Driver::Link(const LinkOptions& options,
  837. const CodegenOptions& codegen_options) -> RunResult {
  838. // TODO: Currently we use the Clang driver to link. This works well on Unix
  839. // OSes but we likely need to directly build logic to invoke `link.exe` on
  840. // Windows where `cl.exe` doesn't typically cover that logic.
  841. // Use a reasonably large small vector here to minimize allocations. We expect
  842. // to link reasonably large numbers of object files.
  843. llvm::SmallVector<llvm::StringRef, 128> clang_args;
  844. // We link using a C++ mode of the driver.
  845. clang_args.push_back("--driver-mode=g++");
  846. // Use LLD, which we provide in our install directory, for linking.
  847. clang_args.push_back("-fuse-ld=lld");
  848. // Add OS-specific flags based on the target.
  849. AddOSFlags(codegen_options.target, clang_args);
  850. clang_args.push_back("-o");
  851. clang_args.push_back(options.output_filename);
  852. clang_args.append(options.object_filenames.begin(),
  853. options.object_filenames.end());
  854. ClangRunner runner(installation_, codegen_options.target, vlog_stream_);
  855. return {.success = runner.Run(clang_args)};
  856. }
  857. } // namespace Carbon