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 : [(&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 : [(&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: &str) -> 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(target, pm, m, output_c.as_ptr(), file_type);
110 if result.into_result().is_err() {
111 let msg = format!("could not write output to {}", output.display());
112 Err(llvm_err(handler, &msg))
119 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
121 config::OptLevel::No => llvm::CodeGenOptLevel::None,
122 config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
123 config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
124 config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
125 _ => llvm::CodeGenOptLevel::Default,
129 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
131 config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
132 config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
133 _ => llvm::CodeGenOptSizeNone,
137 pub fn create_target_machine(
140 ) -> &'static mut llvm::TargetMachine {
141 target_machine_factory(sess, find_features)().unwrap_or_else(|err| {
142 llvm_err(sess.diagnostic(), &err).raise()
146 // If find_features is true this won't access `sess.crate_types` by assuming
147 // that `is_pie_binary` is false. When we discover LLVM target features
148 // `sess.crate_types` is uninitialized so we cannot access it.
149 pub fn target_machine_factory(sess: &Session, find_features: bool)
150 -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>
152 let reloc_model = get_reloc_model(sess);
154 let opt_level = get_llvm_opt_level(sess.opts.optimize);
155 let use_softfp = sess.opts.cg.soft_float;
157 let ffunction_sections = sess.target.target.options.function_sections;
158 let fdata_sections = ffunction_sections;
160 let code_model_arg = sess.opts.cg.code_model.as_ref().or(
161 sess.target.target.options.code_model.as_ref(),
164 let code_model = match code_model_arg {
166 match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
169 sess.err(&format!("{:?} is not a valid code model",
171 sess.abort_if_errors();
176 None => llvm::CodeModel::None,
179 let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
180 let mut singlethread = sess.target.target.options.singlethread;
182 // On the wasm target once the `atomics` feature is enabled that means that
183 // we're no longer single-threaded, or otherwise we don't want LLVM to
184 // lower atomic operations to single-threaded operations.
186 sess.target.target.llvm_target.contains("wasm32") &&
187 features.iter().any(|s| *s == "+atomics")
189 singlethread = false;
192 let triple = SmallCStr::new(&sess.target.target.llvm_target);
193 let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
194 let features = features.join(",");
195 let features = CString::new(features).unwrap();
196 let is_pie_binary = !find_features && is_pie_binary(sess);
197 let trap_unreachable = sess.target.target.options.trap_unreachable;
198 let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
200 let asm_comments = sess.asm_comments();
204 llvm::LLVMRustCreateTargetMachine(
205 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
216 emit_stack_size_section,
221 format!("Could not create LLVM TargetMachine for triple: {}",
222 triple.to_str().unwrap())
227 /// Module-specific configuration for `optimize_and_codegen`.
228 pub struct ModuleConfig {
229 /// Names of additional optimization passes to run.
231 /// Some(level) to optimize at a certain level, or None to run
232 /// absolutely no optimizations (used for the metadata module).
233 pub opt_level: Option<llvm::CodeGenOptLevel>,
235 /// Some(level) to optimize binary size, or None to not affect program size.
236 opt_size: Option<llvm::CodeGenOptSize>,
238 pgo_gen: Option<String>,
241 // Flags indicating which outputs to produce.
242 pub emit_pre_thin_lto_bc: bool,
243 emit_no_opt_bc: bool,
245 emit_bc_compressed: bool,
250 // Miscellaneous flags. These are mostly copied from command-line
252 pub verify_llvm_ir: bool,
253 no_prepopulate_passes: bool,
256 vectorize_loop: bool,
258 merge_functions: bool,
259 inline_threshold: Option<usize>,
260 // Instead of creating an object file by doing LLVM codegen, just
261 // make the object file bitcode. Provides easy compatibility with
262 // emscripten's ecc compiler, when used as the linker.
263 obj_is_bitcode: bool,
264 no_integrated_as: bool,
266 embed_bitcode_marker: bool,
270 fn new(passes: Vec<String>) -> ModuleConfig {
277 pgo_use: String::new(),
279 emit_no_opt_bc: false,
280 emit_pre_thin_lto_bc: false,
282 emit_bc_compressed: false,
287 obj_is_bitcode: false,
288 embed_bitcode: false,
289 embed_bitcode_marker: false,
290 no_integrated_as: false,
292 verify_llvm_ir: false,
293 no_prepopulate_passes: false,
296 vectorize_loop: false,
297 vectorize_slp: false,
298 merge_functions: false,
299 inline_threshold: None
303 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
304 self.verify_llvm_ir = sess.verify_llvm_ir();
305 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
306 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
307 self.time_passes = sess.time_passes();
308 self.inline_threshold = sess.opts.cg.inline_threshold;
309 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
310 sess.opts.debugging_opts.cross_lang_lto.enabled();
311 let embed_bitcode = sess.target.target.options.embed_bitcode ||
312 sess.opts.debugging_opts.embed_bitcode;
314 match sess.opts.optimize {
315 config::OptLevel::No |
316 config::OptLevel::Less => {
317 self.embed_bitcode_marker = embed_bitcode;
319 _ => self.embed_bitcode = embed_bitcode,
323 // Copy what clang does by turning on loop vectorization at O2 and
324 // slp vectorization at O3. Otherwise configure other optimization aspects
325 // of this pass manager builder.
326 // Turn off vectorization for emscripten, as it's not very well supported.
327 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
328 (sess.opts.optimize == config::OptLevel::Default ||
329 sess.opts.optimize == config::OptLevel::Aggressive) &&
330 !sess.target.target.options.is_like_emscripten;
332 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
333 sess.opts.optimize == config::OptLevel::Aggressive &&
334 !sess.target.target.options.is_like_emscripten;
336 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
337 sess.opts.optimize == config::OptLevel::Aggressive;
340 pub fn bitcode_needed(&self) -> bool {
341 self.emit_bc || self.obj_is_bitcode
342 || self.emit_bc_compressed || self.embed_bitcode
346 /// Assembler name and command used by codegen when no_integrated_as is enabled
347 struct AssemblerCommand {
352 /// Additional resources used by optimize_and_codegen (not module specific)
354 pub struct CodegenContext {
355 // Resources needed when running LTO
356 pub time_passes: bool,
358 pub no_landing_pads: bool,
359 pub save_temps: bool,
360 pub fewer_names: bool,
361 pub exported_symbols: Option<Arc<ExportedSymbols>>,
362 pub opts: Arc<config::Options>,
363 pub crate_types: Vec<config::CrateType>,
364 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
365 output_filenames: Arc<OutputFilenames>,
366 regular_module_config: Arc<ModuleConfig>,
367 metadata_module_config: Arc<ModuleConfig>,
368 allocator_module_config: Arc<ModuleConfig>,
369 pub tm_factory: Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>,
370 pub msvc_imps_needed: bool,
371 pub target_pointer_width: String,
372 debuginfo: config::DebugInfo,
374 // Number of cgus excluding the allocator/metadata modules
375 pub total_cgus: usize,
376 // Handler to use for diagnostics produced during codegen.
377 pub diag_emitter: SharedEmitter,
378 // LLVM passes added by plugins.
379 pub plugin_passes: Vec<String>,
380 // LLVM optimizations for which we want to print remarks.
382 // Worker thread number
384 // The incremental compilation session directory, or None if we are not
385 // compiling incrementally
386 pub incr_comp_session_dir: Option<PathBuf>,
387 // Used to update CGU re-use information during the thinlto phase.
388 pub cgu_reuse_tracker: CguReuseTracker,
389 // Channel back to the main control thread to send messages to
390 coordinator_send: Sender<Box<dyn Any + Send>>,
391 // A reference to the TimeGraph so we can register timings. None means that
392 // measuring is disabled.
393 time_graph: Option<TimeGraph>,
394 // The assembler command if no_integrated_as option is enabled, None otherwise
395 assembler_cmd: Option<Arc<AssemblerCommand>>,
398 impl CodegenContext {
399 pub fn create_diag_handler(&self) -> Handler {
400 Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
403 pub(crate) fn config(&self, kind: ModuleKind) -> &ModuleConfig {
405 ModuleKind::Regular => &self.regular_module_config,
406 ModuleKind::Metadata => &self.metadata_module_config,
407 ModuleKind::Allocator => &self.allocator_module_config,
411 pub(crate) fn save_temp_bitcode(&self, module: &ModuleCodegen, name: &str) {
412 if !self.save_temps {
416 let ext = format!("{}.bc", name);
417 let cgu = Some(&module.name[..]);
418 let path = self.output_filenames.temp_path_ext(&ext, cgu);
419 let cstr = path2cstr(&path);
420 let llmod = module.module_llvm.llmod();
421 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
426 pub struct DiagnosticHandlers<'a> {
427 data: *mut (&'a CodegenContext, &'a Handler),
428 llcx: &'a llvm::Context,
431 impl<'a> DiagnosticHandlers<'a> {
432 pub fn new(cgcx: &'a CodegenContext,
433 handler: &'a Handler,
434 llcx: &'a llvm::Context) -> Self {
435 let data = Box::into_raw(Box::new((cgcx, handler)));
437 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
438 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
440 DiagnosticHandlers { data, llcx }
444 impl<'a> Drop for DiagnosticHandlers<'a> {
446 use std::ptr::null_mut;
448 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
449 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
450 drop(Box::from_raw(self.data));
455 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
458 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_owned());
461 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
467 let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
469 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
470 .expect("non-UTF8 SMDiagnostic");
472 report_inline_asm(cgcx, &msg, cookie);
475 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
479 let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
481 match llvm::diagnostic::Diagnostic::unpack(info) {
482 llvm::diagnostic::InlineAsm(inline) => {
483 report_inline_asm(cgcx,
484 &llvm::twine_to_string(inline.message),
488 llvm::diagnostic::Optimization(opt) => {
489 let enabled = match cgcx.remark {
491 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
495 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
504 llvm::diagnostic::PGO(diagnostic_ref) |
505 llvm::diagnostic::Linker(diagnostic_ref) => {
506 let msg = llvm::build_string(|s| {
507 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
508 }).expect("non-UTF8 diagnostic");
509 diag_handler.warn(&msg);
511 llvm::diagnostic::UnknownDiagnostic(..) => {},
515 // Unsafe due to LLVM calls.
516 unsafe fn optimize(cgcx: &CodegenContext,
517 diag_handler: &Handler,
518 module: &ModuleCodegen,
519 config: &ModuleConfig,
520 timeline: &mut Timeline)
521 -> Result<(), FatalError>
523 let llmod = module.module_llvm.llmod();
524 let llcx = &*module.module_llvm.llcx;
525 let tm = &*module.module_llvm.tm;
526 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
528 let module_name = module.name.clone();
529 let module_name = Some(&module_name[..]);
531 if config.emit_no_opt_bc {
532 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
533 let out = path2cstr(&out);
534 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
537 if config.opt_level.is_some() {
538 // Create the two optimizing pass managers. These mirror what clang
539 // does, and are by populated by LLVM's default PassManagerBuilder.
540 // Each manager has a different set of passes, but they also share
541 // some common passes.
542 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
543 let mpm = llvm::LLVMCreatePassManager();
546 // If we're verifying or linting, add them to the function pass
548 let addpass = |pass_name: &str| {
549 let pass_name = SmallCStr::new(pass_name);
550 let pass = match llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr()) {
552 None => return false,
554 let pass_manager = match llvm::LLVMRustPassKind(pass) {
555 llvm::PassKind::Function => &*fpm,
556 llvm::PassKind::Module => &*mpm,
557 llvm::PassKind::Other => {
558 diag_handler.err("Encountered LLVM pass kind we can't handle");
562 llvm::LLVMRustAddPass(pass_manager, pass);
566 if config.verify_llvm_ir { assert!(addpass("verify")); }
568 // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
569 // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
570 // we'll get errors in LLVM.
571 let using_thin_buffers = config.bitcode_needed();
572 let mut have_name_anon_globals_pass = false;
573 if !config.no_prepopulate_passes {
574 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
575 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
576 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
577 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal ||
578 (cgcx.lto != Lto::Fat && cgcx.opts.debugging_opts.cross_lang_lto.enabled());
579 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
580 if using_thin_buffers && !prepare_for_thin_lto {
581 assert!(addpass("name-anon-globals"));
582 have_name_anon_globals_pass = true;
584 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
585 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
586 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
590 for pass in &config.passes {
592 diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass));
594 if pass == "name-anon-globals" {
595 have_name_anon_globals_pass = true;
599 for pass in &cgcx.plugin_passes {
601 diag_handler.err(&format!("a plugin asked for LLVM pass \
602 `{}` but LLVM does not \
603 recognize it", pass));
605 if pass == "name-anon-globals" {
606 have_name_anon_globals_pass = true;
610 if using_thin_buffers && !have_name_anon_globals_pass {
611 // As described above, this will probably cause an error in LLVM
612 if config.no_prepopulate_passes {
613 diag_handler.err("The current compilation is going to use thin LTO buffers \
614 without running LLVM's NameAnonGlobals pass. \
615 This will likely cause errors in LLVM. Consider adding \
616 -C passes=name-anon-globals to the compiler command line.");
618 bug!("We are using thin LTO buffers without running the NameAnonGlobals pass. \
619 This will likely cause errors in LLVM and should never happen.");
624 diag_handler.abort_if_errors();
626 // Finally, run the actual optimization passes
627 time_ext(config.time_passes,
629 &format!("llvm function passes [{}]", module_name.unwrap()),
631 llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
633 timeline.record("fpm");
634 time_ext(config.time_passes,
636 &format!("llvm module passes [{}]", module_name.unwrap()),
638 llvm::LLVMRunPassManager(mpm, llmod)
641 // Deallocate managers that we're now done with
642 llvm::LLVMDisposePassManager(fpm);
643 llvm::LLVMDisposePassManager(mpm);
648 fn generate_lto_work(cgcx: &CodegenContext,
649 modules: Vec<ModuleCodegen>,
650 import_only_modules: Vec<(SerializedModule, WorkProduct)>)
651 -> Vec<(WorkItem, u64)>
653 let mut timeline = cgcx.time_graph.as_ref().map(|tg| {
654 tg.start(CODEGEN_WORKER_TIMELINE,
655 CODEGEN_WORK_PACKAGE_KIND,
657 }).unwrap_or(Timeline::noop());
658 let (lto_modules, copy_jobs) = lto::run(cgcx, modules, import_only_modules, &mut timeline)
659 .unwrap_or_else(|e| e.raise());
661 let lto_modules = lto_modules.into_iter().map(|module| {
662 let cost = module.cost();
663 (WorkItem::LTO(module), cost)
666 let copy_jobs = copy_jobs.into_iter().map(|wp| {
667 (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
668 name: wp.cgu_name.clone(),
673 lto_modules.chain(copy_jobs).collect()
676 unsafe fn codegen(cgcx: &CodegenContext,
677 diag_handler: &Handler,
678 module: ModuleCodegen,
679 config: &ModuleConfig,
680 timeline: &mut Timeline)
681 -> Result<CompiledModule, FatalError>
683 timeline.record("codegen");
685 let llmod = module.module_llvm.llmod();
686 let llcx = &*module.module_llvm.llcx;
687 let tm = &*module.module_llvm.tm;
688 let module_name = module.name.clone();
689 let module_name = Some(&module_name[..]);
690 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
692 if cgcx.msvc_imps_needed {
693 create_msvc_imps(cgcx, llcx, llmod);
696 // A codegen-specific pass manager is used to generate object
697 // files for an LLVM module.
699 // Apparently each of these pass managers is a one-shot kind of
700 // thing, so we create a new one for each type of output. The
701 // pass manager passed to the closure should be ensured to not
702 // escape the closure itself, and the manager should only be
704 unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine,
705 llmod: &'ll llvm::Module,
708 where F: FnOnce(&'ll mut PassManager<'ll>) -> R,
710 let cpm = llvm::LLVMCreatePassManager();
711 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
712 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
716 // If we don't have the integrated assembler, then we need to emit asm
717 // from LLVM and use `gcc` to create the object file.
718 let asm_to_obj = config.emit_obj && config.no_integrated_as;
720 // Change what we write and cleanup based on whether obj files are
721 // just llvm bitcode. In that case write bitcode, and possibly
722 // delete the bitcode if it wasn't requested. Don't generate the
723 // machine code, instead copy the .o file from the .bc
724 let write_bc = config.emit_bc || config.obj_is_bitcode;
725 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
726 let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
727 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
729 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
730 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
733 if write_bc || config.emit_bc_compressed || config.embed_bitcode {
734 let thin = ThinBuffer::new(llmod);
735 let data = thin.data();
736 timeline.record("make-bc");
739 if let Err(e) = fs::write(&bc_out, data) {
740 diag_handler.err(&format!("failed to write bytecode: {}", e));
742 timeline.record("write-bc");
745 if config.embed_bitcode {
746 embed_bitcode(cgcx, llcx, llmod, Some(data));
747 timeline.record("embed-bc");
750 if config.emit_bc_compressed {
751 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
752 let data = bytecode::encode(&module.name, data);
753 if let Err(e) = fs::write(&dst, data) {
754 diag_handler.err(&format!("failed to write bytecode: {}", e));
756 timeline.record("compress-bc");
758 } else if config.embed_bitcode_marker {
759 embed_bitcode(cgcx, llcx, llmod, None);
762 time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
763 || -> Result<(), FatalError> {
765 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
766 let out = path2cstr(&out);
768 extern "C" fn demangle_callback(input_ptr: *const c_char,
770 output_ptr: *mut c_char,
771 output_len: size_t) -> size_t {
773 slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
776 let input = match str::from_utf8(input) {
781 let output = unsafe {
782 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
784 let mut cursor = io::Cursor::new(output);
786 let demangled = match rustc_demangle::try_demangle(input) {
791 if let Err(_) = write!(cursor, "{:#}", demangled) {
792 // Possible only if provided buffer is not big enough
796 cursor.position() as size_t
799 with_codegen(tm, llmod, config.no_builtins, |cpm| {
800 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
801 llvm::LLVMDisposePassManager(cpm);
803 timeline.record("ir");
806 if config.emit_asm || asm_to_obj {
807 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
809 // We can't use the same module for asm and binary output, because that triggers
810 // various errors like invalid IR or broken binaries, so we might have to clone the
811 // module to produce the asm output
812 let llmod = if config.emit_obj {
813 llvm::LLVMCloneModule(llmod)
817 with_codegen(tm, llmod, config.no_builtins, |cpm| {
818 write_output_file(diag_handler, tm, cpm, llmod, &path,
819 llvm::FileType::AssemblyFile)
821 timeline.record("asm");
825 with_codegen(tm, llmod, config.no_builtins, |cpm| {
826 write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
827 llvm::FileType::ObjectFile)
829 timeline.record("obj");
830 } else if asm_to_obj {
831 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
832 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
833 timeline.record("asm_to_obj");
835 if !config.emit_asm && !cgcx.save_temps {
836 drop(fs::remove_file(&assembly));
844 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
845 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
846 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
851 debug!("removing_bitcode {:?}", bc_out);
852 if let Err(e) = fs::remove_file(&bc_out) {
853 diag_handler.err(&format!("failed to remove bitcode: {}", e));
859 Ok(module.into_compiled_module(config.emit_obj,
861 config.emit_bc_compressed,
862 &cgcx.output_filenames))
865 /// Embed the bitcode of an LLVM module in the LLVM module itself.
867 /// This is done primarily for iOS where it appears to be standard to compile C
868 /// code at least with `-fembed-bitcode` which creates two sections in the
871 /// * __LLVM,__bitcode
872 /// * __LLVM,__cmdline
874 /// It appears *both* of these sections are necessary to get the linker to
875 /// recognize what's going on. For us though we just always throw in an empty
878 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
879 /// embed an empty section.
881 /// Basically all of this is us attempting to follow in the footsteps of clang
882 /// on iOS. See #35968 for lots more info.
883 unsafe fn embed_bitcode(cgcx: &CodegenContext,
884 llcx: &llvm::Context,
885 llmod: &llvm::Module,
886 bitcode: Option<&[u8]>) {
887 let llconst = C_bytes_in_context(llcx, bitcode.unwrap_or(&[]));
888 let llglobal = llvm::LLVMAddGlobal(
891 "rustc.embedded.module\0".as_ptr() as *const _,
893 llvm::LLVMSetInitializer(llglobal, llconst);
895 let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
896 cgcx.opts.target_triple.triple().contains("-darwin");
898 let section = if is_apple {
903 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
904 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
905 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
907 let llconst = C_bytes_in_context(llcx, &[]);
908 let llglobal = llvm::LLVMAddGlobal(
911 "rustc.embedded.cmdline\0".as_ptr() as *const _,
913 llvm::LLVMSetInitializer(llglobal, llconst);
914 let section = if is_apple {
919 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
920 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
923 pub(crate) struct CompiledModules {
924 pub modules: Vec<CompiledModule>,
925 pub metadata_module: CompiledModule,
926 pub allocator_module: Option<CompiledModule>,
929 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
930 sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
931 sess.opts.output_types.contains_key(&OutputType::Exe)
934 fn need_pre_thin_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
935 if sess.opts.incremental.is_none() {
943 Lto::ThinLocal => true,
947 pub fn start_async_codegen(tcx: TyCtxt,
948 time_graph: Option<TimeGraph>,
949 metadata: EncodedMetadata,
950 coordinator_receive: Receiver<Box<dyn Any + Send>>,
954 let crate_name = tcx.crate_name(LOCAL_CRATE);
955 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
956 let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
957 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
958 "windows_subsystem");
959 let windows_subsystem = subsystem.map(|subsystem| {
960 if subsystem != "windows" && subsystem != "console" {
961 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
962 `windows` and `console` are allowed",
965 subsystem.to_string()
968 let linker_info = LinkerInfo::new(tcx);
969 let crate_info = CrateInfo::new(tcx);
971 // Figure out what we actually need to build.
972 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
973 let mut metadata_config = ModuleConfig::new(vec![]);
974 let mut allocator_config = ModuleConfig::new(vec![]);
976 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
978 Sanitizer::Address => {
979 modules_config.passes.push("asan".to_owned());
980 modules_config.passes.push("asan-module".to_owned());
982 Sanitizer::Memory => {
983 modules_config.passes.push("msan".to_owned())
985 Sanitizer::Thread => {
986 modules_config.passes.push("tsan".to_owned())
992 if sess.opts.debugging_opts.profile {
993 modules_config.passes.push("insert-gcov-profiling".to_owned())
996 modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
997 modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
999 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
1000 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
1002 // Save all versions of the bytecode if we're saving our temporaries.
1003 if sess.opts.cg.save_temps {
1004 modules_config.emit_no_opt_bc = true;
1005 modules_config.emit_pre_thin_lto_bc = true;
1006 modules_config.emit_bc = true;
1007 modules_config.emit_lto_bc = true;
1008 metadata_config.emit_bc = true;
1009 allocator_config.emit_bc = true;
1012 // Emit compressed bitcode files for the crate if we're emitting an rlib.
1013 // Whenever an rlib is created, the bitcode is inserted into the archive in
1014 // order to allow LTO against it.
1015 if need_crate_bitcode_for_rlib(sess) {
1016 modules_config.emit_bc_compressed = true;
1017 allocator_config.emit_bc_compressed = true;
1020 modules_config.emit_pre_thin_lto_bc =
1021 need_pre_thin_lto_bitcode_for_incr_comp(sess);
1023 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
1024 tcx.sess.target.target.options.no_integrated_as;
1026 for output_type in sess.opts.output_types.keys() {
1027 match *output_type {
1028 OutputType::Bitcode => { modules_config.emit_bc = true; }
1029 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
1030 OutputType::Assembly => {
1031 modules_config.emit_asm = true;
1032 // If we're not using the LLVM assembler, this function
1033 // could be invoked specially with output_type_assembly, so
1034 // in this case we still want the metadata object file.
1035 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
1036 metadata_config.emit_obj = true;
1037 allocator_config.emit_obj = true;
1040 OutputType::Object => { modules_config.emit_obj = true; }
1041 OutputType::Metadata => { metadata_config.emit_obj = true; }
1042 OutputType::Exe => {
1043 modules_config.emit_obj = true;
1044 metadata_config.emit_obj = true;
1045 allocator_config.emit_obj = true;
1047 OutputType::Mir => {}
1048 OutputType::DepInfo => {}
1052 modules_config.set_flags(sess, no_builtins);
1053 metadata_config.set_flags(sess, no_builtins);
1054 allocator_config.set_flags(sess, no_builtins);
1056 // Exclude metadata and allocator modules from time_passes output, since
1057 // they throw off the "LLVM passes" measurement.
1058 metadata_config.time_passes = false;
1059 allocator_config.time_passes = false;
1061 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
1062 let (codegen_worker_send, codegen_worker_receive) = channel();
1064 let coordinator_thread = start_executing_work(tcx,
1067 codegen_worker_send,
1068 coordinator_receive,
1070 sess.jobserver.clone(),
1072 Arc::new(modules_config),
1073 Arc::new(metadata_config),
1074 Arc::new(allocator_config));
1085 coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
1086 codegen_worker_receive,
1087 shared_emitter_main,
1088 future: coordinator_thread,
1089 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1093 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
1095 compiled_modules: &CompiledModules,
1096 ) -> FxHashMap<WorkProductId, WorkProduct> {
1097 let mut work_products = FxHashMap::default();
1099 if sess.opts.incremental.is_none() {
1100 return work_products;
1103 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
1104 let mut files = vec![];
1106 if let Some(ref path) = module.object {
1107 files.push((WorkProductFileKind::Object, path.clone()));
1109 if let Some(ref path) = module.bytecode {
1110 files.push((WorkProductFileKind::Bytecode, path.clone()));
1112 if let Some(ref path) = module.bytecode_compressed {
1113 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
1116 if let Some((id, product)) =
1117 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files)
1119 work_products.insert(id, product);
1126 fn produce_final_output_artifacts(sess: &Session,
1127 compiled_modules: &CompiledModules,
1128 crate_output: &OutputFilenames) {
1129 let mut user_wants_bitcode = false;
1130 let mut user_wants_objects = false;
1132 // Produce final compile outputs.
1133 let copy_gracefully = |from: &Path, to: &Path| {
1134 if let Err(e) = fs::copy(from, to) {
1135 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
1139 let copy_if_one_unit = |output_type: OutputType,
1140 keep_numbered: bool| {
1141 if compiled_modules.modules.len() == 1 {
1142 // 1) Only one codegen unit. In this case it's no difficulty
1143 // to copy `foo.0.x` to `foo.x`.
1144 let module_name = Some(&compiled_modules.modules[0].name[..]);
1145 let path = crate_output.temp_path(output_type, module_name);
1146 copy_gracefully(&path,
1147 &crate_output.path(output_type));
1148 if !sess.opts.cg.save_temps && !keep_numbered {
1149 // The user just wants `foo.x`, not `foo.#module-name#.x`.
1150 remove(sess, &path);
1153 let ext = crate_output.temp_path(output_type, None)
1160 if crate_output.outputs.contains_key(&output_type) {
1161 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
1162 // no good solution for this case, so warn the user.
1163 sess.warn(&format!("ignoring emit path because multiple .{} files \
1164 were produced", ext));
1165 } else if crate_output.single_output_file.is_some() {
1166 // 3) Multiple codegen units, with `-o some_name`. We have
1167 // no good solution for this case, so warn the user.
1168 sess.warn(&format!("ignoring -o because multiple .{} files \
1169 were produced", ext));
1171 // 4) Multiple codegen units, but no explicit name. We
1172 // just leave the `foo.0.x` files in place.
1173 // (We don't have to do any work in this case.)
1178 // Flag to indicate whether the user explicitly requested bitcode.
1179 // Otherwise, we produced it only as a temporary output, and will need
1180 // to get rid of it.
1181 for output_type in crate_output.outputs.keys() {
1182 match *output_type {
1183 OutputType::Bitcode => {
1184 user_wants_bitcode = true;
1185 // Copy to .bc, but always keep the .0.bc. There is a later
1186 // check to figure out if we should delete .0.bc files, or keep
1187 // them for making an rlib.
1188 copy_if_one_unit(OutputType::Bitcode, true);
1190 OutputType::LlvmAssembly => {
1191 copy_if_one_unit(OutputType::LlvmAssembly, false);
1193 OutputType::Assembly => {
1194 copy_if_one_unit(OutputType::Assembly, false);
1196 OutputType::Object => {
1197 user_wants_objects = true;
1198 copy_if_one_unit(OutputType::Object, true);
1201 OutputType::Metadata |
1203 OutputType::DepInfo => {}
1207 // Clean up unwanted temporary files.
1209 // We create the following files by default:
1210 // - #crate#.#module-name#.bc
1211 // - #crate#.#module-name#.o
1212 // - #crate#.crate.metadata.bc
1213 // - #crate#.crate.metadata.o
1214 // - #crate#.o (linked from crate.##.o)
1215 // - #crate#.bc (copied from crate.##.bc)
1216 // We may create additional files if requested by the user (through
1217 // `-C save-temps` or `--emit=` flags).
1219 if !sess.opts.cg.save_temps {
1220 // Remove the temporary .#module-name#.o objects. If the user didn't
1221 // explicitly request bitcode (with --emit=bc), and the bitcode is not
1222 // needed for building an rlib, then we must remove .#module-name#.bc as
1225 // Specific rules for keeping .#module-name#.bc:
1226 // - If the user requested bitcode (`user_wants_bitcode`), and
1227 // codegen_units > 1, then keep it.
1228 // - If the user requested bitcode but codegen_units == 1, then we
1229 // can toss .#module-name#.bc because we copied it to .bc earlier.
1230 // - If we're not building an rlib and the user didn't request
1231 // bitcode, then delete .#module-name#.bc.
1232 // If you change how this works, also update back::link::link_rlib,
1233 // where .#module-name#.bc files are (maybe) deleted after making an
1235 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
1237 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
1239 let keep_numbered_objects = needs_crate_object ||
1240 (user_wants_objects && sess.codegen_units() > 1);
1242 for module in compiled_modules.modules.iter() {
1243 if let Some(ref path) = module.object {
1244 if !keep_numbered_objects {
1249 if let Some(ref path) = module.bytecode {
1250 if !keep_numbered_bitcode {
1256 if !user_wants_bitcode {
1257 if let Some(ref path) = compiled_modules.metadata_module.bytecode {
1258 remove(sess, &path);
1261 if let Some(ref allocator_module) = compiled_modules.allocator_module {
1262 if let Some(ref path) = allocator_module.bytecode {
1269 // We leave the following files around by default:
1271 // - #crate#.crate.metadata.o
1273 // These are used in linking steps and will be cleaned up afterward.
1276 pub(crate) fn dump_incremental_data(_codegen_results: &CodegenResults) {
1277 // FIXME(mw): This does not work at the moment because the situation has
1278 // become more complicated due to incremental LTO. Now a CGU
1279 // can have more than two caching states.
1280 // println!("[incremental] Re-using {} out of {} modules",
1281 // codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
1282 // codegen_results.modules.len());
1286 /// Optimize a newly codegened, totally unoptimized module.
1287 Optimize(ModuleCodegen),
1288 /// Copy the post-LTO artifacts from the incremental cache to the output
1290 CopyPostLtoArtifacts(CachedModuleCodegen),
1291 /// Perform (Thin)LTO on the given module.
1292 LTO(lto::LtoModuleCodegen),
1296 fn module_kind(&self) -> ModuleKind {
1298 WorkItem::Optimize(ref m) => m.kind,
1299 WorkItem::CopyPostLtoArtifacts(_) |
1300 WorkItem::LTO(_) => ModuleKind::Regular,
1304 fn name(&self) -> String {
1306 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
1307 WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
1308 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
1313 enum WorkItemResult {
1314 Compiled(CompiledModule),
1315 NeedsLTO(ModuleCodegen),
1318 fn execute_work_item(cgcx: &CodegenContext,
1319 work_item: WorkItem,
1320 timeline: &mut Timeline)
1321 -> Result<WorkItemResult, FatalError>
1323 let module_config = cgcx.config(work_item.module_kind());
1326 WorkItem::Optimize(module) => {
1327 execute_optimize_work_item(cgcx, module, module_config, timeline)
1329 WorkItem::CopyPostLtoArtifacts(module) => {
1330 execute_copy_from_cache_work_item(cgcx, module, module_config, timeline)
1332 WorkItem::LTO(module) => {
1333 execute_lto_work_item(cgcx, module, module_config, timeline)
1338 fn execute_optimize_work_item(cgcx: &CodegenContext,
1339 module: ModuleCodegen,
1340 module_config: &ModuleConfig,
1341 timeline: &mut Timeline)
1342 -> Result<WorkItemResult, FatalError>
1344 let diag_handler = cgcx.create_diag_handler();
1347 optimize(cgcx, &diag_handler, &module, module_config, timeline)?;
1350 let linker_does_lto = cgcx.opts.debugging_opts.cross_lang_lto.enabled();
1352 // After we've done the initial round of optimizations we need to
1353 // decide whether to synchronously codegen this module or ship it
1354 // back to the coordinator thread for further LTO processing (which
1355 // has to wait for all the initial modules to be optimized).
1357 // Here we dispatch based on the `cgcx.lto` and kind of module we're
1359 let needs_lto = match cgcx.lto {
1362 // If the linker does LTO, we don't have to do it. Note that we
1363 // keep doing full LTO, if it is requested, as not to break the
1364 // assumption that the output will be a single module.
1365 Lto::Thin | Lto::ThinLocal if linker_does_lto => false,
1367 // Here we've got a full crate graph LTO requested. We ignore
1368 // this, however, if the crate type is only an rlib as there's
1369 // no full crate graph to process, that'll happen later.
1371 // This use case currently comes up primarily for targets that
1372 // require LTO so the request for LTO is always unconditionally
1373 // passed down to the backend, but we don't actually want to do
1374 // anything about it yet until we've got a final product.
1375 Lto::Fat | Lto::Thin => {
1376 cgcx.crate_types.len() != 1 ||
1377 cgcx.crate_types[0] != config::CrateType::Rlib
1380 // When we're automatically doing ThinLTO for multi-codegen-unit
1381 // builds we don't actually want to LTO the allocator modules if
1382 // it shows up. This is due to various linker shenanigans that
1383 // we'll encounter later.
1385 module.kind != ModuleKind::Allocator
1389 // Metadata modules never participate in LTO regardless of the lto
1391 let needs_lto = needs_lto && module.kind != ModuleKind::Metadata;
1394 Ok(WorkItemResult::NeedsLTO(module))
1396 let module = unsafe {
1397 codegen(cgcx, &diag_handler, module, module_config, timeline)?
1399 Ok(WorkItemResult::Compiled(module))
1403 fn execute_copy_from_cache_work_item(cgcx: &CodegenContext,
1404 module: CachedModuleCodegen,
1405 module_config: &ModuleConfig,
1407 -> Result<WorkItemResult, FatalError>
1409 let incr_comp_session_dir = cgcx.incr_comp_session_dir
1412 let mut object = None;
1413 let mut bytecode = None;
1414 let mut bytecode_compressed = None;
1415 for (kind, saved_file) in &module.source.saved_files {
1416 let obj_out = match kind {
1417 WorkProductFileKind::Object => {
1418 let path = cgcx.output_filenames.temp_path(OutputType::Object,
1419 Some(&module.name));
1420 object = Some(path.clone());
1423 WorkProductFileKind::Bytecode => {
1424 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1425 Some(&module.name));
1426 bytecode = Some(path.clone());
1429 WorkProductFileKind::BytecodeCompressed => {
1430 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1432 .with_extension(RLIB_BYTECODE_EXTENSION);
1433 bytecode_compressed = Some(path.clone());
1437 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1439 debug!("copying pre-existing module `{}` from {:?} to {}",
1443 if let Err(err) = link_or_copy(&source_file, &obj_out) {
1444 let diag_handler = cgcx.create_diag_handler();
1445 diag_handler.err(&format!("unable to copy {} to {}: {}",
1446 source_file.display(),
1452 assert_eq!(object.is_some(), module_config.emit_obj);
1453 assert_eq!(bytecode.is_some(), module_config.emit_bc);
1454 assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
1456 Ok(WorkItemResult::Compiled(CompiledModule {
1458 kind: ModuleKind::Regular,
1461 bytecode_compressed,
1465 fn execute_lto_work_item(cgcx: &CodegenContext,
1466 mut module: lto::LtoModuleCodegen,
1467 module_config: &ModuleConfig,
1468 timeline: &mut Timeline)
1469 -> Result<WorkItemResult, FatalError>
1471 let diag_handler = cgcx.create_diag_handler();
1474 let module = module.optimize(cgcx, timeline)?;
1475 let module = codegen(cgcx, &diag_handler, module, module_config, timeline)?;
1476 Ok(WorkItemResult::Compiled(module))
1481 Token(io::Result<Acquired>),
1483 result: ModuleCodegen,
1487 result: Result<CompiledModule, ()>,
1491 llvm_work_item: WorkItem,
1494 AddImportOnlyModule {
1495 module_data: SerializedModule,
1496 work_product: WorkProduct,
1505 code: Option<DiagnosticId>,
1509 #[derive(PartialEq, Clone, Copy, Debug)]
1510 enum MainThreadWorkerState {
1516 fn start_executing_work(tcx: TyCtxt,
1517 crate_info: &CrateInfo,
1518 shared_emitter: SharedEmitter,
1519 codegen_worker_send: Sender<Message>,
1520 coordinator_receive: Receiver<Box<dyn Any + Send>>,
1523 time_graph: Option<TimeGraph>,
1524 modules_config: Arc<ModuleConfig>,
1525 metadata_config: Arc<ModuleConfig>,
1526 allocator_config: Arc<ModuleConfig>)
1527 -> thread::JoinHandle<Result<CompiledModules, ()>> {
1528 let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1529 let sess = tcx.sess;
1531 // Compute the set of symbols we need to retain when doing LTO (if we need to)
1532 let exported_symbols = {
1533 let mut exported_symbols = FxHashMap::default();
1535 let copy_symbols = |cnum| {
1536 let symbols = tcx.exported_symbols(cnum)
1538 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1546 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1547 Some(Arc::new(exported_symbols))
1549 Lto::Fat | Lto::Thin => {
1550 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1551 for &cnum in tcx.crates().iter() {
1552 exported_symbols.insert(cnum, copy_symbols(cnum));
1554 Some(Arc::new(exported_symbols))
1559 // First up, convert our jobserver into a helper thread so we can use normal
1560 // mpsc channels to manage our messages and such.
1561 // After we've requested tokens then we'll, when we can,
1562 // get tokens on `coordinator_receive` which will
1563 // get managed in the main loop below.
1564 let coordinator_send2 = coordinator_send.clone();
1565 let helper = jobserver.into_helper_thread(move |token| {
1566 drop(coordinator_send2.send(Box::new(Message::Token(token))));
1567 }).expect("failed to spawn helper thread");
1569 let mut each_linked_rlib_for_lto = Vec::new();
1570 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1571 if link::ignored_for_lto(sess, crate_info, cnum) {
1574 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1577 let assembler_cmd = if modules_config.no_integrated_as {
1578 // HACK: currently we use linker (gcc) as our assembler
1579 let (linker, flavor) = link::linker_and_flavor(sess);
1581 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1582 cmd.args(&sess.target.target.options.asm_args);
1584 Some(Arc::new(AssemblerCommand { name, cmd }))
1589 let cgcx = CodegenContext {
1590 crate_types: sess.crate_types.borrow().clone(),
1591 each_linked_rlib_for_lto,
1593 no_landing_pads: sess.no_landing_pads(),
1594 fewer_names: sess.fewer_names(),
1595 save_temps: sess.opts.cg.save_temps,
1596 opts: Arc::new(sess.opts.clone()),
1597 time_passes: sess.time_passes(),
1599 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1600 remark: sess.opts.cg.remark.clone(),
1602 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1603 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1605 diag_emitter: shared_emitter.clone(),
1607 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1608 regular_module_config: modules_config,
1609 metadata_module_config: metadata_config,
1610 allocator_module_config: allocator_config,
1611 tm_factory: target_machine_factory(tcx.sess, false),
1613 msvc_imps_needed: msvc_imps_needed(tcx),
1614 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1615 debuginfo: tcx.sess.opts.debuginfo,
1619 // This is the "main loop" of parallel work happening for parallel codegen.
1620 // It's here that we manage parallelism, schedule work, and work with
1621 // messages coming from clients.
1623 // There are a few environmental pre-conditions that shape how the system
1626 // - Error reporting only can happen on the main thread because that's the
1627 // only place where we have access to the compiler `Session`.
1628 // - LLVM work can be done on any thread.
1629 // - Codegen can only happen on the main thread.
1630 // - Each thread doing substantial work most be in possession of a `Token`
1631 // from the `Jobserver`.
1632 // - The compiler process always holds one `Token`. Any additional `Tokens`
1633 // have to be requested from the `Jobserver`.
1637 // The error reporting restriction is handled separately from the rest: We
1638 // set up a `SharedEmitter` the holds an open channel to the main thread.
1639 // When an error occurs on any thread, the shared emitter will send the
1640 // error message to the receiver main thread (`SharedEmitterMain`). The
1641 // main thread will periodically query this error message queue and emit
1642 // any error messages it has received. It might even abort compilation if
1643 // has received a fatal error. In this case we rely on all other threads
1644 // being torn down automatically with the main thread.
1645 // Since the main thread will often be busy doing codegen work, error
1646 // reporting will be somewhat delayed, since the message queue can only be
1647 // checked in between to work packages.
1649 // Work Processing Infrastructure
1650 // ==============================
1651 // The work processing infrastructure knows three major actors:
1653 // - the coordinator thread,
1654 // - the main thread, and
1655 // - LLVM worker threads
1657 // The coordinator thread is running a message loop. It instructs the main
1658 // thread about what work to do when, and it will spawn off LLVM worker
1659 // threads as open LLVM WorkItems become available.
1661 // The job of the main thread is to codegen CGUs into LLVM work package
1662 // (since the main thread is the only thread that can do this). The main
1663 // thread will block until it receives a message from the coordinator, upon
1664 // which it will codegen one CGU, send it to the coordinator and block
1665 // again. This way the coordinator can control what the main thread is
1668 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1669 // available, it will spawn off a new LLVM worker thread and let it process
1670 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1671 // it will just shut down, which also frees all resources associated with
1672 // the given LLVM module, and sends a message to the coordinator that the
1673 // has been completed.
1677 // The scheduler's goal is to minimize the time it takes to complete all
1678 // work there is, however, we also want to keep memory consumption low
1679 // if possible. These two goals are at odds with each other: If memory
1680 // consumption were not an issue, we could just let the main thread produce
1681 // LLVM WorkItems at full speed, assuring maximal utilization of
1682 // Tokens/LLVM worker threads. However, since codegen usual is faster
1683 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1684 // WorkItem potentially holds on to a substantial amount of memory.
1686 // So the actual goal is to always produce just enough LLVM WorkItems as
1687 // not to starve our LLVM worker threads. That means, once we have enough
1688 // WorkItems in our queue, we can block the main thread, so it does not
1689 // produce more until we need them.
1691 // Doing LLVM Work on the Main Thread
1692 // ----------------------------------
1693 // Since the main thread owns the compiler processes implicit `Token`, it is
1694 // wasteful to keep it blocked without doing any work. Therefore, what we do
1695 // in this case is: We spawn off an additional LLVM worker thread that helps
1696 // reduce the queue. The work it is doing corresponds to the implicit
1697 // `Token`. The coordinator will mark the main thread as being busy with
1698 // LLVM work. (The actual work happens on another OS thread but we just care
1699 // about `Tokens`, not actual threads).
1701 // When any LLVM worker thread finishes while the main thread is marked as
1702 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1703 // of the just finished thread to the LLVM worker thread that is working on
1704 // behalf of the main thread's implicit Token, thus freeing up the main
1705 // thread again. The coordinator can then again decide what the main thread
1706 // should do. This allows the coordinator to make decisions at more points
1709 // Striking a Balance between Throughput and Memory Consumption
1710 // ------------------------------------------------------------
1711 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1712 // memory consumption as low as possible, are in conflict with each other,
1713 // we have to find a trade off between them. Right now, the goal is to keep
1714 // all workers busy, which means that no worker should find the queue empty
1715 // when it is ready to start.
1716 // How do we do achieve this? Good question :) We actually never know how
1717 // many `Tokens` are potentially available so it's hard to say how much to
1718 // fill up the queue before switching the main thread to LLVM work. Also we
1719 // currently don't have a means to estimate how long a running LLVM worker
1720 // will still be busy with it's current WorkItem. However, we know the
1721 // maximal count of available Tokens that makes sense (=the number of CPU
1722 // cores), so we can take a conservative guess. The heuristic we use here
1723 // is implemented in the `queue_full_enough()` function.
1725 // Some Background on Jobservers
1726 // -----------------------------
1727 // It's worth also touching on the management of parallelism here. We don't
1728 // want to just spawn a thread per work item because while that's optimal
1729 // parallelism it may overload a system with too many threads or violate our
1730 // configuration for the maximum amount of cpu to use for this process. To
1731 // manage this we use the `jobserver` crate.
1733 // Job servers are an artifact of GNU make and are used to manage
1734 // parallelism between processes. A jobserver is a glorified IPC semaphore
1735 // basically. Whenever we want to run some work we acquire the semaphore,
1736 // and whenever we're done with that work we release the semaphore. In this
1737 // manner we can ensure that the maximum number of parallel workers is
1738 // capped at any one point in time.
1740 // LTO and the coordinator thread
1741 // ------------------------------
1743 // The final job the coordinator thread is responsible for is managing LTO
1744 // and how that works. When LTO is requested what we'll to is collect all
1745 // optimized LLVM modules into a local vector on the coordinator. Once all
1746 // modules have been codegened and optimized we hand this to the `lto`
1747 // module for further optimization. The `lto` module will return back a list
1748 // of more modules to work on, which the coordinator will continue to spawn
1751 // Each LLVM module is automatically sent back to the coordinator for LTO if
1752 // necessary. There's already optimizations in place to avoid sending work
1753 // back to the coordinator if LTO isn't requested.
1754 return thread::spawn(move || {
1755 // We pretend to be within the top-level LLVM time-passes task here:
1758 let max_workers = ::num_cpus::get();
1759 let mut worker_id_counter = 0;
1760 let mut free_worker_ids = Vec::new();
1761 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1762 if let Some(id) = free_worker_ids.pop() {
1765 let id = worker_id_counter;
1766 worker_id_counter += 1;
1771 // This is where we collect codegen units that have gone all the way
1772 // through codegen and LLVM.
1773 let mut compiled_modules = vec![];
1774 let mut compiled_metadata_module = None;
1775 let mut compiled_allocator_module = None;
1776 let mut needs_lto = Vec::new();
1777 let mut lto_import_only_modules = Vec::new();
1778 let mut started_lto = false;
1779 let mut codegen_aborted = false;
1781 // This flag tracks whether all items have gone through codegens
1782 let mut codegen_done = false;
1784 // This is the queue of LLVM work items that still need processing.
1785 let mut work_items = Vec::<(WorkItem, u64)>::new();
1787 // This are the Jobserver Tokens we currently hold. Does not include
1788 // the implicit Token the compiler process owns no matter what.
1789 let mut tokens = Vec::new();
1791 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1792 let mut running = 0;
1794 let mut llvm_start_time = None;
1796 // Run the message loop while there's still anything that needs message
1797 // processing. Note that as soon as codegen is aborted we simply want to
1798 // wait for all existing work to finish, so many of the conditions here
1799 // only apply if codegen hasn't been aborted as they represent pending
1801 while !codegen_done ||
1803 (!codegen_aborted && (
1804 work_items.len() > 0 ||
1805 needs_lto.len() > 0 ||
1806 lto_import_only_modules.len() > 0 ||
1807 main_thread_worker_state != MainThreadWorkerState::Idle
1811 // While there are still CGUs to be codegened, the coordinator has
1812 // to decide how to utilize the compiler processes implicit Token:
1813 // For codegenning more CGU or for running them through LLVM.
1815 if main_thread_worker_state == MainThreadWorkerState::Idle {
1816 if !queue_full_enough(work_items.len(), running, max_workers) {
1817 // The queue is not full enough, codegen more items:
1818 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1819 panic!("Could not send Message::CodegenItem to main thread")
1821 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1823 // The queue is full enough to not let the worker
1824 // threads starve. Use the implicit Token to do some
1826 let (item, _) = work_items.pop()
1827 .expect("queue empty - queue_full_enough() broken?");
1828 let cgcx = CodegenContext {
1829 worker: get_worker_id(&mut free_worker_ids),
1832 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1833 &mut llvm_start_time);
1834 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1835 spawn_work(cgcx, item);
1838 } else if codegen_aborted {
1839 // don't queue up any more work if codegen was aborted, we're
1840 // just waiting for our existing children to finish
1842 // If we've finished everything related to normal codegen
1843 // then it must be the case that we've got some LTO work to do.
1844 // Perform the serial work here of figuring out what we're
1845 // going to LTO and then push a bunch of work items onto our
1847 if work_items.len() == 0 &&
1849 main_thread_worker_state == MainThreadWorkerState::Idle {
1850 assert!(!started_lto);
1851 assert!(needs_lto.len() + lto_import_only_modules.len() > 0);
1853 let modules = mem::replace(&mut needs_lto, Vec::new());
1854 let import_only_modules =
1855 mem::replace(&mut lto_import_only_modules, Vec::new());
1856 for (work, cost) in generate_lto_work(&cgcx, modules, import_only_modules) {
1857 let insertion_index = work_items
1858 .binary_search_by_key(&cost, |&(_, cost)| cost)
1859 .unwrap_or_else(|e| e);
1860 work_items.insert(insertion_index, (work, cost));
1861 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1862 helper.request_token();
1867 // In this branch, we know that everything has been codegened,
1868 // so it's just a matter of determining whether the implicit
1869 // Token is free to use for LLVM work.
1870 match main_thread_worker_state {
1871 MainThreadWorkerState::Idle => {
1872 if let Some((item, _)) = work_items.pop() {
1873 let cgcx = CodegenContext {
1874 worker: get_worker_id(&mut free_worker_ids),
1877 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1878 &mut llvm_start_time);
1879 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1880 spawn_work(cgcx, item);
1882 // There is no unstarted work, so let the main thread
1883 // take over for a running worker. Otherwise the
1884 // implicit token would just go to waste.
1885 // We reduce the `running` counter by one. The
1886 // `tokens.truncate()` below will take care of
1887 // giving the Token back.
1888 debug_assert!(running > 0);
1890 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1893 MainThreadWorkerState::Codegenning => {
1894 bug!("codegen worker should not be codegenning after \
1895 codegen was already completed")
1897 MainThreadWorkerState::LLVMing => {
1898 // Already making good use of that token
1903 // Spin up what work we can, only doing this while we've got available
1904 // parallelism slots and work left to spawn.
1905 while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1906 let (item, _) = work_items.pop().unwrap();
1908 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1909 &mut llvm_start_time);
1911 let cgcx = CodegenContext {
1912 worker: get_worker_id(&mut free_worker_ids),
1916 spawn_work(cgcx, item);
1920 // Relinquish accidentally acquired extra tokens
1921 tokens.truncate(running);
1923 let msg = coordinator_receive.recv().unwrap();
1924 match *msg.downcast::<Message>().ok().unwrap() {
1925 // Save the token locally and the next turn of the loop will use
1926 // this to spawn a new unit of work, or it may get dropped
1927 // immediately if we have no more work to spawn.
1928 Message::Token(token) => {
1933 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1934 // If the main thread token is used for LLVM work
1935 // at the moment, we turn that thread into a regular
1936 // LLVM worker thread, so the main thread is free
1937 // to react to codegen demand.
1938 main_thread_worker_state = MainThreadWorkerState::Idle;
1943 let msg = &format!("failed to acquire jobserver token: {}", e);
1944 shared_emitter.fatal(msg);
1945 // Exit the coordinator thread
1951 Message::CodegenDone { llvm_work_item, cost } => {
1952 // We keep the queue sorted by estimated processing cost,
1953 // so that more expensive items are processed earlier. This
1954 // is good for throughput as it gives the main thread more
1955 // time to fill up the queue and it avoids scheduling
1956 // expensive items to the end.
1957 // Note, however, that this is not ideal for memory
1958 // consumption, as LLVM module sizes are not evenly
1960 let insertion_index =
1961 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1962 let insertion_index = match insertion_index {
1963 Ok(idx) | Err(idx) => idx
1965 work_items.insert(insertion_index, (llvm_work_item, cost));
1967 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1968 helper.request_token();
1970 assert!(!codegen_aborted);
1971 assert_eq!(main_thread_worker_state,
1972 MainThreadWorkerState::Codegenning);
1973 main_thread_worker_state = MainThreadWorkerState::Idle;
1976 Message::CodegenComplete => {
1977 codegen_done = true;
1978 assert!(!codegen_aborted);
1979 assert_eq!(main_thread_worker_state,
1980 MainThreadWorkerState::Codegenning);
1981 main_thread_worker_state = MainThreadWorkerState::Idle;
1984 // If codegen is aborted that means translation was aborted due
1985 // to some normal-ish compiler error. In this situation we want
1986 // to exit as soon as possible, but we want to make sure all
1987 // existing work has finished. Flag codegen as being done, and
1988 // then conditions above will ensure no more work is spawned but
1989 // we'll keep executing this loop until `running` hits 0.
1990 Message::CodegenAborted => {
1991 assert!(!codegen_aborted);
1992 codegen_done = true;
1993 codegen_aborted = true;
1994 assert_eq!(main_thread_worker_state,
1995 MainThreadWorkerState::Codegenning);
1998 // If a thread exits successfully then we drop a token associated
1999 // with that worker and update our `running` count. We may later
2000 // re-acquire a token to continue running more work. We may also not
2001 // actually drop a token here if the worker was running with an
2002 // "ephemeral token"
2004 // Note that if the thread failed that means it panicked, so we
2005 // abort immediately.
2006 Message::Done { result: Ok(compiled_module), worker_id } => {
2007 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
2008 main_thread_worker_state = MainThreadWorkerState::Idle;
2013 free_worker_ids.push(worker_id);
2015 match compiled_module.kind {
2016 ModuleKind::Regular => {
2017 compiled_modules.push(compiled_module);
2019 ModuleKind::Metadata => {
2020 assert!(compiled_metadata_module.is_none());
2021 compiled_metadata_module = Some(compiled_module);
2023 ModuleKind::Allocator => {
2024 assert!(compiled_allocator_module.is_none());
2025 compiled_allocator_module = Some(compiled_module);
2029 Message::NeedsLTO { result, worker_id } => {
2030 assert!(!started_lto);
2031 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
2032 main_thread_worker_state = MainThreadWorkerState::Idle;
2036 free_worker_ids.push(worker_id);
2037 needs_lto.push(result);
2039 Message::AddImportOnlyModule { module_data, work_product } => {
2040 assert!(!started_lto);
2041 assert!(!codegen_done);
2042 assert_eq!(main_thread_worker_state,
2043 MainThreadWorkerState::Codegenning);
2044 lto_import_only_modules.push((module_data, work_product));
2045 main_thread_worker_state = MainThreadWorkerState::Idle;
2047 Message::Done { result: Err(()), worker_id: _ } => {
2048 bug!("worker thread panicked");
2050 Message::CodegenItem => {
2051 bug!("the coordinator should not receive codegen requests")
2056 if let Some(llvm_start_time) = llvm_start_time {
2057 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
2058 // This is the top-level timing for all of LLVM, set the time-depth
2061 print_time_passes_entry(cgcx.time_passes,
2066 // Regardless of what order these modules completed in, report them to
2067 // the backend in the same order every time to ensure that we're handing
2068 // out deterministic results.
2069 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
2071 let compiled_metadata_module = compiled_metadata_module
2072 .expect("Metadata module not compiled?");
2074 Ok(CompiledModules {
2075 modules: compiled_modules,
2076 metadata_module: compiled_metadata_module,
2077 allocator_module: compiled_allocator_module,
2081 // A heuristic that determines if we have enough LLVM WorkItems in the
2082 // queue so that the main thread can do LLVM work instead of codegen
2083 fn queue_full_enough(items_in_queue: usize,
2084 workers_running: usize,
2085 max_workers: usize) -> bool {
2087 items_in_queue > 0 &&
2088 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
2091 fn maybe_start_llvm_timer(config: &ModuleConfig,
2092 llvm_start_time: &mut Option<Instant>) {
2093 // We keep track of the -Ztime-passes output manually,
2094 // since the closure-based interface does not fit well here.
2095 if config.time_passes {
2096 if llvm_start_time.is_none() {
2097 *llvm_start_time = Some(Instant::now());
2103 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
2104 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
2105 time_graph::TimelineId(CODEGEN_WORKER_ID);
2106 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2107 time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
2108 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2109 time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
2111 fn spawn_work(cgcx: CodegenContext, work: WorkItem) {
2112 let depth = time_depth();
2114 thread::spawn(move || {
2115 set_time_depth(depth);
2117 // Set up a destructor which will fire off a message that we're done as
2120 coordinator_send: Sender<Box<dyn Any + Send>>,
2121 result: Option<WorkItemResult>,
2124 impl Drop for Bomb {
2125 fn drop(&mut self) {
2126 let worker_id = self.worker_id;
2127 let msg = match self.result.take() {
2128 Some(WorkItemResult::Compiled(m)) => {
2129 Message::Done { result: Ok(m), worker_id }
2131 Some(WorkItemResult::NeedsLTO(m)) => {
2132 Message::NeedsLTO { result: m, worker_id }
2134 None => Message::Done { result: Err(()), worker_id }
2136 drop(self.coordinator_send.send(Box::new(msg)));
2140 let mut bomb = Bomb {
2141 coordinator_send: cgcx.coordinator_send.clone(),
2143 worker_id: cgcx.worker,
2146 // Execute the work itself, and if it finishes successfully then flag
2147 // ourselves as a success as well.
2149 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
2150 // as a diagnostic was already sent off to the main thread - just
2151 // surface that there was an error in this worker.
2153 let timeline = cgcx.time_graph.as_ref().map(|tg| {
2154 tg.start(time_graph::TimelineId(cgcx.worker),
2155 LLVM_WORK_PACKAGE_KIND,
2158 let mut timeline = timeline.unwrap_or(Timeline::noop());
2159 execute_work_item(&cgcx, work, &mut timeline).ok()
2164 pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, object: &Path) {
2165 let assembler = cgcx.assembler_cmd
2167 .expect("cgcx.assembler_cmd is missing?");
2169 let pname = &assembler.name;
2170 let mut cmd = assembler.cmd.clone();
2171 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
2172 debug!("{:?}", cmd);
2174 match cmd.output() {
2176 if !prog.status.success() {
2177 let mut note = prog.stderr.clone();
2178 note.extend_from_slice(&prog.stdout);
2180 handler.struct_err(&format!("linking with `{}` failed: {}",
2183 .note(&format!("{:?}", &cmd))
2184 .note(str::from_utf8(¬e[..]).unwrap())
2186 handler.abort_if_errors();
2190 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
2191 handler.abort_if_errors();
2196 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
2197 config: &ModuleConfig,
2198 opt_level: llvm::CodeGenOptLevel,
2199 prepare_for_thin_lto: bool,
2200 f: &mut dyn FnMut(&llvm::PassManagerBuilder)) {
2203 // Create the PassManagerBuilder for LLVM. We configure it with
2204 // reasonable defaults and prepare it to actually populate the pass
2206 let builder = llvm::LLVMPassManagerBuilderCreate();
2207 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
2208 let inline_threshold = config.inline_threshold;
2210 let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
2211 let s = if s.is_empty() { "default_%m.profraw" } else { s };
2212 CString::new(s.as_bytes()).unwrap()
2215 let pgo_use_path = if config.pgo_use.is_empty() {
2218 Some(CString::new(config.pgo_use.as_bytes()).unwrap())
2221 llvm::LLVMRustConfigurePassManagerBuilder(
2224 config.merge_functions,
2225 config.vectorize_slp,
2226 config.vectorize_loop,
2227 prepare_for_thin_lto,
2228 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2229 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2232 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
2234 if opt_size != llvm::CodeGenOptSizeNone {
2235 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
2238 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
2240 // Here we match what clang does (kinda). For O0 we only inline
2241 // always-inline functions (but don't add lifetime intrinsics), at O1 we
2242 // inline with lifetime intrinsics, and O2+ we add an inliner with a
2243 // thresholds copied from clang.
2244 match (opt_level, opt_size, inline_threshold) {
2246 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
2248 (llvm::CodeGenOptLevel::Aggressive, ..) => {
2249 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
2251 (_, llvm::CodeGenOptSizeDefault, _) => {
2252 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
2254 (_, llvm::CodeGenOptSizeAggressive, _) => {
2255 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
2257 (llvm::CodeGenOptLevel::None, ..) => {
2258 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
2260 (llvm::CodeGenOptLevel::Less, ..) => {
2261 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
2263 (llvm::CodeGenOptLevel::Default, ..) => {
2264 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
2266 (llvm::CodeGenOptLevel::Other, ..) => {
2267 bug!("CodeGenOptLevel::Other selected")
2272 llvm::LLVMPassManagerBuilderDispose(builder);
2276 enum SharedEmitterMessage {
2277 Diagnostic(Diagnostic),
2278 InlineAsmError(u32, String),
2284 pub struct SharedEmitter {
2285 sender: Sender<SharedEmitterMessage>,
2288 pub struct SharedEmitterMain {
2289 receiver: Receiver<SharedEmitterMessage>,
2292 impl SharedEmitter {
2293 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
2294 let (sender, receiver) = channel();
2296 (SharedEmitter { sender }, SharedEmitterMain { receiver })
2299 fn inline_asm_error(&self, cookie: u32, msg: String) {
2300 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
2303 fn fatal(&self, msg: &str) {
2304 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2308 impl Emitter for SharedEmitter {
2309 fn emit(&mut self, db: &DiagnosticBuilder) {
2310 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2312 code: db.code.clone(),
2315 for child in &db.children {
2316 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2317 msg: child.message(),
2322 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
2326 impl SharedEmitterMain {
2327 pub fn check(&self, sess: &Session, blocking: bool) {
2329 let message = if blocking {
2330 match self.receiver.recv() {
2331 Ok(message) => Ok(message),
2335 match self.receiver.try_recv() {
2336 Ok(message) => Ok(message),
2342 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2343 let handler = sess.diagnostic();
2346 handler.emit_with_code(&MultiSpan::new(),
2352 handler.emit(&MultiSpan::new(),
2358 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
2359 match Mark::from_u32(cookie).expn_info() {
2360 Some(ei) => sess.span_err(ei.call_site, &msg),
2361 None => sess.err(&msg),
2364 Ok(SharedEmitterMessage::AbortIfErrors) => {
2365 sess.abort_if_errors();
2367 Ok(SharedEmitterMessage::Fatal(msg)) => {
2379 pub struct OngoingCodegen {
2382 metadata: EncodedMetadata,
2383 windows_subsystem: Option<String>,
2384 linker_info: LinkerInfo,
2385 crate_info: CrateInfo,
2386 time_graph: Option<TimeGraph>,
2387 coordinator_send: Sender<Box<dyn Any + Send>>,
2388 codegen_worker_receive: Receiver<Message>,
2389 shared_emitter_main: SharedEmitterMain,
2390 future: thread::JoinHandle<Result<CompiledModules, ()>>,
2391 output_filenames: Arc<OutputFilenames>,
2394 impl OngoingCodegen {
2398 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
2399 self.shared_emitter_main.check(sess, true);
2400 let compiled_modules = match self.future.join() {
2401 Ok(Ok(compiled_modules)) => compiled_modules,
2403 sess.abort_if_errors();
2404 panic!("expected abort due to worker thread errors")
2407 bug!("panic during codegen/LLVM phase");
2411 sess.cgu_reuse_tracker.check_expected_reuse(sess);
2413 sess.abort_if_errors();
2415 if let Some(time_graph) = self.time_graph {
2416 time_graph.dump(&format!("{}-timings", self.crate_name));
2420 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
2422 produce_final_output_artifacts(sess,
2424 &self.output_filenames);
2426 // FIXME: time_llvm_passes support - does this use a global context or
2428 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2429 unsafe { llvm::LLVMRustPrintPassTimings(); }
2433 crate_name: self.crate_name,
2434 crate_hash: self.crate_hash,
2435 metadata: self.metadata,
2436 windows_subsystem: self.windows_subsystem,
2437 linker_info: self.linker_info,
2438 crate_info: self.crate_info,
2440 modules: compiled_modules.modules,
2441 allocator_module: compiled_modules.allocator_module,
2442 metadata_module: compiled_modules.metadata_module,
2446 pub(crate) fn submit_pre_codegened_module_to_llvm(&self,
2448 module: ModuleCodegen) {
2449 self.wait_for_signal_to_codegen_item();
2450 self.check_for_errors(tcx.sess);
2452 // These are generally cheap and won't through off scheduling.
2454 submit_codegened_module_to_llvm(tcx, module, cost);
2457 pub fn codegen_finished(&self, tcx: TyCtxt) {
2458 self.wait_for_signal_to_codegen_item();
2459 self.check_for_errors(tcx.sess);
2460 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete)));
2463 /// Consume this context indicating that codegen was entirely aborted, and
2464 /// we need to exit as quickly as possible.
2466 /// This method blocks the current thread until all worker threads have
2467 /// finished, and all worker threads should have exited or be real close to
2468 /// exiting at this point.
2469 pub fn codegen_aborted(self) {
2470 // Signal to the coordinator it should spawn no more work and start
2472 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted)));
2473 drop(self.future.join());
2476 pub fn check_for_errors(&self, sess: &Session) {
2477 self.shared_emitter_main.check(sess, false);
2480 pub fn wait_for_signal_to_codegen_item(&self) {
2481 match self.codegen_worker_receive.recv() {
2482 Ok(Message::CodegenItem) => {
2485 Ok(_) => panic!("unexpected message"),
2487 // One of the LLVM threads must have panicked, fall through so
2488 // error handling can be reached.
2494 // impl Drop for OngoingCodegen {
2495 // fn drop(&mut self) {
2499 pub(crate) fn submit_codegened_module_to_llvm(tcx: TyCtxt,
2500 module: ModuleCodegen,
2502 let llvm_work_item = WorkItem::Optimize(module);
2503 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2509 pub(crate) fn submit_post_lto_module_to_llvm(tcx: TyCtxt,
2510 module: CachedModuleCodegen) {
2511 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2512 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2518 pub(crate) fn submit_pre_lto_module_to_llvm(tcx: TyCtxt,
2519 module: CachedModuleCodegen) {
2520 let filename = pre_lto_bitcode_filename(&module.name);
2521 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2522 let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
2523 panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
2527 memmap::Mmap::map(&file).unwrap_or_else(|e| {
2528 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2532 // Schedule the module to be loaded
2533 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::AddImportOnlyModule {
2534 module_data: SerializedModule::FromUncompressedFile(mmap),
2535 work_product: module.source,
2539 pub(super) fn pre_lto_bitcode_filename(module_name: &str) -> String {
2540 format!("{}.{}", module_name, PRE_THIN_LTO_BC_EXT)
2543 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2544 // This should never be true (because it's not supported). If it is true,
2545 // something is wrong with commandline arg validation.
2546 assert!(!(tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() &&
2547 tcx.sess.target.target.options.is_like_msvc &&
2548 tcx.sess.opts.cg.prefer_dynamic));
2550 tcx.sess.target.target.options.is_like_msvc &&
2551 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
2552 // ThinLTO can't handle this workaround in all cases, so we don't
2553 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2554 // dynamic linking when cross-language LTO is enabled.
2555 !tcx.sess.opts.debugging_opts.cross_lang_lto.enabled()
2558 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2559 // This is required to satisfy `dllimport` references to static data in .rlibs
2560 // when using MSVC linker. We do this only for data, as linker can fix up
2561 // code references on its own.
2562 // See #26591, #27438
2563 fn create_msvc_imps(cgcx: &CodegenContext, llcx: &llvm::Context, llmod: &llvm::Module) {
2564 if !cgcx.msvc_imps_needed {
2567 // The x86 ABI seems to require that leading underscores are added to symbol
2568 // names, so we need an extra underscore on 32-bit. There's also a leading
2569 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2570 // underscores added in front).
2571 let prefix = if cgcx.target_pointer_width == "32" {
2577 let i8p_ty = Type::i8p_llcx(llcx);
2578 let globals = base::iter_globals(llmod)
2580 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
2581 llvm::LLVMIsDeclaration(val) == 0
2584 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2585 let mut imp_name = prefix.as_bytes().to_vec();
2586 imp_name.extend(name.to_bytes());
2587 let imp_name = CString::new(imp_name).unwrap();
2590 .collect::<Vec<_>>();
2591 for (imp_name, val) in globals {
2592 let imp = llvm::LLVMAddGlobal(llmod,
2594 imp_name.as_ptr() as *const _);
2595 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
2596 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);