1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use back::bytecode::{self, RLIB_BYTECODE_EXTENSION};
13 use back::lto::{self, ThinBuffer, SerializedModule};
14 use back::link::{self, get_linker, remove};
18 use rustc_incremental::{copy_cgu_workproducts_to_incr_comp_cache_dir,
19 in_incr_comp_dir, in_incr_comp_dir_sess};
20 use rustc::dep_graph::{WorkProduct, WorkProductId, WorkProductFileKind};
21 use rustc::dep_graph::cgu_reuse_tracker::CguReuseTracker;
22 use rustc::middle::cstore::EncodedMetadata;
23 use rustc::session::config::{self, OutputFilenames, OutputType, Passes, Sanitizer, Lto};
24 use rustc::session::Session;
25 use rustc::util::nodemap::FxHashMap;
26 use time_graph::{self, TimeGraph, Timeline};
27 use llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
29 use {CodegenResults, ModuleCodegen, CompiledModule, ModuleKind, // ModuleLlvm,
32 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
33 use rustc::ty::TyCtxt;
34 use rustc::util::common::{time_ext, time_depth, set_time_depth, print_time_passes_entry};
35 use rustc_fs_util::{path2cstr, link_or_copy};
36 use rustc_data_structures::small_c_str::SmallCStr;
37 use rustc_data_structures::svh::Svh;
38 use rustc_codegen_utils::command::Command;
39 use rustc_codegen_utils::linker::LinkerInfo;
40 use rustc_codegen_utils::symbol_export::ExportedSymbols;
41 use errors::{self, Handler, Level, DiagnosticBuilder, FatalError, DiagnosticId};
42 use errors::emitter::{Emitter};
44 use syntax::ext::hygiene::Mark;
45 use syntax_pos::MultiSpan;
46 use syntax_pos::symbol::Symbol;
48 use context::{is_pie_binary, get_reloc_model};
49 use common::{C_bytes_in_context, val_ty};
50 use jobserver::{Client, Acquired};
54 use std::ffi::{CString, CStr};
56 use std::io::{self, Write};
58 use std::path::{Path, PathBuf};
61 use std::sync::mpsc::{channel, Sender, Receiver};
63 use std::time::Instant;
65 use libc::{c_uint, c_void, c_char, size_t};
67 pub const RELOC_MODEL_ARGS : [(&'static str, llvm::RelocMode); 7] = [
68 ("pic", llvm::RelocMode::PIC),
69 ("static", llvm::RelocMode::Static),
70 ("default", llvm::RelocMode::Default),
71 ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
72 ("ropi", llvm::RelocMode::ROPI),
73 ("rwpi", llvm::RelocMode::RWPI),
74 ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
77 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
78 ("small", llvm::CodeModel::Small),
79 ("kernel", llvm::CodeModel::Kernel),
80 ("medium", llvm::CodeModel::Medium),
81 ("large", llvm::CodeModel::Large),
84 pub const TLS_MODEL_ARGS : [(&'static str, llvm::ThreadLocalMode); 4] = [
85 ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
86 ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
87 ("initial-exec", llvm::ThreadLocalMode::InitialExec),
88 ("local-exec", llvm::ThreadLocalMode::LocalExec),
91 const PRE_THIN_LTO_BC_EXT: &str = "pre-thin-lto.bc";
93 pub fn llvm_err(handler: &errors::Handler, msg: String) -> FatalError {
94 match llvm::last_error() {
95 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
96 None => handler.fatal(&msg),
100 pub fn write_output_file(
101 handler: &errors::Handler,
102 target: &'ll llvm::TargetMachine,
103 pm: &llvm::PassManager<'ll>,
104 m: &'ll llvm::Module,
106 file_type: llvm::FileType) -> Result<(), FatalError> {
108 let output_c = path2cstr(output);
109 let result = llvm::LLVMRustWriteOutputFile(
110 target, pm, m, output_c.as_ptr(), file_type);
111 if result.into_result().is_err() {
112 let msg = format!("could not write output to {}", output.display());
113 Err(llvm_err(handler, msg))
120 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
122 config::OptLevel::No => llvm::CodeGenOptLevel::None,
123 config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
124 config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
125 config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
126 _ => llvm::CodeGenOptLevel::Default,
130 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
132 config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
133 config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
134 _ => llvm::CodeGenOptSizeNone,
138 pub fn create_target_machine(
141 ) -> &'static mut llvm::TargetMachine {
142 target_machine_factory(sess, find_features)().unwrap_or_else(|err| {
143 llvm_err(sess.diagnostic(), err).raise()
147 // If find_features is true this won't access `sess.crate_types` by assuming
148 // that `is_pie_binary` is false. When we discover LLVM target features
149 // `sess.crate_types` is uninitialized so we cannot access it.
150 pub fn target_machine_factory(sess: &Session, find_features: bool)
151 -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>
153 let reloc_model = get_reloc_model(sess);
155 let opt_level = get_llvm_opt_level(sess.opts.optimize);
156 let use_softfp = sess.opts.cg.soft_float;
158 let ffunction_sections = sess.target.target.options.function_sections;
159 let fdata_sections = ffunction_sections;
161 let code_model_arg = sess.opts.cg.code_model.as_ref().or(
162 sess.target.target.options.code_model.as_ref(),
165 let code_model = match code_model_arg {
167 match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
170 sess.err(&format!("{:?} is not a valid code model",
172 sess.abort_if_errors();
177 None => llvm::CodeModel::None,
180 let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
181 let mut singlethread = sess.target.target.options.singlethread;
183 // On the wasm target once the `atomics` feature is enabled that means that
184 // we're no longer single-threaded, or otherwise we don't want LLVM to
185 // lower atomic operations to single-threaded operations.
187 sess.target.target.llvm_target.contains("wasm32") &&
188 features.iter().any(|s| *s == "+atomics")
190 singlethread = false;
193 let triple = SmallCStr::new(&sess.target.target.llvm_target);
194 let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
195 let features = features.join(",");
196 let features = CString::new(features).unwrap();
197 let is_pie_binary = !find_features && is_pie_binary(sess);
198 let trap_unreachable = sess.target.target.options.trap_unreachable;
199 let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
201 let asm_comments = sess.asm_comments();
205 llvm::LLVMRustCreateTargetMachine(
206 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
217 emit_stack_size_section,
222 format!("Could not create LLVM TargetMachine for triple: {}",
223 triple.to_str().unwrap())
228 /// Module-specific configuration for `optimize_and_codegen`.
229 pub struct ModuleConfig {
230 /// Names of additional optimization passes to run.
232 /// Some(level) to optimize at a certain level, or None to run
233 /// absolutely no optimizations (used for the metadata module).
234 pub opt_level: Option<llvm::CodeGenOptLevel>,
236 /// Some(level) to optimize binary size, or None to not affect program size.
237 opt_size: Option<llvm::CodeGenOptSize>,
239 pgo_gen: Option<String>,
242 // Flags indicating which outputs to produce.
243 pub emit_pre_thin_lto_bc: bool,
244 emit_no_opt_bc: bool,
246 emit_bc_compressed: bool,
251 // Miscellaneous flags. These are mostly copied from command-line
253 pub verify_llvm_ir: bool,
254 no_prepopulate_passes: bool,
257 vectorize_loop: bool,
259 merge_functions: bool,
260 inline_threshold: Option<usize>,
261 // Instead of creating an object file by doing LLVM codegen, just
262 // make the object file bitcode. Provides easy compatibility with
263 // emscripten's ecc compiler, when used as the linker.
264 obj_is_bitcode: bool,
265 no_integrated_as: bool,
267 embed_bitcode_marker: bool,
271 fn new(passes: Vec<String>) -> ModuleConfig {
278 pgo_use: String::new(),
280 emit_no_opt_bc: false,
281 emit_pre_thin_lto_bc: false,
283 emit_bc_compressed: false,
288 obj_is_bitcode: false,
289 embed_bitcode: false,
290 embed_bitcode_marker: false,
291 no_integrated_as: false,
293 verify_llvm_ir: false,
294 no_prepopulate_passes: false,
297 vectorize_loop: false,
298 vectorize_slp: false,
299 merge_functions: false,
300 inline_threshold: None
304 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
305 self.verify_llvm_ir = sess.verify_llvm_ir();
306 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
307 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
308 self.time_passes = sess.time_passes();
309 self.inline_threshold = sess.opts.cg.inline_threshold;
310 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
311 sess.opts.debugging_opts.cross_lang_lto.enabled();
312 let embed_bitcode = sess.target.target.options.embed_bitcode ||
313 sess.opts.debugging_opts.embed_bitcode;
315 match sess.opts.optimize {
316 config::OptLevel::No |
317 config::OptLevel::Less => {
318 self.embed_bitcode_marker = embed_bitcode;
320 _ => self.embed_bitcode = embed_bitcode,
324 // Copy what clang does by turning on loop vectorization at O2 and
325 // slp vectorization at O3. Otherwise configure other optimization aspects
326 // of this pass manager builder.
327 // Turn off vectorization for emscripten, as it's not very well supported.
328 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
329 (sess.opts.optimize == config::OptLevel::Default ||
330 sess.opts.optimize == config::OptLevel::Aggressive) &&
331 !sess.target.target.options.is_like_emscripten;
333 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
334 sess.opts.optimize == config::OptLevel::Aggressive &&
335 !sess.target.target.options.is_like_emscripten;
337 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
338 sess.opts.optimize == config::OptLevel::Aggressive;
341 pub fn bitcode_needed(&self) -> bool {
342 self.emit_bc || self.obj_is_bitcode
343 || self.emit_bc_compressed || self.embed_bitcode
347 /// Assembler name and command used by codegen when no_integrated_as is enabled
348 struct AssemblerCommand {
353 /// Additional resources used by optimize_and_codegen (not module specific)
355 pub struct CodegenContext {
356 // Resources needed when running LTO
357 pub time_passes: bool,
359 pub no_landing_pads: bool,
360 pub save_temps: bool,
361 pub fewer_names: bool,
362 pub exported_symbols: Option<Arc<ExportedSymbols>>,
363 pub opts: Arc<config::Options>,
364 pub crate_types: Vec<config::CrateType>,
365 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
366 output_filenames: Arc<OutputFilenames>,
367 regular_module_config: Arc<ModuleConfig>,
368 metadata_module_config: Arc<ModuleConfig>,
369 allocator_module_config: Arc<ModuleConfig>,
370 pub tm_factory: Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>,
371 pub msvc_imps_needed: bool,
372 pub target_pointer_width: String,
373 debuginfo: config::DebugInfo,
375 // Number of cgus excluding the allocator/metadata modules
376 pub total_cgus: usize,
377 // Handler to use for diagnostics produced during codegen.
378 pub diag_emitter: SharedEmitter,
379 // LLVM passes added by plugins.
380 pub plugin_passes: Vec<String>,
381 // LLVM optimizations for which we want to print remarks.
383 // Worker thread number
385 // The incremental compilation session directory, or None if we are not
386 // compiling incrementally
387 pub incr_comp_session_dir: Option<PathBuf>,
388 // Used to update CGU re-use information during the thinlto phase.
389 pub cgu_reuse_tracker: CguReuseTracker,
390 // Channel back to the main control thread to send messages to
391 coordinator_send: Sender<Box<dyn Any + Send>>,
392 // A reference to the TimeGraph so we can register timings. None means that
393 // measuring is disabled.
394 time_graph: Option<TimeGraph>,
395 // The assembler command if no_integrated_as option is enabled, None otherwise
396 assembler_cmd: Option<Arc<AssemblerCommand>>,
399 impl CodegenContext {
400 pub fn create_diag_handler(&self) -> Handler {
401 Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
404 pub(crate) fn config(&self, kind: ModuleKind) -> &ModuleConfig {
406 ModuleKind::Regular => &self.regular_module_config,
407 ModuleKind::Metadata => &self.metadata_module_config,
408 ModuleKind::Allocator => &self.allocator_module_config,
412 pub(crate) fn save_temp_bitcode(&self, module: &ModuleCodegen, name: &str) {
413 if !self.save_temps {
417 let ext = format!("{}.bc", name);
418 let cgu = Some(&module.name[..]);
419 let path = self.output_filenames.temp_path_ext(&ext, cgu);
420 let cstr = path2cstr(&path);
421 let llmod = module.module_llvm.llmod();
422 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
427 pub struct DiagnosticHandlers<'a> {
428 data: *mut (&'a CodegenContext, &'a Handler),
429 llcx: &'a llvm::Context,
432 impl<'a> DiagnosticHandlers<'a> {
433 pub fn new(cgcx: &'a CodegenContext,
434 handler: &'a Handler,
435 llcx: &'a llvm::Context) -> Self {
436 let data = Box::into_raw(Box::new((cgcx, handler)));
438 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
439 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
441 DiagnosticHandlers { data, llcx }
445 impl<'a> Drop for DiagnosticHandlers<'a> {
447 use std::ptr::null_mut;
449 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
450 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
451 drop(Box::from_raw(self.data));
456 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
459 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_string());
462 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
468 let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
470 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
471 .expect("non-UTF8 SMDiagnostic");
473 report_inline_asm(cgcx, &msg, cookie);
476 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
480 let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
482 match llvm::diagnostic::Diagnostic::unpack(info) {
483 llvm::diagnostic::InlineAsm(inline) => {
484 report_inline_asm(cgcx,
485 &llvm::twine_to_string(inline.message),
489 llvm::diagnostic::Optimization(opt) => {
490 let enabled = match cgcx.remark {
492 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
496 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
505 llvm::diagnostic::PGO(diagnostic_ref) |
506 llvm::diagnostic::Linker(diagnostic_ref) => {
507 let msg = llvm::build_string(|s| {
508 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
509 }).expect("non-UTF8 diagnostic");
510 diag_handler.warn(&msg);
512 llvm::diagnostic::UnknownDiagnostic(..) => {},
516 // Unsafe due to LLVM calls.
517 unsafe fn optimize(cgcx: &CodegenContext,
518 diag_handler: &Handler,
519 module: &ModuleCodegen,
520 config: &ModuleConfig,
521 timeline: &mut Timeline)
522 -> Result<(), FatalError>
524 let llmod = module.module_llvm.llmod();
525 let llcx = &*module.module_llvm.llcx;
526 let tm = &*module.module_llvm.tm;
527 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
529 let module_name = module.name.clone();
530 let module_name = Some(&module_name[..]);
532 if config.emit_no_opt_bc {
533 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
534 let out = path2cstr(&out);
535 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
538 if config.opt_level.is_some() {
539 // Create the two optimizing pass managers. These mirror what clang
540 // does, and are by populated by LLVM's default PassManagerBuilder.
541 // Each manager has a different set of passes, but they also share
542 // some common passes.
543 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
544 let mpm = llvm::LLVMCreatePassManager();
547 // If we're verifying or linting, add them to the function pass
549 let addpass = |pass_name: &str| {
550 let pass_name = SmallCStr::new(pass_name);
551 let pass = match llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr()) {
553 None => return false,
555 let pass_manager = match llvm::LLVMRustPassKind(pass) {
556 llvm::PassKind::Function => &*fpm,
557 llvm::PassKind::Module => &*mpm,
558 llvm::PassKind::Other => {
559 diag_handler.err("Encountered LLVM pass kind we can't handle");
563 llvm::LLVMRustAddPass(pass_manager, pass);
567 if config.verify_llvm_ir { assert!(addpass("verify")); }
569 // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
570 // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
571 // we'll get errors in LLVM.
572 let using_thin_buffers = config.bitcode_needed();
573 let mut have_name_anon_globals_pass = false;
574 if !config.no_prepopulate_passes {
575 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
576 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
577 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
578 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal ||
579 (cgcx.lto != Lto::Fat && cgcx.opts.debugging_opts.cross_lang_lto.enabled());
580 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
581 if using_thin_buffers && !prepare_for_thin_lto {
582 assert!(addpass("name-anon-globals"));
583 have_name_anon_globals_pass = true;
585 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
586 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
587 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
591 for pass in &config.passes {
593 diag_handler.warn(&format!("unknown pass `{}`, ignoring",
596 if pass == "name-anon-globals" {
597 have_name_anon_globals_pass = true;
601 for pass in &cgcx.plugin_passes {
603 diag_handler.err(&format!("a plugin asked for LLVM pass \
604 `{}` but LLVM does not \
605 recognize it", pass));
607 if pass == "name-anon-globals" {
608 have_name_anon_globals_pass = true;
612 if using_thin_buffers && !have_name_anon_globals_pass {
613 // As described above, this will probably cause an error in LLVM
614 if config.no_prepopulate_passes {
615 diag_handler.err("The current compilation is going to use thin LTO buffers \
616 without running LLVM's NameAnonGlobals pass. \
617 This will likely cause errors in LLVM. Consider adding \
618 -C passes=name-anon-globals to the compiler command line.");
620 bug!("We are using thin LTO buffers without running the NameAnonGlobals pass. \
621 This will likely cause errors in LLVM and should never happen.");
626 diag_handler.abort_if_errors();
628 // Finally, run the actual optimization passes
629 time_ext(config.time_passes,
631 &format!("llvm function passes [{}]", module_name.unwrap()),
633 llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
635 timeline.record("fpm");
636 time_ext(config.time_passes,
638 &format!("llvm module passes [{}]", module_name.unwrap()),
640 llvm::LLVMRunPassManager(mpm, llmod)
643 // Deallocate managers that we're now done with
644 llvm::LLVMDisposePassManager(fpm);
645 llvm::LLVMDisposePassManager(mpm);
650 fn generate_lto_work(cgcx: &CodegenContext,
651 modules: Vec<ModuleCodegen>,
652 import_only_modules: Vec<(SerializedModule, WorkProduct)>)
653 -> Vec<(WorkItem, u64)>
655 let mut timeline = cgcx.time_graph.as_ref().map(|tg| {
656 tg.start(CODEGEN_WORKER_TIMELINE,
657 CODEGEN_WORK_PACKAGE_KIND,
659 }).unwrap_or(Timeline::noop());
660 let (lto_modules, copy_jobs) = lto::run(cgcx, modules, import_only_modules, &mut timeline)
661 .unwrap_or_else(|e| e.raise());
663 let lto_modules = lto_modules.into_iter().map(|module| {
664 let cost = module.cost();
665 (WorkItem::LTO(module), cost)
668 let copy_jobs = copy_jobs.into_iter().map(|wp| {
669 (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
670 name: wp.cgu_name.clone(),
675 lto_modules.chain(copy_jobs).collect()
678 unsafe fn codegen(cgcx: &CodegenContext,
679 diag_handler: &Handler,
680 module: ModuleCodegen,
681 config: &ModuleConfig,
682 timeline: &mut Timeline)
683 -> Result<CompiledModule, FatalError>
685 timeline.record("codegen");
687 let llmod = module.module_llvm.llmod();
688 let llcx = &*module.module_llvm.llcx;
689 let tm = &*module.module_llvm.tm;
690 let module_name = module.name.clone();
691 let module_name = Some(&module_name[..]);
692 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
694 if cgcx.msvc_imps_needed {
695 create_msvc_imps(cgcx, llcx, llmod);
698 // A codegen-specific pass manager is used to generate object
699 // files for an LLVM module.
701 // Apparently each of these pass managers is a one-shot kind of
702 // thing, so we create a new one for each type of output. The
703 // pass manager passed to the closure should be ensured to not
704 // escape the closure itself, and the manager should only be
706 unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine,
707 llmod: &'ll llvm::Module,
710 where F: FnOnce(&'ll mut PassManager<'ll>) -> R,
712 let cpm = llvm::LLVMCreatePassManager();
713 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
714 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
718 // If we don't have the integrated assembler, then we need to emit asm
719 // from LLVM and use `gcc` to create the object file.
720 let asm_to_obj = config.emit_obj && config.no_integrated_as;
722 // Change what we write and cleanup based on whether obj files are
723 // just llvm bitcode. In that case write bitcode, and possibly
724 // delete the bitcode if it wasn't requested. Don't generate the
725 // machine code, instead copy the .o file from the .bc
726 let write_bc = config.emit_bc || config.obj_is_bitcode;
727 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
728 let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
729 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
731 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
732 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
735 if write_bc || config.emit_bc_compressed || config.embed_bitcode {
736 let thin = ThinBuffer::new(llmod);
737 let data = thin.data();
738 timeline.record("make-bc");
741 if let Err(e) = fs::write(&bc_out, data) {
742 diag_handler.err(&format!("failed to write bytecode: {}", e));
744 timeline.record("write-bc");
747 if config.embed_bitcode {
748 embed_bitcode(cgcx, llcx, llmod, Some(data));
749 timeline.record("embed-bc");
752 if config.emit_bc_compressed {
753 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
754 let data = bytecode::encode(&module.name, data);
755 if let Err(e) = fs::write(&dst, data) {
756 diag_handler.err(&format!("failed to write bytecode: {}", e));
758 timeline.record("compress-bc");
760 } else if config.embed_bitcode_marker {
761 embed_bitcode(cgcx, llcx, llmod, None);
764 time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
765 || -> Result<(), FatalError> {
767 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
768 let out = path2cstr(&out);
770 extern "C" fn demangle_callback(input_ptr: *const c_char,
772 output_ptr: *mut c_char,
773 output_len: size_t) -> size_t {
775 slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
778 let input = match str::from_utf8(input) {
783 let output = unsafe {
784 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
786 let mut cursor = io::Cursor::new(output);
788 let demangled = match rustc_demangle::try_demangle(input) {
793 if let Err(_) = write!(cursor, "{:#}", demangled) {
794 // Possible only if provided buffer is not big enough
798 cursor.position() as size_t
801 with_codegen(tm, llmod, config.no_builtins, |cpm| {
802 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
803 llvm::LLVMDisposePassManager(cpm);
805 timeline.record("ir");
808 if config.emit_asm || asm_to_obj {
809 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
811 // We can't use the same module for asm and binary output, because that triggers
812 // various errors like invalid IR or broken binaries, so we might have to clone the
813 // module to produce the asm output
814 let llmod = if config.emit_obj {
815 llvm::LLVMCloneModule(llmod)
819 with_codegen(tm, llmod, config.no_builtins, |cpm| {
820 write_output_file(diag_handler, tm, cpm, llmod, &path,
821 llvm::FileType::AssemblyFile)
823 timeline.record("asm");
827 with_codegen(tm, llmod, config.no_builtins, |cpm| {
828 write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
829 llvm::FileType::ObjectFile)
831 timeline.record("obj");
832 } else if asm_to_obj {
833 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
834 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
835 timeline.record("asm_to_obj");
837 if !config.emit_asm && !cgcx.save_temps {
838 drop(fs::remove_file(&assembly));
846 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
847 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
848 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
853 debug!("removing_bitcode {:?}", bc_out);
854 if let Err(e) = fs::remove_file(&bc_out) {
855 diag_handler.err(&format!("failed to remove bitcode: {}", e));
861 Ok(module.into_compiled_module(config.emit_obj,
863 config.emit_bc_compressed,
864 &cgcx.output_filenames))
867 /// Embed the bitcode of an LLVM module in the LLVM module itself.
869 /// This is done primarily for iOS where it appears to be standard to compile C
870 /// code at least with `-fembed-bitcode` which creates two sections in the
873 /// * __LLVM,__bitcode
874 /// * __LLVM,__cmdline
876 /// It appears *both* of these sections are necessary to get the linker to
877 /// recognize what's going on. For us though we just always throw in an empty
880 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
881 /// embed an empty section.
883 /// Basically all of this is us attempting to follow in the footsteps of clang
884 /// on iOS. See #35968 for lots more info.
885 unsafe fn embed_bitcode(cgcx: &CodegenContext,
886 llcx: &llvm::Context,
887 llmod: &llvm::Module,
888 bitcode: Option<&[u8]>) {
889 let llconst = C_bytes_in_context(llcx, bitcode.unwrap_or(&[]));
890 let llglobal = llvm::LLVMAddGlobal(
893 "rustc.embedded.module\0".as_ptr() as *const _,
895 llvm::LLVMSetInitializer(llglobal, llconst);
897 let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
898 cgcx.opts.target_triple.triple().contains("-darwin");
900 let section = if is_apple {
905 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
906 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
907 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
909 let llconst = C_bytes_in_context(llcx, &[]);
910 let llglobal = llvm::LLVMAddGlobal(
913 "rustc.embedded.cmdline\0".as_ptr() as *const _,
915 llvm::LLVMSetInitializer(llglobal, llconst);
916 let section = if is_apple {
921 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
922 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
925 pub(crate) struct CompiledModules {
926 pub modules: Vec<CompiledModule>,
927 pub metadata_module: CompiledModule,
928 pub allocator_module: Option<CompiledModule>,
931 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
932 sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
933 sess.opts.output_types.contains_key(&OutputType::Exe)
936 fn need_pre_thin_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
937 if sess.opts.incremental.is_none() {
945 Lto::ThinLocal => true,
949 pub fn start_async_codegen(tcx: TyCtxt,
950 time_graph: Option<TimeGraph>,
951 metadata: EncodedMetadata,
952 coordinator_receive: Receiver<Box<dyn Any + Send>>,
956 let crate_name = tcx.crate_name(LOCAL_CRATE);
957 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
958 let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
959 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
960 "windows_subsystem");
961 let windows_subsystem = subsystem.map(|subsystem| {
962 if subsystem != "windows" && subsystem != "console" {
963 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
964 `windows` and `console` are allowed",
967 subsystem.to_string()
970 let linker_info = LinkerInfo::new(tcx);
971 let crate_info = CrateInfo::new(tcx);
973 // Figure out what we actually need to build.
974 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
975 let mut metadata_config = ModuleConfig::new(vec![]);
976 let mut allocator_config = ModuleConfig::new(vec![]);
978 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
980 Sanitizer::Address => {
981 modules_config.passes.push("asan".to_owned());
982 modules_config.passes.push("asan-module".to_owned());
984 Sanitizer::Memory => {
985 modules_config.passes.push("msan".to_owned())
987 Sanitizer::Thread => {
988 modules_config.passes.push("tsan".to_owned())
994 if sess.opts.debugging_opts.profile {
995 modules_config.passes.push("insert-gcov-profiling".to_owned())
998 modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
999 modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
1001 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
1002 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
1004 // Save all versions of the bytecode if we're saving our temporaries.
1005 if sess.opts.cg.save_temps {
1006 modules_config.emit_no_opt_bc = true;
1007 modules_config.emit_pre_thin_lto_bc = true;
1008 modules_config.emit_bc = true;
1009 modules_config.emit_lto_bc = true;
1010 metadata_config.emit_bc = true;
1011 allocator_config.emit_bc = true;
1014 // Emit compressed bitcode files for the crate if we're emitting an rlib.
1015 // Whenever an rlib is created, the bitcode is inserted into the archive in
1016 // order to allow LTO against it.
1017 if need_crate_bitcode_for_rlib(sess) {
1018 modules_config.emit_bc_compressed = true;
1019 allocator_config.emit_bc_compressed = true;
1022 modules_config.emit_pre_thin_lto_bc =
1023 need_pre_thin_lto_bitcode_for_incr_comp(sess);
1025 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
1026 tcx.sess.target.target.options.no_integrated_as;
1028 for output_type in sess.opts.output_types.keys() {
1029 match *output_type {
1030 OutputType::Bitcode => { modules_config.emit_bc = true; }
1031 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
1032 OutputType::Assembly => {
1033 modules_config.emit_asm = true;
1034 // If we're not using the LLVM assembler, this function
1035 // could be invoked specially with output_type_assembly, so
1036 // in this case we still want the metadata object file.
1037 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
1038 metadata_config.emit_obj = true;
1039 allocator_config.emit_obj = true;
1042 OutputType::Object => { modules_config.emit_obj = true; }
1043 OutputType::Metadata => { metadata_config.emit_obj = true; }
1044 OutputType::Exe => {
1045 modules_config.emit_obj = true;
1046 metadata_config.emit_obj = true;
1047 allocator_config.emit_obj = true;
1049 OutputType::Mir => {}
1050 OutputType::DepInfo => {}
1054 modules_config.set_flags(sess, no_builtins);
1055 metadata_config.set_flags(sess, no_builtins);
1056 allocator_config.set_flags(sess, no_builtins);
1058 // Exclude metadata and allocator modules from time_passes output, since
1059 // they throw off the "LLVM passes" measurement.
1060 metadata_config.time_passes = false;
1061 allocator_config.time_passes = false;
1063 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
1064 let (codegen_worker_send, codegen_worker_receive) = channel();
1066 let coordinator_thread = start_executing_work(tcx,
1069 codegen_worker_send,
1070 coordinator_receive,
1072 sess.jobserver.clone(),
1074 Arc::new(modules_config),
1075 Arc::new(metadata_config),
1076 Arc::new(allocator_config));
1087 coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
1088 codegen_worker_receive,
1089 shared_emitter_main,
1090 future: coordinator_thread,
1091 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1095 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
1097 compiled_modules: &CompiledModules,
1098 ) -> FxHashMap<WorkProductId, WorkProduct> {
1099 let mut work_products = FxHashMap::default();
1101 if sess.opts.incremental.is_none() {
1102 return work_products;
1105 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
1106 let mut files = vec![];
1108 if let Some(ref path) = module.object {
1109 files.push((WorkProductFileKind::Object, path.clone()));
1111 if let Some(ref path) = module.bytecode {
1112 files.push((WorkProductFileKind::Bytecode, path.clone()));
1114 if let Some(ref path) = module.bytecode_compressed {
1115 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
1118 if let Some((id, product)) =
1119 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
1120 work_products.insert(id, product);
1127 fn produce_final_output_artifacts(sess: &Session,
1128 compiled_modules: &CompiledModules,
1129 crate_output: &OutputFilenames) {
1130 let mut user_wants_bitcode = false;
1131 let mut user_wants_objects = false;
1133 // Produce final compile outputs.
1134 let copy_gracefully = |from: &Path, to: &Path| {
1135 if let Err(e) = fs::copy(from, to) {
1136 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
1140 let copy_if_one_unit = |output_type: OutputType,
1141 keep_numbered: bool| {
1142 if compiled_modules.modules.len() == 1 {
1143 // 1) Only one codegen unit. In this case it's no difficulty
1144 // to copy `foo.0.x` to `foo.x`.
1145 let module_name = Some(&compiled_modules.modules[0].name[..]);
1146 let path = crate_output.temp_path(output_type, module_name);
1147 copy_gracefully(&path,
1148 &crate_output.path(output_type));
1149 if !sess.opts.cg.save_temps && !keep_numbered {
1150 // The user just wants `foo.x`, not `foo.#module-name#.x`.
1151 remove(sess, &path);
1154 let ext = crate_output.temp_path(output_type, None)
1161 if crate_output.outputs.contains_key(&output_type) {
1162 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
1163 // no good solution for this case, so warn the user.
1164 sess.warn(&format!("ignoring emit path because multiple .{} files \
1165 were produced", ext));
1166 } else if crate_output.single_output_file.is_some() {
1167 // 3) Multiple codegen units, with `-o some_name`. We have
1168 // no good solution for this case, so warn the user.
1169 sess.warn(&format!("ignoring -o because multiple .{} files \
1170 were produced", ext));
1172 // 4) Multiple codegen units, but no explicit name. We
1173 // just leave the `foo.0.x` files in place.
1174 // (We don't have to do any work in this case.)
1179 // Flag to indicate whether the user explicitly requested bitcode.
1180 // Otherwise, we produced it only as a temporary output, and will need
1181 // to get rid of it.
1182 for output_type in crate_output.outputs.keys() {
1183 match *output_type {
1184 OutputType::Bitcode => {
1185 user_wants_bitcode = true;
1186 // Copy to .bc, but always keep the .0.bc. There is a later
1187 // check to figure out if we should delete .0.bc files, or keep
1188 // them for making an rlib.
1189 copy_if_one_unit(OutputType::Bitcode, true);
1191 OutputType::LlvmAssembly => {
1192 copy_if_one_unit(OutputType::LlvmAssembly, false);
1194 OutputType::Assembly => {
1195 copy_if_one_unit(OutputType::Assembly, false);
1197 OutputType::Object => {
1198 user_wants_objects = true;
1199 copy_if_one_unit(OutputType::Object, true);
1202 OutputType::Metadata |
1204 OutputType::DepInfo => {}
1208 // Clean up unwanted temporary files.
1210 // We create the following files by default:
1211 // - #crate#.#module-name#.bc
1212 // - #crate#.#module-name#.o
1213 // - #crate#.crate.metadata.bc
1214 // - #crate#.crate.metadata.o
1215 // - #crate#.o (linked from crate.##.o)
1216 // - #crate#.bc (copied from crate.##.bc)
1217 // We may create additional files if requested by the user (through
1218 // `-C save-temps` or `--emit=` flags).
1220 if !sess.opts.cg.save_temps {
1221 // Remove the temporary .#module-name#.o objects. If the user didn't
1222 // explicitly request bitcode (with --emit=bc), and the bitcode is not
1223 // needed for building an rlib, then we must remove .#module-name#.bc as
1226 // Specific rules for keeping .#module-name#.bc:
1227 // - If the user requested bitcode (`user_wants_bitcode`), and
1228 // codegen_units > 1, then keep it.
1229 // - If the user requested bitcode but codegen_units == 1, then we
1230 // can toss .#module-name#.bc because we copied it to .bc earlier.
1231 // - If we're not building an rlib and the user didn't request
1232 // bitcode, then delete .#module-name#.bc.
1233 // If you change how this works, also update back::link::link_rlib,
1234 // where .#module-name#.bc files are (maybe) deleted after making an
1236 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
1238 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
1240 let keep_numbered_objects = needs_crate_object ||
1241 (user_wants_objects && sess.codegen_units() > 1);
1243 for module in compiled_modules.modules.iter() {
1244 if let Some(ref path) = module.object {
1245 if !keep_numbered_objects {
1250 if let Some(ref path) = module.bytecode {
1251 if !keep_numbered_bitcode {
1257 if !user_wants_bitcode {
1258 if let Some(ref path) = compiled_modules.metadata_module.bytecode {
1259 remove(sess, &path);
1262 if let Some(ref allocator_module) = compiled_modules.allocator_module {
1263 if let Some(ref path) = allocator_module.bytecode {
1270 // We leave the following files around by default:
1272 // - #crate#.crate.metadata.o
1274 // These are used in linking steps and will be cleaned up afterward.
1277 pub(crate) fn dump_incremental_data(_codegen_results: &CodegenResults) {
1278 // FIXME(mw): This does not work at the moment because the situation has
1279 // become more complicated due to incremental LTO. Now a CGU
1280 // can have more than two caching states.
1281 // println!("[incremental] Re-using {} out of {} modules",
1282 // codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
1283 // codegen_results.modules.len());
1287 /// Optimize a newly codegened, totally unoptimized module.
1288 Optimize(ModuleCodegen),
1289 /// Copy the post-LTO artifacts from the incremental cache to the output
1291 CopyPostLtoArtifacts(CachedModuleCodegen),
1292 /// Perform (Thin)LTO on the given module.
1293 LTO(lto::LtoModuleCodegen),
1297 fn module_kind(&self) -> ModuleKind {
1299 WorkItem::Optimize(ref m) => m.kind,
1300 WorkItem::CopyPostLtoArtifacts(_) |
1301 WorkItem::LTO(_) => ModuleKind::Regular,
1305 fn name(&self) -> String {
1307 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
1308 WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
1309 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
1314 enum WorkItemResult {
1315 Compiled(CompiledModule),
1316 NeedsLTO(ModuleCodegen),
1319 fn execute_work_item(cgcx: &CodegenContext,
1320 work_item: WorkItem,
1321 timeline: &mut Timeline)
1322 -> Result<WorkItemResult, FatalError>
1324 let module_config = cgcx.config(work_item.module_kind());
1327 WorkItem::Optimize(module) => {
1328 execute_optimize_work_item(cgcx, module, module_config, timeline)
1330 WorkItem::CopyPostLtoArtifacts(module) => {
1331 execute_copy_from_cache_work_item(cgcx, module, module_config, timeline)
1333 WorkItem::LTO(module) => {
1334 execute_lto_work_item(cgcx, module, module_config, timeline)
1339 fn execute_optimize_work_item(cgcx: &CodegenContext,
1340 module: ModuleCodegen,
1341 module_config: &ModuleConfig,
1342 timeline: &mut Timeline)
1343 -> Result<WorkItemResult, FatalError>
1345 let diag_handler = cgcx.create_diag_handler();
1348 optimize(cgcx, &diag_handler, &module, module_config, timeline)?;
1351 let linker_does_lto = cgcx.opts.debugging_opts.cross_lang_lto.enabled();
1353 // After we've done the initial round of optimizations we need to
1354 // decide whether to synchronously codegen this module or ship it
1355 // back to the coordinator thread for further LTO processing (which
1356 // has to wait for all the initial modules to be optimized).
1358 // Here we dispatch based on the `cgcx.lto` and kind of module we're
1360 let needs_lto = match cgcx.lto {
1363 // If the linker does LTO, we don't have to do it. Note that we
1364 // keep doing full LTO, if it is requested, as not to break the
1365 // assumption that the output will be a single module.
1366 Lto::Thin | Lto::ThinLocal if linker_does_lto => false,
1368 // Here we've got a full crate graph LTO requested. We ignore
1369 // this, however, if the crate type is only an rlib as there's
1370 // no full crate graph to process, that'll happen later.
1372 // This use case currently comes up primarily for targets that
1373 // require LTO so the request for LTO is always unconditionally
1374 // passed down to the backend, but we don't actually want to do
1375 // anything about it yet until we've got a final product.
1376 Lto::Fat | Lto::Thin => {
1377 cgcx.crate_types.len() != 1 ||
1378 cgcx.crate_types[0] != config::CrateType::Rlib
1381 // When we're automatically doing ThinLTO for multi-codegen-unit
1382 // builds we don't actually want to LTO the allocator modules if
1383 // it shows up. This is due to various linker shenanigans that
1384 // we'll encounter later.
1386 module.kind != ModuleKind::Allocator
1390 // Metadata modules never participate in LTO regardless of the lto
1392 let needs_lto = needs_lto && module.kind != ModuleKind::Metadata;
1395 Ok(WorkItemResult::NeedsLTO(module))
1397 let module = unsafe {
1398 codegen(cgcx, &diag_handler, module, module_config, timeline)?
1400 Ok(WorkItemResult::Compiled(module))
1404 fn execute_copy_from_cache_work_item(cgcx: &CodegenContext,
1405 module: CachedModuleCodegen,
1406 module_config: &ModuleConfig,
1408 -> Result<WorkItemResult, FatalError>
1410 let incr_comp_session_dir = cgcx.incr_comp_session_dir
1413 let mut object = None;
1414 let mut bytecode = None;
1415 let mut bytecode_compressed = None;
1416 for (kind, saved_file) in &module.source.saved_files {
1417 let obj_out = match kind {
1418 WorkProductFileKind::Object => {
1419 let path = cgcx.output_filenames.temp_path(OutputType::Object,
1420 Some(&module.name));
1421 object = Some(path.clone());
1424 WorkProductFileKind::Bytecode => {
1425 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1426 Some(&module.name));
1427 bytecode = Some(path.clone());
1430 WorkProductFileKind::BytecodeCompressed => {
1431 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1433 .with_extension(RLIB_BYTECODE_EXTENSION);
1434 bytecode_compressed = Some(path.clone());
1438 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1440 debug!("copying pre-existing module `{}` from {:?} to {}",
1444 match link_or_copy(&source_file, &obj_out) {
1447 let diag_handler = cgcx.create_diag_handler();
1448 diag_handler.err(&format!("unable to copy {} to {}: {}",
1449 source_file.display(),
1456 assert_eq!(object.is_some(), module_config.emit_obj);
1457 assert_eq!(bytecode.is_some(), module_config.emit_bc);
1458 assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
1460 Ok(WorkItemResult::Compiled(CompiledModule {
1462 kind: ModuleKind::Regular,
1465 bytecode_compressed,
1469 fn execute_lto_work_item(cgcx: &CodegenContext,
1470 mut module: lto::LtoModuleCodegen,
1471 module_config: &ModuleConfig,
1472 timeline: &mut Timeline)
1473 -> Result<WorkItemResult, FatalError>
1475 let diag_handler = cgcx.create_diag_handler();
1478 let module = module.optimize(cgcx, timeline)?;
1479 let module = codegen(cgcx, &diag_handler, module, module_config, timeline)?;
1480 Ok(WorkItemResult::Compiled(module))
1485 Token(io::Result<Acquired>),
1487 result: ModuleCodegen,
1491 result: Result<CompiledModule, ()>,
1495 llvm_work_item: WorkItem,
1498 AddImportOnlyModule {
1499 module_data: SerializedModule,
1500 work_product: WorkProduct,
1509 code: Option<DiagnosticId>,
1513 #[derive(PartialEq, Clone, Copy, Debug)]
1514 enum MainThreadWorkerState {
1520 fn start_executing_work(tcx: TyCtxt,
1521 crate_info: &CrateInfo,
1522 shared_emitter: SharedEmitter,
1523 codegen_worker_send: Sender<Message>,
1524 coordinator_receive: Receiver<Box<dyn Any + Send>>,
1527 time_graph: Option<TimeGraph>,
1528 modules_config: Arc<ModuleConfig>,
1529 metadata_config: Arc<ModuleConfig>,
1530 allocator_config: Arc<ModuleConfig>)
1531 -> thread::JoinHandle<Result<CompiledModules, ()>> {
1532 let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1533 let sess = tcx.sess;
1535 // Compute the set of symbols we need to retain when doing LTO (if we need to)
1536 let exported_symbols = {
1537 let mut exported_symbols = FxHashMap::default();
1539 let copy_symbols = |cnum| {
1540 let symbols = tcx.exported_symbols(cnum)
1542 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1550 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1551 Some(Arc::new(exported_symbols))
1553 Lto::Fat | Lto::Thin => {
1554 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1555 for &cnum in tcx.crates().iter() {
1556 exported_symbols.insert(cnum, copy_symbols(cnum));
1558 Some(Arc::new(exported_symbols))
1563 // First up, convert our jobserver into a helper thread so we can use normal
1564 // mpsc channels to manage our messages and such.
1565 // After we've requested tokens then we'll, when we can,
1566 // get tokens on `coordinator_receive` which will
1567 // get managed in the main loop below.
1568 let coordinator_send2 = coordinator_send.clone();
1569 let helper = jobserver.into_helper_thread(move |token| {
1570 drop(coordinator_send2.send(Box::new(Message::Token(token))));
1571 }).expect("failed to spawn helper thread");
1573 let mut each_linked_rlib_for_lto = Vec::new();
1574 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1575 if link::ignored_for_lto(sess, crate_info, cnum) {
1578 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1581 let assembler_cmd = if modules_config.no_integrated_as {
1582 // HACK: currently we use linker (gcc) as our assembler
1583 let (linker, flavor) = link::linker_and_flavor(sess);
1585 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1586 cmd.args(&sess.target.target.options.asm_args);
1587 Some(Arc::new(AssemblerCommand {
1595 let cgcx = CodegenContext {
1596 crate_types: sess.crate_types.borrow().clone(),
1597 each_linked_rlib_for_lto,
1599 no_landing_pads: sess.no_landing_pads(),
1600 fewer_names: sess.fewer_names(),
1601 save_temps: sess.opts.cg.save_temps,
1602 opts: Arc::new(sess.opts.clone()),
1603 time_passes: sess.time_passes(),
1605 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1606 remark: sess.opts.cg.remark.clone(),
1608 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1609 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1611 diag_emitter: shared_emitter.clone(),
1613 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1614 regular_module_config: modules_config,
1615 metadata_module_config: metadata_config,
1616 allocator_module_config: allocator_config,
1617 tm_factory: target_machine_factory(tcx.sess, false),
1619 msvc_imps_needed: msvc_imps_needed(tcx),
1620 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1621 debuginfo: tcx.sess.opts.debuginfo,
1625 // This is the "main loop" of parallel work happening for parallel codegen.
1626 // It's here that we manage parallelism, schedule work, and work with
1627 // messages coming from clients.
1629 // There are a few environmental pre-conditions that shape how the system
1632 // - Error reporting only can happen on the main thread because that's the
1633 // only place where we have access to the compiler `Session`.
1634 // - LLVM work can be done on any thread.
1635 // - Codegen can only happen on the main thread.
1636 // - Each thread doing substantial work most be in possession of a `Token`
1637 // from the `Jobserver`.
1638 // - The compiler process always holds one `Token`. Any additional `Tokens`
1639 // have to be requested from the `Jobserver`.
1643 // The error reporting restriction is handled separately from the rest: We
1644 // set up a `SharedEmitter` the holds an open channel to the main thread.
1645 // When an error occurs on any thread, the shared emitter will send the
1646 // error message to the receiver main thread (`SharedEmitterMain`). The
1647 // main thread will periodically query this error message queue and emit
1648 // any error messages it has received. It might even abort compilation if
1649 // has received a fatal error. In this case we rely on all other threads
1650 // being torn down automatically with the main thread.
1651 // Since the main thread will often be busy doing codegen work, error
1652 // reporting will be somewhat delayed, since the message queue can only be
1653 // checked in between to work packages.
1655 // Work Processing Infrastructure
1656 // ==============================
1657 // The work processing infrastructure knows three major actors:
1659 // - the coordinator thread,
1660 // - the main thread, and
1661 // - LLVM worker threads
1663 // The coordinator thread is running a message loop. It instructs the main
1664 // thread about what work to do when, and it will spawn off LLVM worker
1665 // threads as open LLVM WorkItems become available.
1667 // The job of the main thread is to codegen CGUs into LLVM work package
1668 // (since the main thread is the only thread that can do this). The main
1669 // thread will block until it receives a message from the coordinator, upon
1670 // which it will codegen one CGU, send it to the coordinator and block
1671 // again. This way the coordinator can control what the main thread is
1674 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1675 // available, it will spawn off a new LLVM worker thread and let it process
1676 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1677 // it will just shut down, which also frees all resources associated with
1678 // the given LLVM module, and sends a message to the coordinator that the
1679 // has been completed.
1683 // The scheduler's goal is to minimize the time it takes to complete all
1684 // work there is, however, we also want to keep memory consumption low
1685 // if possible. These two goals are at odds with each other: If memory
1686 // consumption were not an issue, we could just let the main thread produce
1687 // LLVM WorkItems at full speed, assuring maximal utilization of
1688 // Tokens/LLVM worker threads. However, since codegen usual is faster
1689 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1690 // WorkItem potentially holds on to a substantial amount of memory.
1692 // So the actual goal is to always produce just enough LLVM WorkItems as
1693 // not to starve our LLVM worker threads. That means, once we have enough
1694 // WorkItems in our queue, we can block the main thread, so it does not
1695 // produce more until we need them.
1697 // Doing LLVM Work on the Main Thread
1698 // ----------------------------------
1699 // Since the main thread owns the compiler processes implicit `Token`, it is
1700 // wasteful to keep it blocked without doing any work. Therefore, what we do
1701 // in this case is: We spawn off an additional LLVM worker thread that helps
1702 // reduce the queue. The work it is doing corresponds to the implicit
1703 // `Token`. The coordinator will mark the main thread as being busy with
1704 // LLVM work. (The actual work happens on another OS thread but we just care
1705 // about `Tokens`, not actual threads).
1707 // When any LLVM worker thread finishes while the main thread is marked as
1708 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1709 // of the just finished thread to the LLVM worker thread that is working on
1710 // behalf of the main thread's implicit Token, thus freeing up the main
1711 // thread again. The coordinator can then again decide what the main thread
1712 // should do. This allows the coordinator to make decisions at more points
1715 // Striking a Balance between Throughput and Memory Consumption
1716 // ------------------------------------------------------------
1717 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1718 // memory consumption as low as possible, are in conflict with each other,
1719 // we have to find a trade off between them. Right now, the goal is to keep
1720 // all workers busy, which means that no worker should find the queue empty
1721 // when it is ready to start.
1722 // How do we do achieve this? Good question :) We actually never know how
1723 // many `Tokens` are potentially available so it's hard to say how much to
1724 // fill up the queue before switching the main thread to LLVM work. Also we
1725 // currently don't have a means to estimate how long a running LLVM worker
1726 // will still be busy with it's current WorkItem. However, we know the
1727 // maximal count of available Tokens that makes sense (=the number of CPU
1728 // cores), so we can take a conservative guess. The heuristic we use here
1729 // is implemented in the `queue_full_enough()` function.
1731 // Some Background on Jobservers
1732 // -----------------------------
1733 // It's worth also touching on the management of parallelism here. We don't
1734 // want to just spawn a thread per work item because while that's optimal
1735 // parallelism it may overload a system with too many threads or violate our
1736 // configuration for the maximum amount of cpu to use for this process. To
1737 // manage this we use the `jobserver` crate.
1739 // Job servers are an artifact of GNU make and are used to manage
1740 // parallelism between processes. A jobserver is a glorified IPC semaphore
1741 // basically. Whenever we want to run some work we acquire the semaphore,
1742 // and whenever we're done with that work we release the semaphore. In this
1743 // manner we can ensure that the maximum number of parallel workers is
1744 // capped at any one point in time.
1746 // LTO and the coordinator thread
1747 // ------------------------------
1749 // The final job the coordinator thread is responsible for is managing LTO
1750 // and how that works. When LTO is requested what we'll to is collect all
1751 // optimized LLVM modules into a local vector on the coordinator. Once all
1752 // modules have been codegened and optimized we hand this to the `lto`
1753 // module for further optimization. The `lto` module will return back a list
1754 // of more modules to work on, which the coordinator will continue to spawn
1757 // Each LLVM module is automatically sent back to the coordinator for LTO if
1758 // necessary. There's already optimizations in place to avoid sending work
1759 // back to the coordinator if LTO isn't requested.
1760 return thread::spawn(move || {
1761 // We pretend to be within the top-level LLVM time-passes task here:
1764 let max_workers = ::num_cpus::get();
1765 let mut worker_id_counter = 0;
1766 let mut free_worker_ids = Vec::new();
1767 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1768 if let Some(id) = free_worker_ids.pop() {
1771 let id = worker_id_counter;
1772 worker_id_counter += 1;
1777 // This is where we collect codegen units that have gone all the way
1778 // through codegen and LLVM.
1779 let mut compiled_modules = vec![];
1780 let mut compiled_metadata_module = None;
1781 let mut compiled_allocator_module = None;
1782 let mut needs_lto = Vec::new();
1783 let mut lto_import_only_modules = Vec::new();
1784 let mut started_lto = false;
1785 let mut codegen_aborted = false;
1787 // This flag tracks whether all items have gone through codegens
1788 let mut codegen_done = false;
1790 // This is the queue of LLVM work items that still need processing.
1791 let mut work_items = Vec::<(WorkItem, u64)>::new();
1793 // This are the Jobserver Tokens we currently hold. Does not include
1794 // the implicit Token the compiler process owns no matter what.
1795 let mut tokens = Vec::new();
1797 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1798 let mut running = 0;
1800 let mut llvm_start_time = None;
1802 // Run the message loop while there's still anything that needs message
1803 // processing. Note that as soon as codegen is aborted we simply want to
1804 // wait for all existing work to finish, so many of the conditions here
1805 // only apply if codegen hasn't been aborted as they represent pending
1807 while !codegen_done ||
1809 (!codegen_aborted && (
1810 work_items.len() > 0 ||
1811 needs_lto.len() > 0 ||
1812 lto_import_only_modules.len() > 0 ||
1813 main_thread_worker_state != MainThreadWorkerState::Idle
1817 // While there are still CGUs to be codegened, the coordinator has
1818 // to decide how to utilize the compiler processes implicit Token:
1819 // For codegenning more CGU or for running them through LLVM.
1821 if main_thread_worker_state == MainThreadWorkerState::Idle {
1822 if !queue_full_enough(work_items.len(), running, max_workers) {
1823 // The queue is not full enough, codegen more items:
1824 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1825 panic!("Could not send Message::CodegenItem to main thread")
1827 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1829 // The queue is full enough to not let the worker
1830 // threads starve. Use the implicit Token to do some
1832 let (item, _) = work_items.pop()
1833 .expect("queue empty - queue_full_enough() broken?");
1834 let cgcx = CodegenContext {
1835 worker: get_worker_id(&mut free_worker_ids),
1838 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1839 &mut llvm_start_time);
1840 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1841 spawn_work(cgcx, item);
1844 } else if codegen_aborted {
1845 // don't queue up any more work if codegen was aborted, we're
1846 // just waiting for our existing children to finish
1848 // If we've finished everything related to normal codegen
1849 // then it must be the case that we've got some LTO work to do.
1850 // Perform the serial work here of figuring out what we're
1851 // going to LTO and then push a bunch of work items onto our
1853 if work_items.len() == 0 &&
1855 main_thread_worker_state == MainThreadWorkerState::Idle {
1856 assert!(!started_lto);
1857 assert!(needs_lto.len() + lto_import_only_modules.len() > 0);
1859 let modules = mem::replace(&mut needs_lto, Vec::new());
1860 let import_only_modules =
1861 mem::replace(&mut lto_import_only_modules, Vec::new());
1862 for (work, cost) in generate_lto_work(&cgcx, modules, import_only_modules) {
1863 let insertion_index = work_items
1864 .binary_search_by_key(&cost, |&(_, cost)| cost)
1865 .unwrap_or_else(|e| e);
1866 work_items.insert(insertion_index, (work, cost));
1867 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1868 helper.request_token();
1873 // In this branch, we know that everything has been codegened,
1874 // so it's just a matter of determining whether the implicit
1875 // Token is free to use for LLVM work.
1876 match main_thread_worker_state {
1877 MainThreadWorkerState::Idle => {
1878 if let Some((item, _)) = work_items.pop() {
1879 let cgcx = CodegenContext {
1880 worker: get_worker_id(&mut free_worker_ids),
1883 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1884 &mut llvm_start_time);
1885 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1886 spawn_work(cgcx, item);
1888 // There is no unstarted work, so let the main thread
1889 // take over for a running worker. Otherwise the
1890 // implicit token would just go to waste.
1891 // We reduce the `running` counter by one. The
1892 // `tokens.truncate()` below will take care of
1893 // giving the Token back.
1894 debug_assert!(running > 0);
1896 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1899 MainThreadWorkerState::Codegenning => {
1900 bug!("codegen worker should not be codegenning after \
1901 codegen was already completed")
1903 MainThreadWorkerState::LLVMing => {
1904 // Already making good use of that token
1909 // Spin up what work we can, only doing this while we've got available
1910 // parallelism slots and work left to spawn.
1911 while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1912 let (item, _) = work_items.pop().unwrap();
1914 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1915 &mut llvm_start_time);
1917 let cgcx = CodegenContext {
1918 worker: get_worker_id(&mut free_worker_ids),
1922 spawn_work(cgcx, item);
1926 // Relinquish accidentally acquired extra tokens
1927 tokens.truncate(running);
1929 let msg = coordinator_receive.recv().unwrap();
1930 match *msg.downcast::<Message>().ok().unwrap() {
1931 // Save the token locally and the next turn of the loop will use
1932 // this to spawn a new unit of work, or it may get dropped
1933 // immediately if we have no more work to spawn.
1934 Message::Token(token) => {
1939 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1940 // If the main thread token is used for LLVM work
1941 // at the moment, we turn that thread into a regular
1942 // LLVM worker thread, so the main thread is free
1943 // to react to codegen demand.
1944 main_thread_worker_state = MainThreadWorkerState::Idle;
1949 let msg = &format!("failed to acquire jobserver token: {}", e);
1950 shared_emitter.fatal(msg);
1951 // Exit the coordinator thread
1957 Message::CodegenDone { llvm_work_item, cost } => {
1958 // We keep the queue sorted by estimated processing cost,
1959 // so that more expensive items are processed earlier. This
1960 // is good for throughput as it gives the main thread more
1961 // time to fill up the queue and it avoids scheduling
1962 // expensive items to the end.
1963 // Note, however, that this is not ideal for memory
1964 // consumption, as LLVM module sizes are not evenly
1966 let insertion_index =
1967 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1968 let insertion_index = match insertion_index {
1969 Ok(idx) | Err(idx) => idx
1971 work_items.insert(insertion_index, (llvm_work_item, cost));
1973 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1974 helper.request_token();
1976 assert!(!codegen_aborted);
1977 assert_eq!(main_thread_worker_state,
1978 MainThreadWorkerState::Codegenning);
1979 main_thread_worker_state = MainThreadWorkerState::Idle;
1982 Message::CodegenComplete => {
1983 codegen_done = true;
1984 assert!(!codegen_aborted);
1985 assert_eq!(main_thread_worker_state,
1986 MainThreadWorkerState::Codegenning);
1987 main_thread_worker_state = MainThreadWorkerState::Idle;
1990 // If codegen is aborted that means translation was aborted due
1991 // to some normal-ish compiler error. In this situation we want
1992 // to exit as soon as possible, but we want to make sure all
1993 // existing work has finished. Flag codegen as being done, and
1994 // then conditions above will ensure no more work is spawned but
1995 // we'll keep executing this loop until `running` hits 0.
1996 Message::CodegenAborted => {
1997 assert!(!codegen_aborted);
1998 codegen_done = true;
1999 codegen_aborted = true;
2000 assert_eq!(main_thread_worker_state,
2001 MainThreadWorkerState::Codegenning);
2004 // If a thread exits successfully then we drop a token associated
2005 // with that worker and update our `running` count. We may later
2006 // re-acquire a token to continue running more work. We may also not
2007 // actually drop a token here if the worker was running with an
2008 // "ephemeral token"
2010 // Note that if the thread failed that means it panicked, so we
2011 // abort immediately.
2012 Message::Done { result: Ok(compiled_module), worker_id } => {
2013 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
2014 main_thread_worker_state = MainThreadWorkerState::Idle;
2019 free_worker_ids.push(worker_id);
2021 match compiled_module.kind {
2022 ModuleKind::Regular => {
2023 compiled_modules.push(compiled_module);
2025 ModuleKind::Metadata => {
2026 assert!(compiled_metadata_module.is_none());
2027 compiled_metadata_module = Some(compiled_module);
2029 ModuleKind::Allocator => {
2030 assert!(compiled_allocator_module.is_none());
2031 compiled_allocator_module = Some(compiled_module);
2035 Message::NeedsLTO { result, worker_id } => {
2036 assert!(!started_lto);
2037 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
2038 main_thread_worker_state = MainThreadWorkerState::Idle;
2042 free_worker_ids.push(worker_id);
2043 needs_lto.push(result);
2045 Message::AddImportOnlyModule { module_data, work_product } => {
2046 assert!(!started_lto);
2047 assert!(!codegen_done);
2048 assert_eq!(main_thread_worker_state,
2049 MainThreadWorkerState::Codegenning);
2050 lto_import_only_modules.push((module_data, work_product));
2051 main_thread_worker_state = MainThreadWorkerState::Idle;
2053 Message::Done { result: Err(()), worker_id: _ } => {
2054 bug!("worker thread panicked");
2056 Message::CodegenItem => {
2057 bug!("the coordinator should not receive codegen requests")
2062 if let Some(llvm_start_time) = llvm_start_time {
2063 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
2064 // This is the top-level timing for all of LLVM, set the time-depth
2067 print_time_passes_entry(cgcx.time_passes,
2072 // Regardless of what order these modules completed in, report them to
2073 // the backend in the same order every time to ensure that we're handing
2074 // out deterministic results.
2075 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
2077 let compiled_metadata_module = compiled_metadata_module
2078 .expect("Metadata module not compiled?");
2080 Ok(CompiledModules {
2081 modules: compiled_modules,
2082 metadata_module: compiled_metadata_module,
2083 allocator_module: compiled_allocator_module,
2087 // A heuristic that determines if we have enough LLVM WorkItems in the
2088 // queue so that the main thread can do LLVM work instead of codegen
2089 fn queue_full_enough(items_in_queue: usize,
2090 workers_running: usize,
2091 max_workers: usize) -> bool {
2093 items_in_queue > 0 &&
2094 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
2097 fn maybe_start_llvm_timer(config: &ModuleConfig,
2098 llvm_start_time: &mut Option<Instant>) {
2099 // We keep track of the -Ztime-passes output manually,
2100 // since the closure-based interface does not fit well here.
2101 if config.time_passes {
2102 if llvm_start_time.is_none() {
2103 *llvm_start_time = Some(Instant::now());
2109 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
2110 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
2111 time_graph::TimelineId(CODEGEN_WORKER_ID);
2112 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2113 time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
2114 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2115 time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
2117 fn spawn_work(cgcx: CodegenContext, work: WorkItem) {
2118 let depth = time_depth();
2120 thread::spawn(move || {
2121 set_time_depth(depth);
2123 // Set up a destructor which will fire off a message that we're done as
2126 coordinator_send: Sender<Box<dyn Any + Send>>,
2127 result: Option<WorkItemResult>,
2130 impl Drop for Bomb {
2131 fn drop(&mut self) {
2132 let worker_id = self.worker_id;
2133 let msg = match self.result.take() {
2134 Some(WorkItemResult::Compiled(m)) => {
2135 Message::Done { result: Ok(m), worker_id }
2137 Some(WorkItemResult::NeedsLTO(m)) => {
2138 Message::NeedsLTO { result: m, worker_id }
2140 None => Message::Done { result: Err(()), worker_id }
2142 drop(self.coordinator_send.send(Box::new(msg)));
2146 let mut bomb = Bomb {
2147 coordinator_send: cgcx.coordinator_send.clone(),
2149 worker_id: cgcx.worker,
2152 // Execute the work itself, and if it finishes successfully then flag
2153 // ourselves as a success as well.
2155 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
2156 // as a diagnostic was already sent off to the main thread - just
2157 // surface that there was an error in this worker.
2159 let timeline = cgcx.time_graph.as_ref().map(|tg| {
2160 tg.start(time_graph::TimelineId(cgcx.worker),
2161 LLVM_WORK_PACKAGE_KIND,
2164 let mut timeline = timeline.unwrap_or(Timeline::noop());
2165 execute_work_item(&cgcx, work, &mut timeline).ok()
2170 pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, object: &Path) {
2171 let assembler = cgcx.assembler_cmd
2173 .expect("cgcx.assembler_cmd is missing?");
2175 let pname = &assembler.name;
2176 let mut cmd = assembler.cmd.clone();
2177 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
2178 debug!("{:?}", cmd);
2180 match cmd.output() {
2182 if !prog.status.success() {
2183 let mut note = prog.stderr.clone();
2184 note.extend_from_slice(&prog.stdout);
2186 handler.struct_err(&format!("linking with `{}` failed: {}",
2189 .note(&format!("{:?}", &cmd))
2190 .note(str::from_utf8(¬e[..]).unwrap())
2192 handler.abort_if_errors();
2196 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
2197 handler.abort_if_errors();
2202 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
2203 config: &ModuleConfig,
2204 opt_level: llvm::CodeGenOptLevel,
2205 prepare_for_thin_lto: bool,
2206 f: &mut dyn FnMut(&llvm::PassManagerBuilder)) {
2209 // Create the PassManagerBuilder for LLVM. We configure it with
2210 // reasonable defaults and prepare it to actually populate the pass
2212 let builder = llvm::LLVMPassManagerBuilderCreate();
2213 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
2214 let inline_threshold = config.inline_threshold;
2216 let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
2217 let s = if s.is_empty() { "default_%m.profraw" } else { s };
2218 CString::new(s.as_bytes()).unwrap()
2221 let pgo_use_path = if config.pgo_use.is_empty() {
2224 Some(CString::new(config.pgo_use.as_bytes()).unwrap())
2227 llvm::LLVMRustConfigurePassManagerBuilder(
2230 config.merge_functions,
2231 config.vectorize_slp,
2232 config.vectorize_loop,
2233 prepare_for_thin_lto,
2234 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2235 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2238 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
2240 if opt_size != llvm::CodeGenOptSizeNone {
2241 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
2244 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
2246 // Here we match what clang does (kinda). For O0 we only inline
2247 // always-inline functions (but don't add lifetime intrinsics), at O1 we
2248 // inline with lifetime intrinsics, and O2+ we add an inliner with a
2249 // thresholds copied from clang.
2250 match (opt_level, opt_size, inline_threshold) {
2252 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
2254 (llvm::CodeGenOptLevel::Aggressive, ..) => {
2255 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
2257 (_, llvm::CodeGenOptSizeDefault, _) => {
2258 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
2260 (_, llvm::CodeGenOptSizeAggressive, _) => {
2261 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
2263 (llvm::CodeGenOptLevel::None, ..) => {
2264 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
2266 (llvm::CodeGenOptLevel::Less, ..) => {
2267 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
2269 (llvm::CodeGenOptLevel::Default, ..) => {
2270 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
2272 (llvm::CodeGenOptLevel::Other, ..) => {
2273 bug!("CodeGenOptLevel::Other selected")
2278 llvm::LLVMPassManagerBuilderDispose(builder);
2282 enum SharedEmitterMessage {
2283 Diagnostic(Diagnostic),
2284 InlineAsmError(u32, String),
2290 pub struct SharedEmitter {
2291 sender: Sender<SharedEmitterMessage>,
2294 pub struct SharedEmitterMain {
2295 receiver: Receiver<SharedEmitterMessage>,
2298 impl SharedEmitter {
2299 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
2300 let (sender, receiver) = channel();
2302 (SharedEmitter { sender }, SharedEmitterMain { receiver })
2305 fn inline_asm_error(&self, cookie: u32, msg: String) {
2306 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
2309 fn fatal(&self, msg: &str) {
2310 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2314 impl Emitter for SharedEmitter {
2315 fn emit(&mut self, db: &DiagnosticBuilder) {
2316 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2318 code: db.code.clone(),
2321 for child in &db.children {
2322 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2323 msg: child.message(),
2328 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
2332 impl SharedEmitterMain {
2333 pub fn check(&self, sess: &Session, blocking: bool) {
2335 let message = if blocking {
2336 match self.receiver.recv() {
2337 Ok(message) => Ok(message),
2341 match self.receiver.try_recv() {
2342 Ok(message) => Ok(message),
2348 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2349 let handler = sess.diagnostic();
2352 handler.emit_with_code(&MultiSpan::new(),
2358 handler.emit(&MultiSpan::new(),
2364 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
2365 match Mark::from_u32(cookie).expn_info() {
2366 Some(ei) => sess.span_err(ei.call_site, &msg),
2367 None => sess.err(&msg),
2370 Ok(SharedEmitterMessage::AbortIfErrors) => {
2371 sess.abort_if_errors();
2373 Ok(SharedEmitterMessage::Fatal(msg)) => {
2385 pub struct OngoingCodegen {
2388 metadata: EncodedMetadata,
2389 windows_subsystem: Option<String>,
2390 linker_info: LinkerInfo,
2391 crate_info: CrateInfo,
2392 time_graph: Option<TimeGraph>,
2393 coordinator_send: Sender<Box<dyn Any + Send>>,
2394 codegen_worker_receive: Receiver<Message>,
2395 shared_emitter_main: SharedEmitterMain,
2396 future: thread::JoinHandle<Result<CompiledModules, ()>>,
2397 output_filenames: Arc<OutputFilenames>,
2400 impl OngoingCodegen {
2404 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
2405 self.shared_emitter_main.check(sess, true);
2406 let compiled_modules = match self.future.join() {
2407 Ok(Ok(compiled_modules)) => compiled_modules,
2409 sess.abort_if_errors();
2410 panic!("expected abort due to worker thread errors")
2413 bug!("panic during codegen/LLVM phase");
2417 sess.cgu_reuse_tracker.check_expected_reuse(sess);
2419 sess.abort_if_errors();
2421 if let Some(time_graph) = self.time_graph {
2422 time_graph.dump(&format!("{}-timings", self.crate_name));
2426 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
2428 produce_final_output_artifacts(sess,
2430 &self.output_filenames);
2432 // FIXME: time_llvm_passes support - does this use a global context or
2434 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2435 unsafe { llvm::LLVMRustPrintPassTimings(); }
2439 crate_name: self.crate_name,
2440 crate_hash: self.crate_hash,
2441 metadata: self.metadata,
2442 windows_subsystem: self.windows_subsystem,
2443 linker_info: self.linker_info,
2444 crate_info: self.crate_info,
2446 modules: compiled_modules.modules,
2447 allocator_module: compiled_modules.allocator_module,
2448 metadata_module: compiled_modules.metadata_module,
2452 pub(crate) fn submit_pre_codegened_module_to_llvm(&self,
2454 module: ModuleCodegen) {
2455 self.wait_for_signal_to_codegen_item();
2456 self.check_for_errors(tcx.sess);
2458 // These are generally cheap and won't through off scheduling.
2460 submit_codegened_module_to_llvm(tcx, module, cost);
2463 pub fn codegen_finished(&self, tcx: TyCtxt) {
2464 self.wait_for_signal_to_codegen_item();
2465 self.check_for_errors(tcx.sess);
2466 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete)));
2469 /// Consume this context indicating that codegen was entirely aborted, and
2470 /// we need to exit as quickly as possible.
2472 /// This method blocks the current thread until all worker threads have
2473 /// finished, and all worker threads should have exited or be real close to
2474 /// exiting at this point.
2475 pub fn codegen_aborted(self) {
2476 // Signal to the coordinator it should spawn no more work and start
2478 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted)));
2479 drop(self.future.join());
2482 pub fn check_for_errors(&self, sess: &Session) {
2483 self.shared_emitter_main.check(sess, false);
2486 pub fn wait_for_signal_to_codegen_item(&self) {
2487 match self.codegen_worker_receive.recv() {
2488 Ok(Message::CodegenItem) => {
2491 Ok(_) => panic!("unexpected message"),
2493 // One of the LLVM threads must have panicked, fall through so
2494 // error handling can be reached.
2500 // impl Drop for OngoingCodegen {
2501 // fn drop(&mut self) {
2505 pub(crate) fn submit_codegened_module_to_llvm(tcx: TyCtxt,
2506 module: ModuleCodegen,
2508 let llvm_work_item = WorkItem::Optimize(module);
2509 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2515 pub(crate) fn submit_post_lto_module_to_llvm(tcx: TyCtxt,
2516 module: CachedModuleCodegen) {
2517 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2518 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2524 pub(crate) fn submit_pre_lto_module_to_llvm(tcx: TyCtxt,
2525 module: CachedModuleCodegen) {
2526 let filename = pre_lto_bitcode_filename(&module.name);
2527 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2528 let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
2529 panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
2533 memmap::Mmap::map(&file).unwrap_or_else(|e| {
2534 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2538 // Schedule the module to be loaded
2539 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::AddImportOnlyModule {
2540 module_data: SerializedModule::FromUncompressedFile(mmap),
2541 work_product: module.source,
2545 pub(super) fn pre_lto_bitcode_filename(module_name: &str) -> String {
2546 format!("{}.{}", module_name, PRE_THIN_LTO_BC_EXT)
2549 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2550 // This should never be true (because it's not supported). If it is true,
2551 // something is wrong with commandline arg validation.
2552 assert!(!(tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() &&
2553 tcx.sess.target.target.options.is_like_msvc &&
2554 tcx.sess.opts.cg.prefer_dynamic));
2556 tcx.sess.target.target.options.is_like_msvc &&
2557 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
2558 // ThinLTO can't handle this workaround in all cases, so we don't
2559 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2560 // dynamic linking when cross-language LTO is enabled.
2561 !tcx.sess.opts.debugging_opts.cross_lang_lto.enabled()
2564 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2565 // This is required to satisfy `dllimport` references to static data in .rlibs
2566 // when using MSVC linker. We do this only for data, as linker can fix up
2567 // code references on its own.
2568 // See #26591, #27438
2569 fn create_msvc_imps(cgcx: &CodegenContext, llcx: &llvm::Context, llmod: &llvm::Module) {
2570 if !cgcx.msvc_imps_needed {
2573 // The x86 ABI seems to require that leading underscores are added to symbol
2574 // names, so we need an extra underscore on 32-bit. There's also a leading
2575 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2576 // underscores added in front).
2577 let prefix = if cgcx.target_pointer_width == "32" {
2583 let i8p_ty = Type::i8p_llcx(llcx);
2584 let globals = base::iter_globals(llmod)
2586 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
2587 llvm::LLVMIsDeclaration(val) == 0
2590 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2591 let mut imp_name = prefix.as_bytes().to_vec();
2592 imp_name.extend(name.to_bytes());
2593 let imp_name = CString::new(imp_name).unwrap();
2596 .collect::<Vec<_>>();
2597 for (imp_name, val) in globals {
2598 let imp = llvm::LLVMAddGlobal(llmod,
2600 imp_name.as_ptr() as *const _);
2601 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
2602 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);