compile_subcommand.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319
  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 <functional>
  6. #include <memory>
  7. #include <optional>
  8. #include <string>
  9. #include <system_error>
  10. #include <utility>
  11. #include "common/pretty_stack_trace_function.h"
  12. #include "common/vlog.h"
  13. #include "llvm/ADT/STLExtras.h"
  14. #include "llvm/ADT/ScopeExit.h"
  15. #include "llvm/MC/TargetRegistry.h"
  16. #include "llvm/Passes/OptimizationLevel.h"
  17. #include "llvm/Passes/PassBuilder.h"
  18. #include "llvm/Passes/StandardInstrumentations.h"
  19. #include "toolchain/base/clang_invocation.h"
  20. #include "toolchain/base/timings.h"
  21. #include "toolchain/check/check.h"
  22. #include "toolchain/codegen/codegen.h"
  23. #include "toolchain/diagnostics/emitter.h"
  24. #include "toolchain/diagnostics/sorting_consumer.h"
  25. #include "toolchain/lex/lex.h"
  26. #include "toolchain/lower/lower.h"
  27. #include "toolchain/parse/parse.h"
  28. #include "toolchain/parse/tree_and_subtrees.h"
  29. #include "toolchain/sem_ir/ids.h"
  30. #include "toolchain/source/source_buffer.h"
  31. namespace Carbon {
  32. auto CompileOptions::Build(CommandLine::CommandBuilder& b) -> void {
  33. b.AddStringPositionalArg(
  34. {
  35. .name = "FILE",
  36. .help = R"""(
  37. The input Carbon source file to compile.
  38. )""",
  39. },
  40. [&](auto& arg_b) {
  41. arg_b.Required(true);
  42. arg_b.Append(&input_filenames);
  43. });
  44. b.AddOneOfOption(
  45. {
  46. .name = "phase",
  47. .help = R"""(
  48. Selects the compilation phase to run. These phases are always run in sequence,
  49. so every phase before the one selected will also be run. The default is to
  50. compile to machine code.
  51. )""",
  52. },
  53. [&](auto& arg_b) {
  54. arg_b.SetOneOf(
  55. {
  56. arg_b.OneOfValue("lex", Phase::Lex),
  57. arg_b.OneOfValue("parse", Phase::Parse),
  58. arg_b.OneOfValue("check", Phase::Check),
  59. arg_b.OneOfValue("lower", Phase::Lower),
  60. arg_b.OneOfValue("optimize", Phase::Optimize),
  61. arg_b.OneOfValue("codegen", Phase::CodeGen).Default(true),
  62. },
  63. &phase);
  64. });
  65. b.AddStringOption(
  66. {
  67. .name = "clang-arg",
  68. .value_name = "CLANG-ARG",
  69. .help = R"""(
  70. An argument to pass to the Clang compiler for use when compiling imported C++
  71. code.
  72. All flags that are accepted by the Clang driver are supported. However, you
  73. cannot specify arguments that would result in additional compilations being
  74. performed. Use `carbon clang` instead to compile additional source files.
  75. )""",
  76. },
  77. [&](auto& arg_b) { arg_b.Append(&clang_args); });
  78. b.AddStringPositionalArg(
  79. {
  80. .name = "CLANG-ARG",
  81. .help = R"""(
  82. Additional Clang arguments. See help for `--clang-arg` for details.
  83. )""",
  84. },
  85. [&](auto& arg_b) { arg_b.Append(&clang_args); });
  86. // TODO: Rearrange the code setting this option and two related ones to
  87. // allow them to reference each other instead of hard-coding their names.
  88. b.AddStringOption(
  89. {
  90. .name = "output",
  91. .value_name = "FILE",
  92. .help = R"""(
  93. The output filename for codegen.
  94. When this is a file name, either textual assembly or a binary object will be
  95. written to it based on the flag `--asm-output`. The default is to write a binary
  96. object file.
  97. Passing `--output=-` will write the output to stdout. In that case, the flag
  98. `--asm-output` is ignored and the output defaults to textual assembly. Binary
  99. object output can be forced by enabling `--force-obj-output`.
  100. )""",
  101. },
  102. [&](auto& arg_b) { arg_b.Set(&output_filename); });
  103. b.AddOneOfOption(
  104. {
  105. .name = "optimize",
  106. .help = R"""(
  107. Selects the amount of optimization to perform.
  108. )""",
  109. },
  110. [&](auto& arg_b) {
  111. arg_b.SetOneOf(
  112. {
  113. // We intentionally don't expose O2 and Os. The difference
  114. // between these levels tends to reflect what achieves the
  115. // best speed for a specific application, as they all
  116. // largely optimize for speed as the primary factor.
  117. //
  118. // Instead of controlling this with more nuanced flags, we
  119. // plan to support profile and in-source hints to the
  120. // optimizer to adjust its strategy in the specific places
  121. // where the default doesn't have the desired results.
  122. arg_b.OneOfValue("none", Lower::OptimizationLevel::None),
  123. arg_b.OneOfValue("debug", Lower::OptimizationLevel::Debug),
  124. arg_b.OneOfValue("speed", Lower::OptimizationLevel::Speed),
  125. arg_b.OneOfValue("size", Lower::OptimizationLevel::Size),
  126. },
  127. &opt_level);
  128. });
  129. // Include the common code generation options at this point to render it
  130. // after the more common options above, but before the more unusual options
  131. // below.
  132. codegen_options.Build(b);
  133. b.AddFlag(
  134. {
  135. .name = "asm-output",
  136. .help = R"""(
  137. Write textual assembly rather than a binary object file to the code generation
  138. output.
  139. This flag only applies when writing to a file. When writing to stdout, the
  140. default is textual assembly and this flag is ignored.
  141. )""",
  142. },
  143. [&](auto& arg_b) { arg_b.Set(&asm_output); });
  144. b.AddFlag(
  145. {
  146. .name = "force-obj-output",
  147. .help = R"""(
  148. Force binary object output, even with `--output=-`.
  149. When `--output=-` is set, the default is textual assembly; this forces printing
  150. of a binary object file instead. Ignored for other `--output` values.
  151. )""",
  152. },
  153. [&](auto& arg_b) { arg_b.Set(&force_obj_output); });
  154. b.AddFlag(
  155. {
  156. .name = "stream-errors",
  157. .help = R"""(
  158. Stream error messages to stderr as they are generated rather than sorting them
  159. and displaying them in source order.
  160. )""",
  161. },
  162. [&](auto& arg_b) { arg_b.Set(&stream_errors); });
  163. b.AddFlag(
  164. {
  165. .name = "dump-shared-values",
  166. .help = R"""(
  167. Dumps shared values. These aren't owned by any particular file or phase.
  168. )""",
  169. },
  170. [&](auto& arg_b) { arg_b.Set(&dump_shared_values); });
  171. b.AddFlag(
  172. {
  173. .name = "dump-tokens",
  174. .help = R"""(
  175. Dump the tokens to stdout when lexed.
  176. )""",
  177. },
  178. [&](auto& arg_b) { arg_b.Set(&dump_tokens); });
  179. b.AddFlag(
  180. {
  181. .name = "omit-file-boundary-tokens",
  182. .help = R"""(
  183. For `--dump-tokens`, omit file start and end boundary tokens.
  184. )""",
  185. },
  186. [&](auto& arg_b) { arg_b.Set(&omit_file_boundary_tokens); });
  187. b.AddFlag(
  188. {
  189. .name = "dump-parse-tree",
  190. .help = R"""(
  191. Dump the parse tree to stdout when parsed.
  192. )""",
  193. },
  194. [&](auto& arg_b) { arg_b.Set(&dump_parse_tree); });
  195. b.AddFlag(
  196. {
  197. .name = "preorder-parse-tree",
  198. .help = R"""(
  199. When dumping the parse tree, reorder it so that it is in preorder rather than
  200. postorder.
  201. )""",
  202. },
  203. [&](auto& arg_b) { arg_b.Set(&preorder_parse_tree); });
  204. b.AddFlag(
  205. {
  206. .name = "dump-raw-sem-ir",
  207. .help = R"""(
  208. Dump the raw JSON structure of SemIR to stdout when built.
  209. )""",
  210. },
  211. [&](auto& arg_b) { arg_b.Set(&dump_raw_sem_ir); });
  212. b.AddFlag(
  213. {
  214. .name = "dump-sem-ir",
  215. .help = R"""(
  216. Dump the full SemIR to stdout when built.
  217. )""",
  218. },
  219. [&](auto& arg_b) { arg_b.Set(&dump_sem_ir); });
  220. b.AddFlag(
  221. {
  222. .name = "dump-cpp-ast",
  223. .help = R"""(
  224. Dump the full C++ AST to stdout when built.
  225. )""",
  226. },
  227. [&](auto& arg_b) { arg_b.Set(&dump_cpp_ast); });
  228. b.AddOneOfOption(
  229. {
  230. .name = "dump-sem-ir-ranges",
  231. .help = R"""(
  232. Selects handling of `//@dump-sem-ir-[begin|end]` markers when dumping SemIR.
  233. By default, `if-present` prints ranges for files that have them, and full SemIR
  234. for files that don't. `only` skips files with no ranges, and `ignore` always
  235. prints full SemIR.
  236. )""",
  237. },
  238. [&](auto& arg_b) {
  239. using DumpSemIRRanges = Check::CheckParseTreesOptions::DumpSemIRRanges;
  240. arg_b.SetOneOf(
  241. {
  242. arg_b.OneOfValue("if-present", DumpSemIRRanges::IfPresent)
  243. .Default(true),
  244. arg_b.OneOfValue("only", DumpSemIRRanges::Only),
  245. arg_b.OneOfValue("ignore", DumpSemIRRanges::Ignore),
  246. },
  247. &dump_sem_ir_ranges);
  248. });
  249. b.AddFlag(
  250. {
  251. .name = "builtin-sem-ir",
  252. .help = R"""(
  253. Include the SemIR for builtins when dumping it.
  254. )""",
  255. },
  256. [&](auto& arg_b) { arg_b.Set(&builtin_sem_ir); });
  257. b.AddFlag(
  258. {
  259. .name = "dump-llvm-ir",
  260. .help = R"""(
  261. Dump the LLVM IR to stdout after lowering.
  262. )""",
  263. },
  264. [&](auto& arg_b) { arg_b.Set(&dump_llvm_ir); });
  265. b.AddFlag(
  266. {
  267. .name = "dump-asm",
  268. .help = R"""(
  269. Dump the generated assembly to stdout after codegen.
  270. )""",
  271. },
  272. [&](auto& arg_b) { arg_b.Set(&dump_asm); });
  273. b.AddFlag(
  274. {
  275. .name = "dump-mem-usage",
  276. .help = R"""(
  277. Dumps the amount of memory used.
  278. )""",
  279. },
  280. [&](auto& arg_b) { arg_b.Set(&dump_mem_usage); });
  281. b.AddFlag(
  282. {
  283. .name = "dump-timings",
  284. .help = R"""(
  285. Dumps the duration of each phase for each compilation unit.
  286. )""",
  287. },
  288. [&](auto& arg_b) { arg_b.Set(&dump_timings); });
  289. b.AddFlag(
  290. {
  291. .name = "prelude-import",
  292. .help = R"""(
  293. Whether to use the implicit prelude import. Enabled by default.
  294. )""",
  295. },
  296. [&](auto& arg_b) {
  297. arg_b.Default(true);
  298. arg_b.Set(&prelude_import);
  299. });
  300. b.AddFlag(
  301. {
  302. .name = "custom-core",
  303. .value_name = "CUSTOM_CORE",
  304. .help = R"""(
  305. Whether to use a custom Core package, the files for which must all be included
  306. in the compile command line.
  307. The prelude library in the Core package is imported automatically. By default,
  308. the Core package shipped with the toolchain is used, and its files do not need
  309. to be specified in the compile command line.
  310. )""",
  311. },
  312. [&](auto& arg_b) {
  313. arg_b.Default(false);
  314. arg_b.Set(&custom_core);
  315. });
  316. b.AddStringOption(
  317. {
  318. .name = "exclude-dump-file-prefix",
  319. .value_name = "PREFIX",
  320. .help = R"""(
  321. Excludes files with the given prefix from dumps.
  322. )""",
  323. },
  324. [&](auto& arg_b) { arg_b.Append(&exclude_dump_file_prefixes); });
  325. b.AddFlag(
  326. {
  327. .name = "debug-info",
  328. .help = R"""(
  329. Whether to emit DWARF debug information.
  330. )""",
  331. },
  332. [&](auto& arg_b) {
  333. arg_b.Default(true);
  334. arg_b.Set(&include_debug_info);
  335. });
  336. b.AddFlag(
  337. {
  338. .name = "verify-llvm-ir",
  339. .help = R"""(
  340. Whether to run the LLVM verifier on modules.
  341. )""",
  342. },
  343. [&](auto& arg_b) {
  344. arg_b.Default(true);
  345. arg_b.Set(&run_llvm_verifier);
  346. });
  347. b.AddStringOption(
  348. {
  349. .name = "sem-ir-crash-dump",
  350. .value_name = "PATH",
  351. .help = R"""(
  352. Where to write a dump of the raw SemIR emitted so far, in the event of a crash
  353. in the check phase. If empty, the dump is not written.
  354. )""",
  355. },
  356. [&](auto& arg_b) { arg_b.Set(&sem_ir_crash_dump); });
  357. }
  358. static constexpr CommandLine::CommandInfo SubcommandInfo = {
  359. .name = "compile",
  360. .help = R"""(
  361. Compile Carbon source code.
  362. This subcommand runs the Carbon compiler over input source code, checking it for
  363. errors and producing the requested output.
  364. Error messages are written to the standard error stream.
  365. Different phases of the compiler can be selected to run, and intermediate state
  366. can be written to standard output as these phases progress.
  367. )""",
  368. };
  369. CompileSubcommand::CompileSubcommand() : DriverSubcommand(SubcommandInfo) {}
  370. // Returns a string for printing the phase in a diagnostic.
  371. static auto PhaseToString(CompileOptions::Phase phase) -> std::string {
  372. switch (phase) {
  373. case CompileOptions::Phase::Lex:
  374. return "lex";
  375. case CompileOptions::Phase::Parse:
  376. return "parse";
  377. case CompileOptions::Phase::Check:
  378. return "check";
  379. case CompileOptions::Phase::Lower:
  380. return "lower";
  381. case CompileOptions::Phase::Optimize:
  382. return "optimize";
  383. case CompileOptions::Phase::CodeGen:
  384. return "codegen";
  385. }
  386. }
  387. auto CompileSubcommand::ValidateOptions(
  388. Diagnostics::NoLocEmitter& emitter) const -> bool {
  389. CARBON_DIAGNOSTIC(
  390. CompilePhaseFlagConflict, Error,
  391. "requested dumping {0} but compile phase is limited to `{1}`",
  392. std::string, std::string);
  393. using Phase = CompileOptions::Phase;
  394. switch (options_.phase) {
  395. case Phase::Lex:
  396. if (options_.dump_parse_tree) {
  397. emitter.Emit(CompilePhaseFlagConflict, "parse tree",
  398. PhaseToString(options_.phase));
  399. return false;
  400. }
  401. [[fallthrough]];
  402. case Phase::Parse:
  403. if (options_.dump_sem_ir) {
  404. emitter.Emit(CompilePhaseFlagConflict, "SemIR",
  405. PhaseToString(options_.phase));
  406. return false;
  407. }
  408. if (options_.dump_cpp_ast) {
  409. emitter.Emit(CompilePhaseFlagConflict, "C++ AST",
  410. PhaseToString(options_.phase));
  411. return false;
  412. }
  413. [[fallthrough]];
  414. case Phase::Check:
  415. if (options_.dump_llvm_ir) {
  416. emitter.Emit(CompilePhaseFlagConflict, "LLVM IR",
  417. PhaseToString(options_.phase));
  418. return false;
  419. }
  420. [[fallthrough]];
  421. case Phase::Lower:
  422. case Phase::Optimize:
  423. case Phase::CodeGen:
  424. // Everything can be dumped in these phases.
  425. break;
  426. }
  427. return true;
  428. }
  429. namespace {
  430. class MultiUnitCache;
  431. // Ties together information for a file being compiled.
  432. class CompilationUnit {
  433. public:
  434. // `driver_env`, `options`, `consumer`, and `target` must be non-null.
  435. explicit CompilationUnit(SemIR::CheckIRId check_ir_id, int total_ir_count,
  436. DriverEnv* driver_env, const CompileOptions* options,
  437. Diagnostics::Consumer* consumer,
  438. llvm::StringRef input_filename,
  439. const llvm::Target* target);
  440. // Sets the multi-unit cache and initializes dependent member state.
  441. auto SetMultiUnitCache(MultiUnitCache* cache) -> void;
  442. // Loads source and lexes it. Returns true on success.
  443. auto RunLex() -> void;
  444. // Parses tokens. Returns true on success.
  445. auto RunParse() -> void;
  446. // Returns information needed to check this unit.
  447. auto GetCheckUnit() -> Check::Unit;
  448. // Runs post-check logic. Returns true if checking succeeded for the IR.
  449. auto PostCheck() -> void;
  450. // Lower SemIR to LLVM IR.
  451. auto RunLower() -> void;
  452. // Runs the optimization pipeline.
  453. auto RunOptimize(const clang::CompilerInvocation& clang_invocation) -> void;
  454. // Runs post-lowering-to-LLVM-IR logic. This is always called if we do any
  455. // lowering work, after we've finished building the IR in RunLower() and,
  456. // optionally, RunOptimize().
  457. auto PostLower() -> void;
  458. auto RunCodeGen() -> void;
  459. // Runs post-compile logic. This is always called, and called after all other
  460. // actions on the CompilationUnit.
  461. auto PostCompile() -> void;
  462. // Flushes diagnostics, specifically as part of generating stack trace
  463. // information.
  464. auto FlushForStackTrace() -> void { consumer_->Flush(); }
  465. auto input_filename() -> llvm::StringRef { return input_filename_; }
  466. auto has_include_in_dumps() -> bool {
  467. return tokens_ && tokens_->has_include_in_dumps();
  468. }
  469. auto success() -> bool { return success_; }
  470. auto has_source() -> bool { return source_.has_value(); }
  471. auto get_trees_and_subtrees() -> Parse::GetTreeAndSubtreesFn {
  472. return *tree_and_subtrees_getter_;
  473. }
  474. private:
  475. // Do codegen. Returns true on success.
  476. auto RunCodeGenHelper() -> bool;
  477. // The TreeAndSubtrees is mainly used for debugging and diagnostics, and has
  478. // significant overhead. Avoid constructing it when unused.
  479. auto GetParseTreeAndSubtrees() -> const Parse::TreeAndSubtrees&;
  480. // Wraps a call with log statements to indicate start and end. Typically logs
  481. // with the actual function name, but marks timings with the appropriate
  482. // phase.
  483. auto LogCall(llvm::StringLiteral logging_label,
  484. llvm::StringLiteral timing_label,
  485. llvm::function_ref<auto()->void> fn) -> void;
  486. // Returns true if the current file should be included in debug dumps.
  487. auto IncludeInDumps() -> bool;
  488. // Builds the LLVM target machine.
  489. auto MakeTargetMachine(const clang::CompilerInvocation& clang_invocation)
  490. -> void;
  491. // The index of the unit amongst all units.
  492. SemIR::CheckIRId check_ir_id_;
  493. // The number of units in total.
  494. int total_ir_count_;
  495. DriverEnv* driver_env_;
  496. const CompileOptions* options_;
  497. const llvm::Target* target_;
  498. SharedValueStores value_stores_;
  499. // The input filename from the command line. For most diagnostics, we
  500. // typically use `source_->filename()`, which includes a `-` -> `<stdin>`
  501. // translation. However, logging and some diagnostics use the command line
  502. // argument.
  503. std::string input_filename_;
  504. // Copied from driver_ for CARBON_VLOG.
  505. llvm::raw_pwrite_stream* vlog_stream_;
  506. // Diagnostics are sent to consumer_, with optional sorting.
  507. std::optional<Diagnostics::SortingConsumer> sorting_consumer_;
  508. Diagnostics::Consumer* consumer_;
  509. bool success_ = true;
  510. // Initialized by `SetMultiUnitCache`.
  511. MultiUnitCache* cache_ = nullptr;
  512. // Tracks memory usage of the compile.
  513. std::optional<MemUsage> mem_usage_;
  514. // Tracks timings of the compile.
  515. std::optional<Timings> timings_;
  516. // These are initialized as steps are run.
  517. std::optional<SourceBuffer> source_;
  518. std::optional<Lex::TokenizedBuffer> tokens_;
  519. std::optional<Parse::Tree> parse_tree_;
  520. std::optional<Parse::TreeAndSubtrees> parse_tree_and_subtrees_;
  521. std::optional<std::function<auto()->const Parse::TreeAndSubtrees&>>
  522. tree_and_subtrees_getter_;
  523. std::unique_ptr<llvm::LLVMContext> llvm_context_;
  524. std::optional<SemIR::File> sem_ir_;
  525. std::unique_ptr<llvm::Module> module_;
  526. std::unique_ptr<llvm::TargetMachine> target_machine_;
  527. };
  528. // Caches lists that are shared cross-unit. Accessors do lazy caching because
  529. // they may not be used.
  530. class MultiUnitCache {
  531. public:
  532. using IncludeInDumpsStore = FixedSizeValueStore<SemIR::CheckIRId, bool>;
  533. using TreeAndSubtreesGettersStore = Parse::GetTreeAndSubtreesStore;
  534. // This relies on construction after `units` are all initialized, which is
  535. // reflected by the `ArrayRef` here.
  536. explicit MultiUnitCache(
  537. const CompileOptions* options,
  538. llvm::ArrayRef<std::unique_ptr<CompilationUnit>> units)
  539. : options_(options), units_(units) {}
  540. // If `include_in_dumps` is in use, we need to apply per-file include
  541. // settings.
  542. auto ApplyPerFileIncludeInDumps() -> void {
  543. if (!include_in_dumps_) {
  544. // No cached value to update.
  545. return;
  546. }
  547. for (const auto& [i, unit] : llvm::enumerate(units_)) {
  548. if (unit->has_include_in_dumps()) {
  549. include_in_dumps_->Set(SemIR::CheckIRId(i), true);
  550. }
  551. }
  552. }
  553. auto include_in_dumps() -> const IncludeInDumpsStore& {
  554. if (!include_in_dumps_) {
  555. include_in_dumps_.emplace(
  556. IncludeInDumpsStore::MakeWithExplicitSize(units_.size(), false));
  557. for (const auto& [i, unit] : llvm::enumerate(units_)) {
  558. // If this is first accessed after lexing is complete, we need to apply
  559. // per-file includes. Otherwise, this is based only on the exclude
  560. // option.
  561. bool include =
  562. unit->has_include_in_dumps() ||
  563. llvm::none_of(options_->exclude_dump_file_prefixes,
  564. [&](auto prefix) {
  565. return unit->input_filename().starts_with(prefix);
  566. });
  567. include_in_dumps_->Set(SemIR::CheckIRId(i), include);
  568. }
  569. }
  570. return *include_in_dumps_;
  571. }
  572. auto tree_and_subtrees_getters() -> const TreeAndSubtreesGettersStore& {
  573. if (!tree_and_subtrees_getters_) {
  574. tree_and_subtrees_getters_.emplace(
  575. TreeAndSubtreesGettersStore::MakeWithExplicitSize(units_.size(),
  576. nullptr));
  577. for (const auto& [i, unit] : llvm::enumerate(units_)) {
  578. if (unit->has_source()) {
  579. tree_and_subtrees_getters_->Set(SemIR::CheckIRId(i),
  580. unit->get_trees_and_subtrees());
  581. }
  582. }
  583. }
  584. return *tree_and_subtrees_getters_;
  585. }
  586. private:
  587. const CompileOptions* options_;
  588. // The units being compiled.
  589. llvm::ArrayRef<std::unique_ptr<CompilationUnit>> units_;
  590. // For each unit, whether it's included in dumps. Used cross-phase.
  591. std::optional<IncludeInDumpsStore> include_in_dumps_;
  592. // For each unit, the `TreeAndSubtrees` getter. Used by lowering.
  593. std::optional<TreeAndSubtreesGettersStore> tree_and_subtrees_getters_;
  594. };
  595. } // namespace
  596. CompilationUnit::CompilationUnit(SemIR::CheckIRId check_ir_id,
  597. int total_ir_count, DriverEnv* driver_env,
  598. const CompileOptions* options,
  599. Diagnostics::Consumer* consumer,
  600. llvm::StringRef input_filename,
  601. const llvm::Target* target)
  602. : check_ir_id_(check_ir_id),
  603. total_ir_count_(total_ir_count),
  604. driver_env_(driver_env),
  605. options_(options),
  606. target_(target),
  607. input_filename_(input_filename),
  608. vlog_stream_(driver_env_->vlog_stream) {
  609. if (vlog_stream_ != nullptr || options_->stream_errors) {
  610. consumer_ = consumer;
  611. } else {
  612. sorting_consumer_ = Diagnostics::SortingConsumer(*consumer);
  613. consumer_ = &*sorting_consumer_;
  614. }
  615. }
  616. auto CompilationUnit::IncludeInDumps() -> bool {
  617. return cache_->include_in_dumps().Get(check_ir_id_);
  618. }
  619. auto CompilationUnit::SetMultiUnitCache(MultiUnitCache* cache) -> void {
  620. CARBON_CHECK(!cache_, "Called SetMultiUnitCache twice");
  621. cache_ = cache;
  622. if (options_->dump_mem_usage && IncludeInDumps()) {
  623. CARBON_CHECK(!mem_usage_);
  624. mem_usage_ = MemUsage();
  625. }
  626. if (options_->dump_timings && IncludeInDumps()) {
  627. CARBON_CHECK(!timings_);
  628. timings_ = Timings();
  629. }
  630. }
  631. auto CompilationUnit::RunLex() -> void {
  632. CARBON_CHECK(cache_, "Must call SetMultiUnitCache first");
  633. CARBON_CHECK(!tokens_, "Called RunLex twice");
  634. LogCall("SourceBuffer::MakeFromFileOrStdin", "source", [&] {
  635. source_ = SourceBuffer::MakeFromFileOrStdin(*driver_env_->fs,
  636. input_filename_, *consumer_);
  637. });
  638. if (!source_) {
  639. success_ = false;
  640. return;
  641. }
  642. if (mem_usage_) {
  643. mem_usage_->Add("source_", source_->text().size(), source_->text().size());
  644. }
  645. CARBON_VLOG("*** SourceBuffer ***\n```\n{0}\n```\n", source_->text());
  646. LogCall("Lex::Lex", "lex", [&] {
  647. Lex::LexOptions options;
  648. options.consumer = consumer_;
  649. options.vlog_stream = vlog_stream_;
  650. if (options_->dump_tokens && IncludeInDumps()) {
  651. options.dump_stream = driver_env_->output_stream;
  652. options.omit_file_boundary_tokens = options_->omit_file_boundary_tokens;
  653. }
  654. tokens_ = Lex::Lex(value_stores_, *source_, options);
  655. });
  656. if (mem_usage_) {
  657. mem_usage_->Collect("tokens_", *tokens_);
  658. }
  659. if (tokens_->has_errors()) {
  660. success_ = false;
  661. }
  662. }
  663. auto CompilationUnit::RunParse() -> void {
  664. LogCall("Parse::Parse", "parse", [&] {
  665. Parse::ParseOptions options;
  666. options.consumer = consumer_;
  667. options.vlog_stream = vlog_stream_;
  668. if (options_->dump_parse_tree && IncludeInDumps()) {
  669. options.dump_stream = driver_env_->output_stream;
  670. options.dump_preorder_parse_tree = options_->preorder_parse_tree;
  671. }
  672. parse_tree_ = Parse::Parse(*tokens_, options);
  673. });
  674. if (mem_usage_) {
  675. mem_usage_->Collect("parse_tree_", *parse_tree_);
  676. }
  677. if (parse_tree_->has_errors()) {
  678. success_ = false;
  679. }
  680. }
  681. auto CompilationUnit::GetCheckUnit() -> Check::Unit {
  682. CARBON_CHECK(parse_tree_, "Must call RunParse first");
  683. CARBON_CHECK(!sem_ir_, "Called GetCheckUnit twice");
  684. tree_and_subtrees_getter_ = [this]() -> const Parse::TreeAndSubtrees& {
  685. return this->GetParseTreeAndSubtrees();
  686. };
  687. sem_ir_.emplace(&*parse_tree_, check_ir_id_, parse_tree_->packaging_decl(),
  688. value_stores_, input_filename_);
  689. if (!llvm_context_) {
  690. llvm_context_ = std::make_unique<llvm::LLVMContext>();
  691. }
  692. return {.consumer = consumer_,
  693. .value_stores = &value_stores_,
  694. .timings = timings_ ? &*timings_ : nullptr,
  695. .sem_ir = &*sem_ir_,
  696. .llvm_context = llvm_context_.get(),
  697. .total_ir_count = total_ir_count_};
  698. }
  699. auto CompilationUnit::PostCheck() -> void {
  700. CARBON_CHECK(sem_ir_, "Must call GetCheckUnit first");
  701. // We've finished all steps that can produce diagnostics. Emit the
  702. // diagnostics now, so that the developer sees them sooner and doesn't need
  703. // to wait for code generation.
  704. consumer_->Flush();
  705. if (mem_usage_) {
  706. mem_usage_->Collect("sem_ir_", *sem_ir_);
  707. }
  708. if (sem_ir_->has_errors()) {
  709. success_ = false;
  710. }
  711. }
  712. auto CompilationUnit::RunLower() -> void {
  713. LogCall("Lower::LowerToLLVM", "lower", [&] {
  714. if (!llvm_context_) {
  715. llvm_context_ = std::make_unique<llvm::LLVMContext>();
  716. }
  717. Lower::LowerToLLVMOptions options;
  718. options.llvm_verifier_stream =
  719. options_->run_llvm_verifier ? driver_env_->error_stream : nullptr;
  720. options.want_debug_info = options_->include_debug_info;
  721. options.vlog_stream = vlog_stream_;
  722. options.opt_level = options_->opt_level;
  723. module_ = Lower::LowerToLLVM(*llvm_context_, driver_env_->fs,
  724. cache_->tree_and_subtrees_getters(), *sem_ir_,
  725. total_ir_count_, options);
  726. });
  727. }
  728. auto CompilationUnit::MakeTargetMachine(
  729. const clang::CompilerInvocation& clang_invocation) -> void {
  730. CARBON_CHECK(module_, "Must call RunLower first");
  731. CARBON_CHECK(!target_machine_, "Should not call this multiple times");
  732. // Set the target on the module.
  733. // TODO: We should do this earlier. Lower should be passed the target triple
  734. // so it can create the module with this already set.
  735. llvm::Triple target_triple(options_->codegen_options.target);
  736. module_->setTargetTriple(target_triple);
  737. // TODO: Provide flags to control these.
  738. constexpr llvm::StringLiteral CPU = "generic";
  739. constexpr llvm::StringLiteral Features = "";
  740. const auto& codegen_opts = clang_invocation.getCodeGenOpts();
  741. // TODO: Make the code in Clang's BackendUtil.cpp externally accessible and
  742. // call it from here. This is doing a subset of the same work to translate
  743. // Clang code generation options into target options.
  744. llvm::TargetOptions target_opts;
  745. target_opts.UseInitArray = codegen_opts.UseInitArray;
  746. target_opts.FunctionSections = codegen_opts.FunctionSections;
  747. target_opts.DataSections = codegen_opts.DataSections;
  748. target_opts.UniqueSectionNames = codegen_opts.UniqueSectionNames;
  749. target_machine_.reset(target_->createTargetMachine(
  750. target_triple, CPU, Features, target_opts, llvm::Reloc::PIC_));
  751. }
  752. // Get the LLVM optimization level corresponding to a Carbon optimization level.
  753. static auto GetLLVMOptimizationLevel(Lower::OptimizationLevel opt_level)
  754. -> llvm::OptimizationLevel {
  755. switch (opt_level) {
  756. case Lower::OptimizationLevel::None:
  757. return llvm::OptimizationLevel::O0;
  758. case Lower::OptimizationLevel::Debug:
  759. return llvm::OptimizationLevel::O1;
  760. case Lower::OptimizationLevel::Size:
  761. return llvm::OptimizationLevel::Oz;
  762. case Lower::OptimizationLevel::Speed:
  763. return llvm::OptimizationLevel::O3;
  764. }
  765. }
  766. // Get the `-O` flag corresponding to an optimization level.
  767. static auto GetClangOptimizationFlag(Lower::OptimizationLevel opt_level)
  768. -> llvm::StringLiteral {
  769. switch (opt_level) {
  770. case Lower::OptimizationLevel::None:
  771. return "-O0";
  772. case Lower::OptimizationLevel::Debug:
  773. return "-O1";
  774. case Lower::OptimizationLevel::Size:
  775. return "-Oz";
  776. case Lower::OptimizationLevel::Speed:
  777. return "-O3";
  778. }
  779. }
  780. auto CompilationUnit::RunOptimize(
  781. const clang::CompilerInvocation& clang_invocation) -> void {
  782. CARBON_CHECK(module_, "Must call RunLower first");
  783. // TODO: A lot of the work done here duplicates work done by Clang setting up
  784. // its pass manager. Moreover, we probably want to pick up Clang's
  785. // customizations and make use of its flags for controlling LLVM passes. We
  786. // should consider whether we would be better off running Clang's pass
  787. // pipeline rather than building one of our own, or factoring out enough of
  788. // Clang's pipeline builder that we can reuse and further customize it.
  789. MakeTargetMachine(clang_invocation);
  790. // TODO: There's no way to set these automatically from an
  791. // llvm::OptimizationLevel. Add such a mechanism to LLVM and use it from
  792. // here. For now we reconstruct what Clang does by default.
  793. llvm::PipelineTuningOptions pto;
  794. bool opt_for_speed = options_->opt_level == Lower::OptimizationLevel::Speed;
  795. bool opt_for_size_or_speed =
  796. opt_for_speed || options_->opt_level == Lower::OptimizationLevel::Size;
  797. // Loop unrolling is enabled by `--optimize=size` but isn't actually performed
  798. // because we add `optsize` attributes to the function definitions we emit.
  799. pto.LoopUnrolling = opt_for_size_or_speed;
  800. pto.LoopInterleaving = opt_for_size_or_speed;
  801. pto.LoopVectorization = opt_for_speed;
  802. pto.SLPVectorization = opt_for_size_or_speed;
  803. llvm::LoopAnalysisManager lam;
  804. llvm::FunctionAnalysisManager fam;
  805. llvm::CGSCCAnalysisManager cgam;
  806. llvm::ModuleAnalysisManager mam;
  807. llvm::PassInstrumentationCallbacks pic;
  808. // Register standard pass instrumentations. This adds support for things like
  809. // `-print-after-all`.
  810. llvm::StandardInstrumentations si(module_->getContext(),
  811. /*DebugLogging=*/false);
  812. si.registerCallbacks(pic);
  813. llvm::PassBuilder builder(target_machine_.get(), pto,
  814. /*PGOOpt=*/std::nullopt, &pic);
  815. // TODO: Add an AssignmentTrackingPass for at least `--optimize=debug`.
  816. // Set up target library information and add an analysis pass to supply it.
  817. std::unique_ptr<llvm::TargetLibraryInfoImpl> tlii(llvm::driver::createTLII(
  818. module_->getTargetTriple(), llvm::driver::VectorLibrary::NoLibrary));
  819. fam.registerPass([&] { return llvm::TargetLibraryAnalysis(*tlii); });
  820. builder.registerModuleAnalyses(mam);
  821. builder.registerCGSCCAnalyses(cgam);
  822. builder.registerFunctionAnalyses(fam);
  823. builder.registerLoopAnalyses(lam);
  824. builder.crossRegisterProxies(lam, fam, cgam, mam);
  825. llvm::ModulePassManager pass_manager = builder.buildPerModuleDefaultPipeline(
  826. GetLLVMOptimizationLevel(options_->opt_level));
  827. if (vlog_stream_) {
  828. CARBON_VLOG("*** Running pass pipeline: ");
  829. pass_manager.printPipeline(
  830. *vlog_stream_, [&pic](llvm::StringRef class_name) {
  831. auto pass_name = pic.getPassNameForClassName(class_name);
  832. return pass_name.empty() ? class_name : pass_name;
  833. });
  834. CARBON_VLOG(" ***\n");
  835. }
  836. LogCall("ModulePassManager::run", "optimize",
  837. [&] { pass_manager.run(*module_, mam); });
  838. if (vlog_stream_) {
  839. CARBON_VLOG("*** Optimized llvm::Module ***\n");
  840. module_->print(*vlog_stream_, /*AAW=*/nullptr,
  841. /*ShouldPreserveUseListOrder=*/false,
  842. /*IsForDebug=*/true);
  843. }
  844. }
  845. auto CompilationUnit::PostLower() -> void {
  846. CARBON_CHECK(module_, "Must call RunLower first");
  847. if (options_->dump_llvm_ir && IncludeInDumps()) {
  848. module_->print(*driver_env_->output_stream, /*AAW=*/nullptr,
  849. /*ShouldPreserveUseListOrder=*/true);
  850. }
  851. }
  852. auto CompilationUnit::RunCodeGen() -> void {
  853. CARBON_CHECK(module_, "Must call RunLower first");
  854. LogCall("CodeGen", "codegen", [&] { success_ = RunCodeGenHelper(); });
  855. }
  856. auto CompilationUnit::PostCompile() -> void {
  857. if (options_->dump_shared_values && IncludeInDumps()) {
  858. Yaml::Print(*driver_env_->output_stream,
  859. value_stores_.OutputYaml(input_filename_));
  860. }
  861. if (mem_usage_) {
  862. mem_usage_->Collect("value_stores_", value_stores_);
  863. Yaml::Print(*driver_env_->output_stream,
  864. mem_usage_->OutputYaml(input_filename_));
  865. }
  866. if (timings_) {
  867. Yaml::Print(*driver_env_->output_stream,
  868. timings_->OutputYaml(input_filename_));
  869. }
  870. // The diagnostics consumer must be flushed before compilation artifacts are
  871. // destructed, because diagnostics can refer to their state.
  872. consumer_->Flush();
  873. }
  874. auto CompilationUnit::RunCodeGenHelper() -> bool {
  875. CARBON_CHECK(module_, "Must call RunLower first");
  876. CARBON_CHECK(target_machine_, "Must call MakeTargetMachine first");
  877. CodeGen codegen(module_.get(), target_machine_.get(), consumer_);
  878. if (vlog_stream_) {
  879. CARBON_VLOG("*** Assembly ***\n");
  880. codegen.EmitAssembly(*vlog_stream_);
  881. }
  882. if (options_->output_filename == "-") {
  883. // TODO: The output file name, forcing object output, and requesting
  884. // textual assembly output are all somewhat linked flags. We should add
  885. // some validation that they are used correctly.
  886. if (options_->force_obj_output) {
  887. if (!codegen.EmitObject(*driver_env_->output_stream)) {
  888. return false;
  889. }
  890. } else {
  891. if (!codegen.EmitAssembly(*driver_env_->output_stream)) {
  892. return false;
  893. }
  894. }
  895. } else {
  896. llvm::SmallString<256> output_filename = options_->output_filename;
  897. if (output_filename.empty()) {
  898. if (!source_->is_regular_file()) {
  899. // Don't invent file names like `-.o` or `/dev/stdin.o`.
  900. // TODO: Consider rephrasing the diagnostic to use the file as the
  901. // `Emit` location.
  902. CARBON_DIAGNOSTIC(CompileInputNotRegularFile, Error,
  903. "output file name must be specified for input `{0}` "
  904. "that is not a regular file",
  905. std::string);
  906. driver_env_->emitter.Emit(CompileInputNotRegularFile, input_filename_);
  907. return false;
  908. }
  909. output_filename = input_filename_;
  910. llvm::sys::path::replace_extension(output_filename,
  911. options_->asm_output ? ".s" : ".o");
  912. } else {
  913. // TODO: Handle the case where multiple input files were specified
  914. // along with an output file name. That should either be an error or
  915. // should produce a single LLVM IR module containing all inputs.
  916. // Currently each unit overwrites the output from the previous one in
  917. // this case.
  918. }
  919. CARBON_VLOG("Writing output to: {0}\n", output_filename);
  920. std::error_code ec;
  921. llvm::raw_fd_ostream output_file(output_filename, ec,
  922. llvm::sys::fs::OF_None);
  923. if (ec) {
  924. // TODO: Consider rephrasing the diagnostic to use the file as the `Emit`
  925. // location.
  926. CARBON_DIAGNOSTIC(CompileOutputFileOpenError, Error,
  927. "could not open output file `{0}`: {1}", std::string,
  928. std::string);
  929. driver_env_->emitter.Emit(CompileOutputFileOpenError,
  930. output_filename.str().str(), ec.message());
  931. return false;
  932. }
  933. if (options_->asm_output) {
  934. if (!codegen.EmitAssembly(output_file)) {
  935. return false;
  936. }
  937. } else {
  938. if (!codegen.EmitObject(output_file)) {
  939. return false;
  940. }
  941. }
  942. }
  943. return true;
  944. }
  945. auto CompilationUnit::GetParseTreeAndSubtrees()
  946. -> const Parse::TreeAndSubtrees& {
  947. if (!parse_tree_and_subtrees_) {
  948. parse_tree_and_subtrees_ = Parse::TreeAndSubtrees(*tokens_, *parse_tree_);
  949. if (mem_usage_) {
  950. mem_usage_->Collect("parse_tree_and_subtrees_",
  951. *parse_tree_and_subtrees_);
  952. }
  953. }
  954. return *parse_tree_and_subtrees_;
  955. }
  956. auto CompilationUnit::LogCall(llvm::StringLiteral logging_label,
  957. llvm::StringLiteral timing_label,
  958. llvm::function_ref<auto()->void> fn) -> void {
  959. PrettyStackTraceFunction trace_file([&](llvm::raw_ostream& out) {
  960. out << "Filename: " << input_filename_ << "\n";
  961. });
  962. CARBON_VLOG("*** {0}: {1} ***\n", logging_label, input_filename_);
  963. Timings::ScopedTiming timing(timings_ ? &*timings_ : nullptr, timing_label);
  964. fn();
  965. CARBON_VLOG("*** {0} done ***\n", logging_label);
  966. }
  967. auto CompileSubcommand::Run(DriverEnv& driver_env) -> DriverResult {
  968. if (!ValidateOptions(driver_env.emitter)) {
  969. return {.success = false};
  970. }
  971. // Validate the target before passing it to Clang.
  972. std::string target_error;
  973. const llvm::Target* target = llvm::TargetRegistry::lookupTarget(
  974. llvm::Triple(options_.codegen_options.target), target_error);
  975. if (!target) {
  976. CARBON_DIAGNOSTIC(CompileTargetInvalid, Error, "invalid target: {0}",
  977. std::string);
  978. driver_env.emitter.Emit(CompileTargetInvalid, target_error);
  979. return {.success = false};
  980. }
  981. std::shared_ptr<clang::CompilerInvocation> clang_invocation;
  982. // Build a clang invocation. We do this regardless of whether we're running
  983. // check, because this is essentially performing further option validation,
  984. // and we generally validate all options even if we're not using them for the
  985. // selected phases of compilation. We also use Clang's target option handling
  986. // to configure our target, to ensure that we are using the same ABI for both
  987. // the C++ and Carbon parts of the compilation.
  988. // TODO: Share any arguments we specify here with the `carbon clang`
  989. // subcommand.
  990. {
  991. if (driver_env.fuzzing && !options_.clang_args.empty()) {
  992. // Parsing specific Clang arguments can reach deep into
  993. // external libraries that aren't fuzz clean.
  994. TestAndDiagnoseIfFuzzingExternalLibraries(driver_env, "compile");
  995. return {.success = false};
  996. }
  997. // TODO: Move this into `BuildClangInvocation` when it can accept an
  998. // optimization level.
  999. llvm::SmallVector<llvm::StringRef> clang_args = {
  1000. // Propagate our optimization level to Clang as a default. This can be
  1001. // overridden by Clang arguments, but doing so will only have an effect
  1002. // if those arguments affect Clang's IR, not its pass pipeline.
  1003. GetClangOptimizationFlag(options_.opt_level),
  1004. };
  1005. clang_args.append(options_.clang_args);
  1006. clang_invocation = BuildClangInvocation(
  1007. driver_env.consumer, driver_env.fs, *driver_env.installation,
  1008. options_.codegen_options.target, clang_args);
  1009. if (!clang_invocation) {
  1010. return {.success = false};
  1011. }
  1012. // We will run our own pass pipeline over the IR in the `Optimize` phase, so
  1013. // disable Clang's pipeline to avoid optimizing C++ code twice.
  1014. clang_invocation->getCodeGenOpts().DisableLLVMPasses = true;
  1015. }
  1016. // Find the files comprising the prelude if we are importing it.
  1017. // TODO: Replace this with a search for library api files in a
  1018. // package-specific search path based on the library name.
  1019. llvm::SmallVector<std::string> prelude;
  1020. if (options_.prelude_import && !options_.custom_core &&
  1021. options_.phase >= CompileOptions::Phase::Check) {
  1022. if (auto find = driver_env.installation->ReadPreludeManifest(); find.ok()) {
  1023. prelude = std::move(*find);
  1024. } else {
  1025. // TODO: Change ReadPreludeManifest to produce diagnostics.
  1026. CARBON_DIAGNOSTIC(CompilePreludeManifestError, Error, "{0}", std::string);
  1027. driver_env.emitter.Emit(CompilePreludeManifestError,
  1028. PrintToString(find.error()));
  1029. return {.success = false};
  1030. }
  1031. }
  1032. // Prepare CompilationUnits before building scope exit handlers.
  1033. llvm::SmallVector<std::unique_ptr<CompilationUnit>> units;
  1034. int total_unit_count = prelude.size() + options_.input_filenames.size();
  1035. int unit_index = -1;
  1036. auto unit_builder = [&](llvm::StringRef filename) {
  1037. ++unit_index;
  1038. return std::make_unique<CompilationUnit>(
  1039. SemIR::CheckIRId(unit_index), total_unit_count, &driver_env, &options_,
  1040. &driver_env.consumer, filename, target);
  1041. };
  1042. llvm::append_range(units, llvm::map_range(prelude, unit_builder));
  1043. llvm::append_range(units,
  1044. llvm::map_range(options_.input_filenames, unit_builder));
  1045. CARBON_CHECK(units.size() == static_cast<size_t>(total_unit_count));
  1046. // Add the cache to all units. This must be done after all units are created.
  1047. MultiUnitCache cache(&options_, units);
  1048. for (auto& unit : units) {
  1049. unit->SetMultiUnitCache(&cache);
  1050. }
  1051. auto on_exit = llvm::scope_exit([&]() {
  1052. // Finish compilation units. This flushes their diagnostics in the order in
  1053. // which they were specified on the command line.
  1054. for (auto& unit : units) {
  1055. unit->PostCompile();
  1056. }
  1057. driver_env.consumer.Flush();
  1058. });
  1059. PrettyStackTraceFunction flush_on_crash([&](llvm::raw_ostream& out) {
  1060. // When crashing, flush diagnostics. If sorting diagnostics, they can be
  1061. // redirected to the crash stream; if streaming, the original stream is
  1062. // flushed.
  1063. // TODO: Eventually we'll want to limit the count.
  1064. if (options_.stream_errors) {
  1065. out << "Flushing diagnostics\n";
  1066. } else {
  1067. out << "Pending diagnostics:\n";
  1068. driver_env.consumer.set_stream(&out);
  1069. }
  1070. for (auto& unit : units) {
  1071. unit->FlushForStackTrace();
  1072. }
  1073. driver_env.consumer.Flush();
  1074. driver_env.consumer.set_stream(driver_env.error_stream);
  1075. });
  1076. // Returns a DriverResult object. Called whenever Compile returns.
  1077. auto make_result = [&]() {
  1078. DriverResult result = {.success = true};
  1079. for (const auto& unit : units) {
  1080. result.success &= unit->success();
  1081. result.per_file_success.push_back(
  1082. {unit->input_filename().str(), unit->success()});
  1083. }
  1084. return result;
  1085. };
  1086. // Lex.
  1087. for (auto& unit : units) {
  1088. unit->RunLex();
  1089. }
  1090. if (options_.phase == CompileOptions::Phase::Lex) {
  1091. return make_result();
  1092. }
  1093. cache.ApplyPerFileIncludeInDumps();
  1094. // Parse and check phases examine `has_source` because they want to proceed if
  1095. // lex failed, but not if source doesn't exist. Later steps are skipped if
  1096. // anything failed, so don't need this.
  1097. // Parse.
  1098. for (auto& unit : units) {
  1099. if (unit->has_source()) {
  1100. unit->RunParse();
  1101. }
  1102. }
  1103. if (options_.phase == CompileOptions::Phase::Parse) {
  1104. return make_result();
  1105. }
  1106. // Gather Check::Units.
  1107. llvm::SmallVector<Check::Unit> check_units;
  1108. check_units.reserve(units.size());
  1109. for (auto& unit : units) {
  1110. if (unit->has_source()) {
  1111. check_units.push_back(unit->GetCheckUnit());
  1112. }
  1113. }
  1114. // Execute the actual checking.
  1115. CARBON_VLOG_TO(driver_env.vlog_stream, "*** Check::CheckParseTrees ***\n");
  1116. Check::CheckParseTreesOptions options;
  1117. options.prelude_import = options_.prelude_import;
  1118. options.vlog_stream = driver_env.vlog_stream;
  1119. options.fuzzing = driver_env.fuzzing;
  1120. if (options.vlog_stream || options_.dump_sem_ir || options_.dump_cpp_ast ||
  1121. options_.dump_raw_sem_ir) {
  1122. options.include_in_dumps = &cache.include_in_dumps();
  1123. if (options_.dump_sem_ir) {
  1124. options.dump_stream = driver_env.output_stream;
  1125. }
  1126. if (options_.dump_cpp_ast) {
  1127. options.dump_cpp_ast_stream = driver_env.output_stream;
  1128. }
  1129. if (options.vlog_stream || options_.dump_sem_ir) {
  1130. options.dump_sem_ir_ranges = options_.dump_sem_ir_ranges;
  1131. }
  1132. if (options_.dump_raw_sem_ir) {
  1133. options.raw_dump_stream = driver_env.output_stream;
  1134. options.dump_raw_sem_ir_builtins = options_.builtin_sem_ir;
  1135. }
  1136. options.sem_ir_crash_dump = options_.sem_ir_crash_dump;
  1137. }
  1138. Check::CheckParseTrees(check_units, cache.tree_and_subtrees_getters(),
  1139. driver_env.fs, options, clang_invocation);
  1140. CARBON_VLOG_TO(driver_env.vlog_stream,
  1141. "*** Check::CheckParseTrees done ***\n");
  1142. for (auto& unit : units) {
  1143. if (unit->has_source()) {
  1144. unit->PostCheck();
  1145. }
  1146. }
  1147. if (options_.phase == CompileOptions::Phase::Check) {
  1148. return make_result();
  1149. }
  1150. // Unlike previous steps, errors block further progress.
  1151. if (llvm::any_of(units, [&](const auto& unit) { return !unit->success(); })) {
  1152. CARBON_VLOG_TO(driver_env.vlog_stream,
  1153. "*** Stopping before lowering due to errors ***\n");
  1154. return make_result();
  1155. }
  1156. // Lower and optimize.
  1157. for (const auto& unit : units) {
  1158. unit->RunLower();
  1159. if (options_.phase != CompileOptions::Phase::Lower) {
  1160. unit->RunOptimize(*clang_invocation);
  1161. }
  1162. unit->PostLower();
  1163. }
  1164. if (options_.phase == CompileOptions::Phase::Lower ||
  1165. options_.phase == CompileOptions::Phase::Optimize) {
  1166. return make_result();
  1167. }
  1168. CARBON_CHECK(options_.phase == CompileOptions::Phase::CodeGen,
  1169. "CodeGen should be the last stage");
  1170. // Codegen.
  1171. for (auto& unit : units) {
  1172. unit->RunCodeGen();
  1173. }
  1174. return make_result();
  1175. }
  1176. } // namespace Carbon