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, ModuleBuffer, ThinBuffer, SerializedModule};
14 use back::link::{self, get_linker, remove};
15 use back::command::Command;
16 use back::linker::LinkerInfo;
17 use back::symbol_export::ExportedSymbols;
21 use rustc_incremental::{copy_cgu_workproducts_to_incr_comp_cache_dir,
22 in_incr_comp_dir, in_incr_comp_dir_sess};
23 use rustc::dep_graph::{WorkProduct, WorkProductId, WorkProductFileKind};
24 use rustc::middle::cstore::EncodedMetadata;
25 use rustc::session::config::{self, OutputFilenames, OutputType, Passes, Sanitizer, Lto};
26 use rustc::session::Session;
27 use rustc::util::nodemap::FxHashMap;
28 use time_graph::{self, TimeGraph, Timeline};
29 use llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
31 use {CodegenResults, ModuleCodegen, CompiledModule, ModuleKind, // ModuleLlvm,
34 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
35 use rustc::ty::TyCtxt;
36 use rustc::util::common::{time_ext, time_depth, set_time_depth, print_time_passes_entry};
37 use rustc_fs_util::{path2cstr, link_or_copy};
38 use rustc_data_structures::small_c_str::SmallCStr;
39 use rustc_data_structures::svh::Svh;
40 use errors::{self, Handler, Level, DiagnosticBuilder, FatalError, DiagnosticId};
41 use errors::emitter::{Emitter};
43 use syntax::ext::hygiene::Mark;
44 use syntax_pos::MultiSpan;
45 use syntax_pos::symbol::Symbol;
47 use context::{is_pie_binary, get_reloc_model};
48 use common::{C_bytes_in_context, val_ty};
49 use jobserver::{Client, Acquired};
53 use std::ffi::{CString, CStr};
55 use std::io::{self, Write};
57 use std::path::{Path, PathBuf};
60 use std::sync::mpsc::{channel, Sender, Receiver};
62 use std::time::Instant;
64 use libc::{c_uint, c_void, c_char, size_t};
66 pub const RELOC_MODEL_ARGS : [(&'static str, llvm::RelocMode); 7] = [
67 ("pic", llvm::RelocMode::PIC),
68 ("static", llvm::RelocMode::Static),
69 ("default", llvm::RelocMode::Default),
70 ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
71 ("ropi", llvm::RelocMode::ROPI),
72 ("rwpi", llvm::RelocMode::RWPI),
73 ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
76 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
77 ("small", llvm::CodeModel::Small),
78 ("kernel", llvm::CodeModel::Kernel),
79 ("medium", llvm::CodeModel::Medium),
80 ("large", llvm::CodeModel::Large),
83 pub const TLS_MODEL_ARGS : [(&'static str, llvm::ThreadLocalMode); 4] = [
84 ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
85 ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
86 ("initial-exec", llvm::ThreadLocalMode::InitialExec),
87 ("local-exec", llvm::ThreadLocalMode::LocalExec),
90 const PRE_THIN_LTO_BC_EXT: &str = "pre-thin-lto.bc";
92 pub fn llvm_err(handler: &errors::Handler, msg: String) -> FatalError {
93 match llvm::last_error() {
94 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
95 None => handler.fatal(&msg),
99 pub fn write_output_file(
100 handler: &errors::Handler,
101 target: &'ll llvm::TargetMachine,
102 pm: &llvm::PassManager<'ll>,
103 m: &'ll llvm::Module,
105 file_type: llvm::FileType) -> Result<(), FatalError> {
107 let output_c = path2cstr(output);
108 let result = llvm::LLVMRustWriteOutputFile(
109 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;
199 let asm_comments = sess.asm_comments();
203 llvm::LLVMRustCreateTargetMachine(
204 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
219 format!("Could not create LLVM TargetMachine for triple: {}",
220 triple.to_str().unwrap())
225 /// Module-specific configuration for `optimize_and_codegen`.
226 pub struct ModuleConfig {
227 /// Names of additional optimization passes to run.
229 /// Some(level) to optimize at a certain level, or None to run
230 /// absolutely no optimizations (used for the metadata module).
231 pub opt_level: Option<llvm::CodeGenOptLevel>,
233 /// Some(level) to optimize binary size, or None to not affect program size.
234 opt_size: Option<llvm::CodeGenOptSize>,
236 pgo_gen: Option<String>,
239 // Flags indicating which outputs to produce.
240 pub emit_pre_thin_lto_bc: bool,
241 emit_no_opt_bc: bool,
243 emit_bc_compressed: bool,
248 // Miscellaneous flags. These are mostly copied from command-line
250 pub verify_llvm_ir: bool,
251 no_prepopulate_passes: bool,
254 vectorize_loop: bool,
256 merge_functions: bool,
257 inline_threshold: Option<usize>,
258 // Instead of creating an object file by doing LLVM codegen, just
259 // make the object file bitcode. Provides easy compatibility with
260 // emscripten's ecc compiler, when used as the linker.
261 obj_is_bitcode: bool,
262 no_integrated_as: bool,
264 embed_bitcode_marker: bool,
268 fn new(passes: Vec<String>) -> ModuleConfig {
275 pgo_use: String::new(),
277 emit_no_opt_bc: false,
278 emit_pre_thin_lto_bc: false,
280 emit_bc_compressed: false,
285 obj_is_bitcode: false,
286 embed_bitcode: false,
287 embed_bitcode_marker: false,
288 no_integrated_as: false,
290 verify_llvm_ir: false,
291 no_prepopulate_passes: false,
294 vectorize_loop: false,
295 vectorize_slp: false,
296 merge_functions: false,
297 inline_threshold: None
301 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
302 self.verify_llvm_ir = sess.verify_llvm_ir();
303 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
304 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
305 self.time_passes = sess.time_passes();
306 self.inline_threshold = sess.opts.cg.inline_threshold;
307 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
308 sess.opts.debugging_opts.cross_lang_lto.enabled();
309 let embed_bitcode = sess.target.target.options.embed_bitcode ||
310 sess.opts.debugging_opts.embed_bitcode;
312 match sess.opts.optimize {
313 config::OptLevel::No |
314 config::OptLevel::Less => {
315 self.embed_bitcode_marker = embed_bitcode;
317 _ => self.embed_bitcode = embed_bitcode,
321 // Copy what clang does by turning on loop vectorization at O2 and
322 // slp vectorization at O3. Otherwise configure other optimization aspects
323 // of this pass manager builder.
324 // Turn off vectorization for emscripten, as it's not very well supported.
325 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
326 (sess.opts.optimize == config::OptLevel::Default ||
327 sess.opts.optimize == config::OptLevel::Aggressive) &&
328 !sess.target.target.options.is_like_emscripten;
330 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
331 sess.opts.optimize == config::OptLevel::Aggressive &&
332 !sess.target.target.options.is_like_emscripten;
334 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
335 sess.opts.optimize == config::OptLevel::Aggressive;
339 /// Assembler name and command used by codegen when no_integrated_as is enabled
340 struct AssemblerCommand {
345 /// Additional resources used by optimize_and_codegen (not module specific)
347 pub struct CodegenContext {
348 // Resources needed when running LTO
349 pub time_passes: bool,
351 pub no_landing_pads: bool,
352 pub save_temps: bool,
353 pub fewer_names: bool,
354 pub exported_symbols: Option<Arc<ExportedSymbols>>,
355 pub opts: Arc<config::Options>,
356 pub crate_types: Vec<config::CrateType>,
357 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
358 output_filenames: Arc<OutputFilenames>,
359 regular_module_config: Arc<ModuleConfig>,
360 metadata_module_config: Arc<ModuleConfig>,
361 allocator_module_config: Arc<ModuleConfig>,
362 pub tm_factory: Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>,
363 pub msvc_imps_needed: bool,
364 pub target_pointer_width: String,
365 debuginfo: config::DebugInfo,
367 // Number of cgus excluding the allocator/metadata modules
368 pub total_cgus: usize,
369 // Handler to use for diagnostics produced during codegen.
370 pub diag_emitter: SharedEmitter,
371 // LLVM passes added by plugins.
372 pub plugin_passes: Vec<String>,
373 // LLVM optimizations for which we want to print remarks.
375 // Worker thread number
377 // The incremental compilation session directory, or None if we are not
378 // compiling incrementally
379 pub incr_comp_session_dir: Option<PathBuf>,
380 // Channel back to the main control thread to send messages to
381 coordinator_send: Sender<Box<dyn Any + Send>>,
382 // A reference to the TimeGraph so we can register timings. None means that
383 // measuring is disabled.
384 time_graph: Option<TimeGraph>,
385 // The assembler command if no_integrated_as option is enabled, None otherwise
386 assembler_cmd: Option<Arc<AssemblerCommand>>,
389 impl CodegenContext {
390 pub fn create_diag_handler(&self) -> Handler {
391 Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
394 pub(crate) fn config(&self, kind: ModuleKind) -> &ModuleConfig {
396 ModuleKind::Regular => &self.regular_module_config,
397 ModuleKind::Metadata => &self.metadata_module_config,
398 ModuleKind::Allocator => &self.allocator_module_config,
402 pub(crate) fn save_temp_bitcode(&self, module: &ModuleCodegen, name: &str) {
403 if !self.save_temps {
407 let ext = format!("{}.bc", name);
408 let cgu = Some(&module.name[..]);
409 let path = self.output_filenames.temp_path_ext(&ext, cgu);
410 let cstr = path2cstr(&path);
411 let llmod = module.module_llvm.llmod();
412 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
417 pub struct DiagnosticHandlers<'a> {
418 data: *mut (&'a CodegenContext, &'a Handler),
419 llcx: &'a llvm::Context,
422 impl<'a> DiagnosticHandlers<'a> {
423 pub fn new(cgcx: &'a CodegenContext,
424 handler: &'a Handler,
425 llcx: &'a llvm::Context) -> Self {
426 let data = Box::into_raw(Box::new((cgcx, handler)));
428 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
429 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
431 DiagnosticHandlers { data, llcx }
435 impl<'a> Drop for DiagnosticHandlers<'a> {
437 use std::ptr::null_mut;
439 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
440 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
441 drop(Box::from_raw(self.data));
446 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
449 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_string());
452 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
458 let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
460 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
461 .expect("non-UTF8 SMDiagnostic");
463 report_inline_asm(cgcx, &msg, cookie);
466 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
470 let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
472 match llvm::diagnostic::Diagnostic::unpack(info) {
473 llvm::diagnostic::InlineAsm(inline) => {
474 report_inline_asm(cgcx,
475 &llvm::twine_to_string(inline.message),
479 llvm::diagnostic::Optimization(opt) => {
480 let enabled = match cgcx.remark {
482 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
486 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
495 llvm::diagnostic::PGO(diagnostic_ref) |
496 llvm::diagnostic::Linker(diagnostic_ref) => {
497 let msg = llvm::build_string(|s| {
498 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
499 }).expect("non-UTF8 diagnostic");
500 diag_handler.warn(&msg);
502 llvm::diagnostic::UnknownDiagnostic(..) => {},
506 // Unsafe due to LLVM calls.
507 unsafe fn optimize(cgcx: &CodegenContext,
508 diag_handler: &Handler,
509 module: &ModuleCodegen,
510 config: &ModuleConfig,
511 timeline: &mut Timeline)
512 -> Result<(), FatalError>
514 let llmod = module.module_llvm.llmod();
515 let llcx = &*module.module_llvm.llcx;
516 let tm = &*module.module_llvm.tm;
517 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
519 let module_name = module.name.clone();
520 let module_name = Some(&module_name[..]);
522 if config.emit_no_opt_bc {
523 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
524 let out = path2cstr(&out);
525 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
528 if config.opt_level.is_some() {
529 // Create the two optimizing pass managers. These mirror what clang
530 // does, and are by populated by LLVM's default PassManagerBuilder.
531 // Each manager has a different set of passes, but they also share
532 // some common passes.
533 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
534 let mpm = llvm::LLVMCreatePassManager();
537 // If we're verifying or linting, add them to the function pass
539 let addpass = |pass_name: &str| {
540 let pass_name = SmallCStr::new(pass_name);
541 let pass = match llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr()) {
543 None => return false,
545 let pass_manager = match llvm::LLVMRustPassKind(pass) {
546 llvm::PassKind::Function => &*fpm,
547 llvm::PassKind::Module => &*mpm,
548 llvm::PassKind::Other => {
549 diag_handler.err("Encountered LLVM pass kind we can't handle");
553 llvm::LLVMRustAddPass(pass_manager, pass);
557 if config.verify_llvm_ir { assert!(addpass("verify")); }
559 // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
560 // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
561 // we'll get errors in LLVM.
562 let using_thin_buffers = llvm::LLVMRustThinLTOAvailable() && (config.emit_bc
563 || config.obj_is_bitcode || config.emit_bc_compressed || config.embed_bitcode);
564 let mut have_name_anon_globals_pass = false;
565 if !config.no_prepopulate_passes {
566 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
567 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
568 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
569 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal ||
570 (cgcx.lto != Lto::Fat && cgcx.opts.debugging_opts.cross_lang_lto.enabled());
571 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
572 if using_thin_buffers && !prepare_for_thin_lto {
573 assert!(addpass("name-anon-globals"));
574 have_name_anon_globals_pass = true;
576 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
577 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
578 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
582 for pass in &config.passes {
584 diag_handler.warn(&format!("unknown pass `{}`, ignoring",
587 if pass == "name-anon-globals" {
588 have_name_anon_globals_pass = true;
592 for pass in &cgcx.plugin_passes {
594 diag_handler.err(&format!("a plugin asked for LLVM pass \
595 `{}` but LLVM does not \
596 recognize it", pass));
598 if pass == "name-anon-globals" {
599 have_name_anon_globals_pass = true;
603 if using_thin_buffers && !have_name_anon_globals_pass {
604 // As described above, this will probably cause an error in LLVM
605 if config.no_prepopulate_passes {
606 diag_handler.err("The current compilation is going to use thin LTO buffers \
607 without running LLVM's NameAnonGlobals pass. \
608 This will likely cause errors in LLVM. Consider adding \
609 -C passes=name-anon-globals to the compiler command line.");
611 bug!("We are using thin LTO buffers without running the NameAnonGlobals pass. \
612 This will likely cause errors in LLVM and should never happen.");
617 diag_handler.abort_if_errors();
619 // Finally, run the actual optimization passes
620 time_ext(config.time_passes,
622 &format!("llvm function passes [{}]", module_name.unwrap()),
624 llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
626 timeline.record("fpm");
627 time_ext(config.time_passes,
629 &format!("llvm module passes [{}]", module_name.unwrap()),
631 llvm::LLVMRunPassManager(mpm, llmod)
634 // Deallocate managers that we're now done with
635 llvm::LLVMDisposePassManager(fpm);
636 llvm::LLVMDisposePassManager(mpm);
641 fn generate_lto_work(cgcx: &CodegenContext,
642 modules: Vec<ModuleCodegen>,
643 import_only_modules: Vec<(SerializedModule, WorkProduct)>)
644 -> Vec<(WorkItem, u64)>
646 let mut timeline = cgcx.time_graph.as_ref().map(|tg| {
647 tg.start(CODEGEN_WORKER_TIMELINE,
648 CODEGEN_WORK_PACKAGE_KIND,
650 }).unwrap_or(Timeline::noop());
651 let (lto_modules, copy_jobs) = lto::run(cgcx, modules, import_only_modules, &mut timeline)
652 .unwrap_or_else(|e| e.raise());
654 let lto_modules = lto_modules.into_iter().map(|module| {
655 let cost = module.cost();
656 (WorkItem::LTO(module), cost)
659 let copy_jobs = copy_jobs.into_iter().map(|wp| {
660 (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
661 name: wp.cgu_name.clone(),
666 lto_modules.chain(copy_jobs).collect()
669 unsafe fn codegen(cgcx: &CodegenContext,
670 diag_handler: &Handler,
671 module: ModuleCodegen,
672 config: &ModuleConfig,
673 timeline: &mut Timeline)
674 -> Result<CompiledModule, FatalError>
676 timeline.record("codegen");
678 let llmod = module.module_llvm.llmod();
679 let llcx = &*module.module_llvm.llcx;
680 let tm = &*module.module_llvm.tm;
681 let module_name = module.name.clone();
682 let module_name = Some(&module_name[..]);
683 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
685 if cgcx.msvc_imps_needed {
686 create_msvc_imps(cgcx, llcx, llmod);
689 // A codegen-specific pass manager is used to generate object
690 // files for an LLVM module.
692 // Apparently each of these pass managers is a one-shot kind of
693 // thing, so we create a new one for each type of output. The
694 // pass manager passed to the closure should be ensured to not
695 // escape the closure itself, and the manager should only be
697 unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine,
698 llmod: &'ll llvm::Module,
701 where F: FnOnce(&'ll mut PassManager<'ll>) -> R,
703 let cpm = llvm::LLVMCreatePassManager();
704 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
705 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
709 // If we don't have the integrated assembler, then we need to emit asm
710 // from LLVM and use `gcc` to create the object file.
711 let asm_to_obj = config.emit_obj && config.no_integrated_as;
713 // Change what we write and cleanup based on whether obj files are
714 // just llvm bitcode. In that case write bitcode, and possibly
715 // delete the bitcode if it wasn't requested. Don't generate the
716 // machine code, instead copy the .o file from the .bc
717 let write_bc = config.emit_bc || config.obj_is_bitcode;
718 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
719 let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
720 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
722 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
723 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
726 if write_bc || config.emit_bc_compressed || config.embed_bitcode {
729 let data = if llvm::LLVMRustThinLTOAvailable() {
730 thin = ThinBuffer::new(llmod);
733 old = ModuleBuffer::new(llmod);
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() {
944 Lto::ThinLocal => true,
948 pub fn start_async_codegen(tcx: TyCtxt,
949 time_graph: Option<TimeGraph>,
950 metadata: EncodedMetadata,
951 coordinator_receive: Receiver<Box<dyn Any + Send>>,
955 let crate_name = tcx.crate_name(LOCAL_CRATE);
956 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
957 let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
958 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
959 "windows_subsystem");
960 let windows_subsystem = subsystem.map(|subsystem| {
961 if subsystem != "windows" && subsystem != "console" {
962 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
963 `windows` and `console` are allowed",
966 subsystem.to_string()
969 let linker_info = LinkerInfo::new(tcx);
970 let crate_info = CrateInfo::new(tcx);
972 // Figure out what we actually need to build.
973 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
974 let mut metadata_config = ModuleConfig::new(vec![]);
975 let mut allocator_config = ModuleConfig::new(vec![]);
977 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
979 Sanitizer::Address => {
980 modules_config.passes.push("asan".to_owned());
981 modules_config.passes.push("asan-module".to_owned());
983 Sanitizer::Memory => {
984 modules_config.passes.push("msan".to_owned())
986 Sanitizer::Thread => {
987 modules_config.passes.push("tsan".to_owned())
993 if sess.opts.debugging_opts.profile {
994 modules_config.passes.push("insert-gcov-profiling".to_owned())
997 modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
998 modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
1000 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
1001 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
1003 // Save all versions of the bytecode if we're saving our temporaries.
1004 if sess.opts.cg.save_temps {
1005 modules_config.emit_no_opt_bc = true;
1006 modules_config.emit_pre_thin_lto_bc = true;
1007 modules_config.emit_bc = true;
1008 modules_config.emit_lto_bc = true;
1009 metadata_config.emit_bc = true;
1010 allocator_config.emit_bc = true;
1013 // Emit compressed bitcode files for the crate if we're emitting an rlib.
1014 // Whenever an rlib is created, the bitcode is inserted into the archive in
1015 // order to allow LTO against it.
1016 if need_crate_bitcode_for_rlib(sess) {
1017 modules_config.emit_bc_compressed = true;
1018 allocator_config.emit_bc_compressed = true;
1021 modules_config.emit_pre_thin_lto_bc =
1022 need_pre_thin_lto_bitcode_for_incr_comp(sess);
1024 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
1025 tcx.sess.target.target.options.no_integrated_as;
1027 for output_type in sess.opts.output_types.keys() {
1028 match *output_type {
1029 OutputType::Bitcode => { modules_config.emit_bc = true; }
1030 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
1031 OutputType::Assembly => {
1032 modules_config.emit_asm = true;
1033 // If we're not using the LLVM assembler, this function
1034 // could be invoked specially with output_type_assembly, so
1035 // in this case we still want the metadata object file.
1036 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
1037 metadata_config.emit_obj = true;
1038 allocator_config.emit_obj = true;
1041 OutputType::Object => { modules_config.emit_obj = true; }
1042 OutputType::Metadata => { metadata_config.emit_obj = true; }
1043 OutputType::Exe => {
1044 modules_config.emit_obj = true;
1045 metadata_config.emit_obj = true;
1046 allocator_config.emit_obj = true;
1048 OutputType::Mir => {}
1049 OutputType::DepInfo => {}
1053 modules_config.set_flags(sess, no_builtins);
1054 metadata_config.set_flags(sess, no_builtins);
1055 allocator_config.set_flags(sess, no_builtins);
1057 // Exclude metadata and allocator modules from time_passes output, since
1058 // they throw off the "LLVM passes" measurement.
1059 metadata_config.time_passes = false;
1060 allocator_config.time_passes = false;
1062 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
1063 let (codegen_worker_send, codegen_worker_receive) = channel();
1065 let coordinator_thread = start_executing_work(tcx,
1068 codegen_worker_send,
1069 coordinator_receive,
1071 sess.jobserver.clone(),
1073 Arc::new(modules_config),
1074 Arc::new(metadata_config),
1075 Arc::new(allocator_config));
1086 coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
1087 codegen_worker_receive,
1088 shared_emitter_main,
1089 future: coordinator_thread,
1090 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1094 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
1096 compiled_modules: &CompiledModules,
1097 ) -> FxHashMap<WorkProductId, WorkProduct> {
1098 let mut work_products = FxHashMap::default();
1100 if sess.opts.incremental.is_none() {
1101 return work_products;
1104 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
1105 let mut files = vec![];
1107 if let Some(ref path) = module.object {
1108 files.push((WorkProductFileKind::Object, path.clone()));
1110 if let Some(ref path) = module.bytecode {
1111 files.push((WorkProductFileKind::Bytecode, path.clone()));
1113 if let Some(ref path) = module.bytecode_compressed {
1114 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
1117 if let Some((id, product)) =
1118 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::Yes | 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 // Additionally here's where we also factor in the current LLVM
1386 // version. If it doesn't support ThinLTO we skip this.
1388 module.kind != ModuleKind::Allocator &&
1389 unsafe { llvm::LLVMRustThinLTOAvailable() }
1393 // Metadata modules never participate in LTO regardless of the lto
1395 let needs_lto = needs_lto && module.kind != ModuleKind::Metadata;
1398 Ok(WorkItemResult::NeedsLTO(module))
1400 let module = unsafe {
1401 codegen(cgcx, &diag_handler, module, module_config, timeline)?
1403 Ok(WorkItemResult::Compiled(module))
1407 fn execute_copy_from_cache_work_item(cgcx: &CodegenContext,
1408 module: CachedModuleCodegen,
1409 module_config: &ModuleConfig,
1411 -> Result<WorkItemResult, FatalError>
1413 let incr_comp_session_dir = cgcx.incr_comp_session_dir
1416 let mut object = None;
1417 let mut bytecode = None;
1418 let mut bytecode_compressed = None;
1419 for (kind, saved_file) in &module.source.saved_files {
1420 let obj_out = match kind {
1421 WorkProductFileKind::Object => {
1422 let path = cgcx.output_filenames.temp_path(OutputType::Object,
1423 Some(&module.name));
1424 object = Some(path.clone());
1427 WorkProductFileKind::Bytecode => {
1428 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1429 Some(&module.name));
1430 bytecode = Some(path.clone());
1433 WorkProductFileKind::BytecodeCompressed => {
1434 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1436 .with_extension(RLIB_BYTECODE_EXTENSION);
1437 bytecode_compressed = Some(path.clone());
1441 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1443 debug!("copying pre-existing module `{}` from {:?} to {}",
1447 match link_or_copy(&source_file, &obj_out) {
1450 let diag_handler = cgcx.create_diag_handler();
1451 diag_handler.err(&format!("unable to copy {} to {}: {}",
1452 source_file.display(),
1459 assert_eq!(object.is_some(), module_config.emit_obj);
1460 assert_eq!(bytecode.is_some(), module_config.emit_bc);
1461 assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
1463 Ok(WorkItemResult::Compiled(CompiledModule {
1465 kind: ModuleKind::Regular,
1468 bytecode_compressed,
1472 fn execute_lto_work_item(cgcx: &CodegenContext,
1473 mut module: lto::LtoModuleCodegen,
1474 module_config: &ModuleConfig,
1475 timeline: &mut Timeline)
1476 -> Result<WorkItemResult, FatalError>
1478 let diag_handler = cgcx.create_diag_handler();
1481 let module = module.optimize(cgcx, timeline)?;
1482 let module = codegen(cgcx, &diag_handler, module, module_config, timeline)?;
1483 Ok(WorkItemResult::Compiled(module))
1488 Token(io::Result<Acquired>),
1490 result: ModuleCodegen,
1494 result: Result<CompiledModule, ()>,
1498 llvm_work_item: WorkItem,
1501 AddImportOnlyModule {
1502 module_data: SerializedModule,
1503 work_product: WorkProduct,
1511 code: Option<DiagnosticId>,
1515 #[derive(PartialEq, Clone, Copy, Debug)]
1516 enum MainThreadWorkerState {
1522 fn start_executing_work(tcx: TyCtxt,
1523 crate_info: &CrateInfo,
1524 shared_emitter: SharedEmitter,
1525 codegen_worker_send: Sender<Message>,
1526 coordinator_receive: Receiver<Box<dyn Any + Send>>,
1529 time_graph: Option<TimeGraph>,
1530 modules_config: Arc<ModuleConfig>,
1531 metadata_config: Arc<ModuleConfig>,
1532 allocator_config: Arc<ModuleConfig>)
1533 -> thread::JoinHandle<Result<CompiledModules, ()>> {
1534 let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1535 let sess = tcx.sess;
1537 // Compute the set of symbols we need to retain when doing LTO (if we need to)
1538 let exported_symbols = {
1539 let mut exported_symbols = FxHashMap();
1541 let copy_symbols = |cnum| {
1542 let symbols = tcx.exported_symbols(cnum)
1544 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1552 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1553 Some(Arc::new(exported_symbols))
1555 Lto::Yes | Lto::Fat | Lto::Thin => {
1556 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1557 for &cnum in tcx.crates().iter() {
1558 exported_symbols.insert(cnum, copy_symbols(cnum));
1560 Some(Arc::new(exported_symbols))
1565 // First up, convert our jobserver into a helper thread so we can use normal
1566 // mpsc channels to manage our messages and such.
1567 // After we've requested tokens then we'll, when we can,
1568 // get tokens on `coordinator_receive` which will
1569 // get managed in the main loop below.
1570 let coordinator_send2 = coordinator_send.clone();
1571 let helper = jobserver.into_helper_thread(move |token| {
1572 drop(coordinator_send2.send(Box::new(Message::Token(token))));
1573 }).expect("failed to spawn helper thread");
1575 let mut each_linked_rlib_for_lto = Vec::new();
1576 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1577 if link::ignored_for_lto(sess, crate_info, cnum) {
1580 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1583 let assembler_cmd = if modules_config.no_integrated_as {
1584 // HACK: currently we use linker (gcc) as our assembler
1585 let (linker, flavor) = link::linker_and_flavor(sess);
1587 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1588 cmd.args(&sess.target.target.options.asm_args);
1589 Some(Arc::new(AssemblerCommand {
1597 let cgcx = CodegenContext {
1598 crate_types: sess.crate_types.borrow().clone(),
1599 each_linked_rlib_for_lto,
1601 no_landing_pads: sess.no_landing_pads(),
1602 fewer_names: sess.fewer_names(),
1603 save_temps: sess.opts.cg.save_temps,
1604 opts: Arc::new(sess.opts.clone()),
1605 time_passes: sess.time_passes(),
1607 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1608 remark: sess.opts.cg.remark.clone(),
1610 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1612 diag_emitter: shared_emitter.clone(),
1614 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1615 regular_module_config: modules_config,
1616 metadata_module_config: metadata_config,
1617 allocator_module_config: allocator_config,
1618 tm_factory: target_machine_factory(tcx.sess, false),
1620 msvc_imps_needed: msvc_imps_needed(tcx),
1621 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1622 debuginfo: tcx.sess.opts.debuginfo,
1626 // This is the "main loop" of parallel work happening for parallel codegen.
1627 // It's here that we manage parallelism, schedule work, and work with
1628 // messages coming from clients.
1630 // There are a few environmental pre-conditions that shape how the system
1633 // - Error reporting only can happen on the main thread because that's the
1634 // only place where we have access to the compiler `Session`.
1635 // - LLVM work can be done on any thread.
1636 // - Codegen can only happen on the main thread.
1637 // - Each thread doing substantial work most be in possession of a `Token`
1638 // from the `Jobserver`.
1639 // - The compiler process always holds one `Token`. Any additional `Tokens`
1640 // have to be requested from the `Jobserver`.
1644 // The error reporting restriction is handled separately from the rest: We
1645 // set up a `SharedEmitter` the holds an open channel to the main thread.
1646 // When an error occurs on any thread, the shared emitter will send the
1647 // error message to the receiver main thread (`SharedEmitterMain`). The
1648 // main thread will periodically query this error message queue and emit
1649 // any error messages it has received. It might even abort compilation if
1650 // has received a fatal error. In this case we rely on all other threads
1651 // being torn down automatically with the main thread.
1652 // Since the main thread will often be busy doing codegen work, error
1653 // reporting will be somewhat delayed, since the message queue can only be
1654 // checked in between to work packages.
1656 // Work Processing Infrastructure
1657 // ==============================
1658 // The work processing infrastructure knows three major actors:
1660 // - the coordinator thread,
1661 // - the main thread, and
1662 // - LLVM worker threads
1664 // The coordinator thread is running a message loop. It instructs the main
1665 // thread about what work to do when, and it will spawn off LLVM worker
1666 // threads as open LLVM WorkItems become available.
1668 // The job of the main thread is to codegen CGUs into LLVM work package
1669 // (since the main thread is the only thread that can do this). The main
1670 // thread will block until it receives a message from the coordinator, upon
1671 // which it will codegen one CGU, send it to the coordinator and block
1672 // again. This way the coordinator can control what the main thread is
1675 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1676 // available, it will spawn off a new LLVM worker thread and let it process
1677 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1678 // it will just shut down, which also frees all resources associated with
1679 // the given LLVM module, and sends a message to the coordinator that the
1680 // has been completed.
1684 // The scheduler's goal is to minimize the time it takes to complete all
1685 // work there is, however, we also want to keep memory consumption low
1686 // if possible. These two goals are at odds with each other: If memory
1687 // consumption were not an issue, we could just let the main thread produce
1688 // LLVM WorkItems at full speed, assuring maximal utilization of
1689 // Tokens/LLVM worker threads. However, since codegen usual is faster
1690 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1691 // WorkItem potentially holds on to a substantial amount of memory.
1693 // So the actual goal is to always produce just enough LLVM WorkItems as
1694 // not to starve our LLVM worker threads. That means, once we have enough
1695 // WorkItems in our queue, we can block the main thread, so it does not
1696 // produce more until we need them.
1698 // Doing LLVM Work on the Main Thread
1699 // ----------------------------------
1700 // Since the main thread owns the compiler processes implicit `Token`, it is
1701 // wasteful to keep it blocked without doing any work. Therefore, what we do
1702 // in this case is: We spawn off an additional LLVM worker thread that helps
1703 // reduce the queue. The work it is doing corresponds to the implicit
1704 // `Token`. The coordinator will mark the main thread as being busy with
1705 // LLVM work. (The actual work happens on another OS thread but we just care
1706 // about `Tokens`, not actual threads).
1708 // When any LLVM worker thread finishes while the main thread is marked as
1709 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1710 // of the just finished thread to the LLVM worker thread that is working on
1711 // behalf of the main thread's implicit Token, thus freeing up the main
1712 // thread again. The coordinator can then again decide what the main thread
1713 // should do. This allows the coordinator to make decisions at more points
1716 // Striking a Balance between Throughput and Memory Consumption
1717 // ------------------------------------------------------------
1718 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1719 // memory consumption as low as possible, are in conflict with each other,
1720 // we have to find a trade off between them. Right now, the goal is to keep
1721 // all workers busy, which means that no worker should find the queue empty
1722 // when it is ready to start.
1723 // How do we do achieve this? Good question :) We actually never know how
1724 // many `Tokens` are potentially available so it's hard to say how much to
1725 // fill up the queue before switching the main thread to LLVM work. Also we
1726 // currently don't have a means to estimate how long a running LLVM worker
1727 // will still be busy with it's current WorkItem. However, we know the
1728 // maximal count of available Tokens that makes sense (=the number of CPU
1729 // cores), so we can take a conservative guess. The heuristic we use here
1730 // is implemented in the `queue_full_enough()` function.
1732 // Some Background on Jobservers
1733 // -----------------------------
1734 // It's worth also touching on the management of parallelism here. We don't
1735 // want to just spawn a thread per work item because while that's optimal
1736 // parallelism it may overload a system with too many threads or violate our
1737 // configuration for the maximum amount of cpu to use for this process. To
1738 // manage this we use the `jobserver` crate.
1740 // Job servers are an artifact of GNU make and are used to manage
1741 // parallelism between processes. A jobserver is a glorified IPC semaphore
1742 // basically. Whenever we want to run some work we acquire the semaphore,
1743 // and whenever we're done with that work we release the semaphore. In this
1744 // manner we can ensure that the maximum number of parallel workers is
1745 // capped at any one point in time.
1747 // LTO and the coordinator thread
1748 // ------------------------------
1750 // The final job the coordinator thread is responsible for is managing LTO
1751 // and how that works. When LTO is requested what we'll to is collect all
1752 // optimized LLVM modules into a local vector on the coordinator. Once all
1753 // modules have been codegened and optimized we hand this to the `lto`
1754 // module for further optimization. The `lto` module will return back a list
1755 // of more modules to work on, which the coordinator will continue to spawn
1758 // Each LLVM module is automatically sent back to the coordinator for LTO if
1759 // necessary. There's already optimizations in place to avoid sending work
1760 // back to the coordinator if LTO isn't requested.
1761 return thread::spawn(move || {
1762 // We pretend to be within the top-level LLVM time-passes task here:
1765 let max_workers = ::num_cpus::get();
1766 let mut worker_id_counter = 0;
1767 let mut free_worker_ids = Vec::new();
1768 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1769 if let Some(id) = free_worker_ids.pop() {
1772 let id = worker_id_counter;
1773 worker_id_counter += 1;
1778 // This is where we collect codegen units that have gone all the way
1779 // through codegen and LLVM.
1780 let mut compiled_modules = vec![];
1781 let mut compiled_metadata_module = None;
1782 let mut compiled_allocator_module = None;
1783 let mut needs_lto = Vec::new();
1784 let mut lto_import_only_modules = Vec::new();
1785 let mut started_lto = 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
1804 while !codegen_done ||
1805 work_items.len() > 0 ||
1807 needs_lto.len() > 0 ||
1808 lto_import_only_modules.len() > 0 ||
1809 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);
1839 // If we've finished everything related to normal codegen
1840 // then it must be the case that we've got some LTO work to do.
1841 // Perform the serial work here of figuring out what we're
1842 // going to LTO and then push a bunch of work items onto our
1844 if work_items.len() == 0 &&
1846 main_thread_worker_state == MainThreadWorkerState::Idle {
1847 assert!(!started_lto);
1848 assert!(needs_lto.len() + lto_import_only_modules.len() > 0);
1850 let modules = mem::replace(&mut needs_lto, Vec::new());
1851 let import_only_modules =
1852 mem::replace(&mut lto_import_only_modules, Vec::new());
1853 for (work, cost) in generate_lto_work(&cgcx, modules, import_only_modules) {
1854 let insertion_index = work_items
1855 .binary_search_by_key(&cost, |&(_, cost)| cost)
1856 .unwrap_or_else(|e| e);
1857 work_items.insert(insertion_index, (work, cost));
1858 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1859 helper.request_token();
1864 // In this branch, we know that everything has been codegened,
1865 // so it's just a matter of determining whether the implicit
1866 // Token is free to use for LLVM work.
1867 match main_thread_worker_state {
1868 MainThreadWorkerState::Idle => {
1869 if let Some((item, _)) = work_items.pop() {
1870 let cgcx = CodegenContext {
1871 worker: get_worker_id(&mut free_worker_ids),
1874 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1875 &mut llvm_start_time);
1876 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1877 spawn_work(cgcx, item);
1879 // There is no unstarted work, so let the main thread
1880 // take over for a running worker. Otherwise the
1881 // implicit token would just go to waste.
1882 // We reduce the `running` counter by one. The
1883 // `tokens.truncate()` below will take care of
1884 // giving the Token back.
1885 debug_assert!(running > 0);
1887 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1890 MainThreadWorkerState::Codegenning => {
1891 bug!("codegen worker should not be codegenning after \
1892 codegen was already completed")
1894 MainThreadWorkerState::LLVMing => {
1895 // Already making good use of that token
1900 // Spin up what work we can, only doing this while we've got available
1901 // parallelism slots and work left to spawn.
1902 while work_items.len() > 0 && running < tokens.len() {
1903 let (item, _) = work_items.pop().unwrap();
1905 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1906 &mut llvm_start_time);
1908 let cgcx = CodegenContext {
1909 worker: get_worker_id(&mut free_worker_ids),
1913 spawn_work(cgcx, item);
1917 // Relinquish accidentally acquired extra tokens
1918 tokens.truncate(running);
1920 let msg = coordinator_receive.recv().unwrap();
1921 match *msg.downcast::<Message>().ok().unwrap() {
1922 // Save the token locally and the next turn of the loop will use
1923 // this to spawn a new unit of work, or it may get dropped
1924 // immediately if we have no more work to spawn.
1925 Message::Token(token) => {
1930 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1931 // If the main thread token is used for LLVM work
1932 // at the moment, we turn that thread into a regular
1933 // LLVM worker thread, so the main thread is free
1934 // to react to codegen demand.
1935 main_thread_worker_state = MainThreadWorkerState::Idle;
1940 let msg = &format!("failed to acquire jobserver token: {}", e);
1941 shared_emitter.fatal(msg);
1942 // Exit the coordinator thread
1948 Message::CodegenDone { llvm_work_item, cost } => {
1949 // We keep the queue sorted by estimated processing cost,
1950 // so that more expensive items are processed earlier. This
1951 // is good for throughput as it gives the main thread more
1952 // time to fill up the queue and it avoids scheduling
1953 // expensive items to the end.
1954 // Note, however, that this is not ideal for memory
1955 // consumption, as LLVM module sizes are not evenly
1957 let insertion_index =
1958 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1959 let insertion_index = match insertion_index {
1960 Ok(idx) | Err(idx) => idx
1962 work_items.insert(insertion_index, (llvm_work_item, cost));
1964 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1965 helper.request_token();
1967 assert_eq!(main_thread_worker_state,
1968 MainThreadWorkerState::Codegenning);
1969 main_thread_worker_state = MainThreadWorkerState::Idle;
1972 Message::CodegenComplete => {
1973 codegen_done = true;
1974 assert_eq!(main_thread_worker_state,
1975 MainThreadWorkerState::Codegenning);
1976 main_thread_worker_state = MainThreadWorkerState::Idle;
1979 // If a thread exits successfully then we drop a token associated
1980 // with that worker and update our `running` count. We may later
1981 // re-acquire a token to continue running more work. We may also not
1982 // actually drop a token here if the worker was running with an
1983 // "ephemeral token"
1985 // Note that if the thread failed that means it panicked, so we
1986 // abort immediately.
1987 Message::Done { result: Ok(compiled_module), worker_id } => {
1988 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1989 main_thread_worker_state = MainThreadWorkerState::Idle;
1994 free_worker_ids.push(worker_id);
1996 match compiled_module.kind {
1997 ModuleKind::Regular => {
1998 compiled_modules.push(compiled_module);
2000 ModuleKind::Metadata => {
2001 assert!(compiled_metadata_module.is_none());
2002 compiled_metadata_module = Some(compiled_module);
2004 ModuleKind::Allocator => {
2005 assert!(compiled_allocator_module.is_none());
2006 compiled_allocator_module = Some(compiled_module);
2010 Message::NeedsLTO { result, worker_id } => {
2011 assert!(!started_lto);
2012 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
2013 main_thread_worker_state = MainThreadWorkerState::Idle;
2017 free_worker_ids.push(worker_id);
2018 needs_lto.push(result);
2020 Message::AddImportOnlyModule { module_data, work_product } => {
2021 assert!(!started_lto);
2022 assert!(!codegen_done);
2023 assert_eq!(main_thread_worker_state,
2024 MainThreadWorkerState::Codegenning);
2025 lto_import_only_modules.push((module_data, work_product));
2026 main_thread_worker_state = MainThreadWorkerState::Idle;
2028 Message::Done { result: Err(()), worker_id: _ } => {
2029 shared_emitter.fatal("aborting due to worker thread failure");
2030 // Exit the coordinator thread
2033 Message::CodegenItem => {
2034 bug!("the coordinator should not receive codegen requests")
2039 if let Some(llvm_start_time) = llvm_start_time {
2040 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
2041 // This is the top-level timing for all of LLVM, set the time-depth
2044 print_time_passes_entry(cgcx.time_passes,
2049 // Regardless of what order these modules completed in, report them to
2050 // the backend in the same order every time to ensure that we're handing
2051 // out deterministic results.
2052 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
2054 let compiled_metadata_module = compiled_metadata_module
2055 .expect("Metadata module not compiled?");
2057 Ok(CompiledModules {
2058 modules: compiled_modules,
2059 metadata_module: compiled_metadata_module,
2060 allocator_module: compiled_allocator_module,
2064 // A heuristic that determines if we have enough LLVM WorkItems in the
2065 // queue so that the main thread can do LLVM work instead of codegen
2066 fn queue_full_enough(items_in_queue: usize,
2067 workers_running: usize,
2068 max_workers: usize) -> bool {
2070 items_in_queue > 0 &&
2071 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
2074 fn maybe_start_llvm_timer(config: &ModuleConfig,
2075 llvm_start_time: &mut Option<Instant>) {
2076 // We keep track of the -Ztime-passes output manually,
2077 // since the closure-based interface does not fit well here.
2078 if config.time_passes {
2079 if llvm_start_time.is_none() {
2080 *llvm_start_time = Some(Instant::now());
2086 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
2087 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
2088 time_graph::TimelineId(CODEGEN_WORKER_ID);
2089 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2090 time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
2091 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2092 time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
2094 fn spawn_work(cgcx: CodegenContext, work: WorkItem) {
2095 let depth = time_depth();
2097 thread::spawn(move || {
2098 set_time_depth(depth);
2100 // Set up a destructor which will fire off a message that we're done as
2103 coordinator_send: Sender<Box<dyn Any + Send>>,
2104 result: Option<WorkItemResult>,
2107 impl Drop for Bomb {
2108 fn drop(&mut self) {
2109 let worker_id = self.worker_id;
2110 let msg = match self.result.take() {
2111 Some(WorkItemResult::Compiled(m)) => {
2112 Message::Done { result: Ok(m), worker_id }
2114 Some(WorkItemResult::NeedsLTO(m)) => {
2115 Message::NeedsLTO { result: m, worker_id }
2117 None => Message::Done { result: Err(()), worker_id }
2119 drop(self.coordinator_send.send(Box::new(msg)));
2123 let mut bomb = Bomb {
2124 coordinator_send: cgcx.coordinator_send.clone(),
2126 worker_id: cgcx.worker,
2129 // Execute the work itself, and if it finishes successfully then flag
2130 // ourselves as a success as well.
2132 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
2133 // as a diagnostic was already sent off to the main thread - just
2134 // surface that there was an error in this worker.
2136 let timeline = cgcx.time_graph.as_ref().map(|tg| {
2137 tg.start(time_graph::TimelineId(cgcx.worker),
2138 LLVM_WORK_PACKAGE_KIND,
2141 let mut timeline = timeline.unwrap_or(Timeline::noop());
2142 execute_work_item(&cgcx, work, &mut timeline).ok()
2147 pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, object: &Path) {
2148 let assembler = cgcx.assembler_cmd
2150 .expect("cgcx.assembler_cmd is missing?");
2152 let pname = &assembler.name;
2153 let mut cmd = assembler.cmd.clone();
2154 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
2155 debug!("{:?}", cmd);
2157 match cmd.output() {
2159 if !prog.status.success() {
2160 let mut note = prog.stderr.clone();
2161 note.extend_from_slice(&prog.stdout);
2163 handler.struct_err(&format!("linking with `{}` failed: {}",
2166 .note(&format!("{:?}", &cmd))
2167 .note(str::from_utf8(¬e[..]).unwrap())
2169 handler.abort_if_errors();
2173 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
2174 handler.abort_if_errors();
2179 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
2180 config: &ModuleConfig,
2181 opt_level: llvm::CodeGenOptLevel,
2182 prepare_for_thin_lto: bool,
2183 f: &mut dyn FnMut(&llvm::PassManagerBuilder)) {
2186 // Create the PassManagerBuilder for LLVM. We configure it with
2187 // reasonable defaults and prepare it to actually populate the pass
2189 let builder = llvm::LLVMPassManagerBuilderCreate();
2190 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
2191 let inline_threshold = config.inline_threshold;
2193 let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
2194 let s = if s.is_empty() { "default_%m.profraw" } else { s };
2195 CString::new(s.as_bytes()).unwrap()
2198 let pgo_use_path = if config.pgo_use.is_empty() {
2201 Some(CString::new(config.pgo_use.as_bytes()).unwrap())
2204 llvm::LLVMRustConfigurePassManagerBuilder(
2207 config.merge_functions,
2208 config.vectorize_slp,
2209 config.vectorize_loop,
2210 prepare_for_thin_lto,
2211 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2212 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2215 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
2217 if opt_size != llvm::CodeGenOptSizeNone {
2218 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
2221 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
2223 // Here we match what clang does (kinda). For O0 we only inline
2224 // always-inline functions (but don't add lifetime intrinsics), at O1 we
2225 // inline with lifetime intrinsics, and O2+ we add an inliner with a
2226 // thresholds copied from clang.
2227 match (opt_level, opt_size, inline_threshold) {
2229 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
2231 (llvm::CodeGenOptLevel::Aggressive, ..) => {
2232 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
2234 (_, llvm::CodeGenOptSizeDefault, _) => {
2235 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
2237 (_, llvm::CodeGenOptSizeAggressive, _) => {
2238 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
2240 (llvm::CodeGenOptLevel::None, ..) => {
2241 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
2243 (llvm::CodeGenOptLevel::Less, ..) => {
2244 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
2246 (llvm::CodeGenOptLevel::Default, ..) => {
2247 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
2249 (llvm::CodeGenOptLevel::Other, ..) => {
2250 bug!("CodeGenOptLevel::Other selected")
2255 llvm::LLVMPassManagerBuilderDispose(builder);
2259 enum SharedEmitterMessage {
2260 Diagnostic(Diagnostic),
2261 InlineAsmError(u32, String),
2267 pub struct SharedEmitter {
2268 sender: Sender<SharedEmitterMessage>,
2271 pub struct SharedEmitterMain {
2272 receiver: Receiver<SharedEmitterMessage>,
2275 impl SharedEmitter {
2276 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
2277 let (sender, receiver) = channel();
2279 (SharedEmitter { sender }, SharedEmitterMain { receiver })
2282 fn inline_asm_error(&self, cookie: u32, msg: String) {
2283 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
2286 fn fatal(&self, msg: &str) {
2287 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2291 impl Emitter for SharedEmitter {
2292 fn emit(&mut self, db: &DiagnosticBuilder) {
2293 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2295 code: db.code.clone(),
2298 for child in &db.children {
2299 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2300 msg: child.message(),
2305 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
2309 impl SharedEmitterMain {
2310 pub fn check(&self, sess: &Session, blocking: bool) {
2312 let message = if blocking {
2313 match self.receiver.recv() {
2314 Ok(message) => Ok(message),
2318 match self.receiver.try_recv() {
2319 Ok(message) => Ok(message),
2325 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2326 let handler = sess.diagnostic();
2329 handler.emit_with_code(&MultiSpan::new(),
2335 handler.emit(&MultiSpan::new(),
2341 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
2342 match Mark::from_u32(cookie).expn_info() {
2343 Some(ei) => sess.span_err(ei.call_site, &msg),
2344 None => sess.err(&msg),
2347 Ok(SharedEmitterMessage::AbortIfErrors) => {
2348 sess.abort_if_errors();
2350 Ok(SharedEmitterMessage::Fatal(msg)) => {
2362 pub struct OngoingCodegen {
2365 metadata: EncodedMetadata,
2366 windows_subsystem: Option<String>,
2367 linker_info: LinkerInfo,
2368 crate_info: CrateInfo,
2369 time_graph: Option<TimeGraph>,
2370 coordinator_send: Sender<Box<dyn Any + Send>>,
2371 codegen_worker_receive: Receiver<Message>,
2372 shared_emitter_main: SharedEmitterMain,
2373 future: thread::JoinHandle<Result<CompiledModules, ()>>,
2374 output_filenames: Arc<OutputFilenames>,
2377 impl OngoingCodegen {
2381 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
2382 self.shared_emitter_main.check(sess, true);
2383 let compiled_modules = match self.future.join() {
2384 Ok(Ok(compiled_modules)) => compiled_modules,
2386 sess.abort_if_errors();
2387 panic!("expected abort due to worker thread errors")
2390 sess.fatal("Error during codegen/LLVM phase.");
2394 sess.abort_if_errors();
2396 if let Some(time_graph) = self.time_graph {
2397 time_graph.dump(&format!("{}-timings", self.crate_name));
2401 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
2403 produce_final_output_artifacts(sess,
2405 &self.output_filenames);
2407 // FIXME: time_llvm_passes support - does this use a global context or
2409 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2410 unsafe { llvm::LLVMRustPrintPassTimings(); }
2414 crate_name: self.crate_name,
2415 crate_hash: self.crate_hash,
2416 metadata: self.metadata,
2417 windows_subsystem: self.windows_subsystem,
2418 linker_info: self.linker_info,
2419 crate_info: self.crate_info,
2421 modules: compiled_modules.modules,
2422 allocator_module: compiled_modules.allocator_module,
2423 metadata_module: compiled_modules.metadata_module,
2427 pub(crate) fn submit_pre_codegened_module_to_llvm(&self,
2429 module: ModuleCodegen) {
2430 self.wait_for_signal_to_codegen_item();
2431 self.check_for_errors(tcx.sess);
2433 // These are generally cheap and won't through off scheduling.
2435 submit_codegened_module_to_llvm(tcx, module, cost);
2438 pub fn codegen_finished(&self, tcx: TyCtxt) {
2439 self.wait_for_signal_to_codegen_item();
2440 self.check_for_errors(tcx.sess);
2441 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete)));
2444 pub fn check_for_errors(&self, sess: &Session) {
2445 self.shared_emitter_main.check(sess, false);
2448 pub fn wait_for_signal_to_codegen_item(&self) {
2449 match self.codegen_worker_receive.recv() {
2450 Ok(Message::CodegenItem) => {
2453 Ok(_) => panic!("unexpected message"),
2455 // One of the LLVM threads must have panicked, fall through so
2456 // error handling can be reached.
2462 pub(crate) fn submit_codegened_module_to_llvm(tcx: TyCtxt,
2463 module: ModuleCodegen,
2465 let llvm_work_item = WorkItem::Optimize(module);
2466 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2472 pub(crate) fn submit_post_lto_module_to_llvm(tcx: TyCtxt,
2473 module: CachedModuleCodegen) {
2474 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2475 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2481 pub(crate) fn submit_pre_lto_module_to_llvm(tcx: TyCtxt,
2482 module: CachedModuleCodegen) {
2483 let filename = pre_lto_bitcode_filename(&module.name);
2484 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2485 let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
2486 panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
2490 memmap::Mmap::map(&file).unwrap_or_else(|e| {
2491 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2495 // Schedule the module to be loaded
2496 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::AddImportOnlyModule {
2497 module_data: SerializedModule::FromUncompressedFile(mmap),
2498 work_product: module.source,
2502 pub(super) fn pre_lto_bitcode_filename(module_name: &str) -> String {
2503 format!("{}.{}", module_name, PRE_THIN_LTO_BC_EXT)
2506 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2507 // This should never be true (because it's not supported). If it is true,
2508 // something is wrong with commandline arg validation.
2509 assert!(!(tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() &&
2510 tcx.sess.target.target.options.is_like_msvc &&
2511 tcx.sess.opts.cg.prefer_dynamic));
2513 tcx.sess.target.target.options.is_like_msvc &&
2514 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
2515 // ThinLTO can't handle this workaround in all cases, so we don't
2516 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2517 // dynamic linking when cross-language LTO is enabled.
2518 !tcx.sess.opts.debugging_opts.cross_lang_lto.enabled()
2521 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2522 // This is required to satisfy `dllimport` references to static data in .rlibs
2523 // when using MSVC linker. We do this only for data, as linker can fix up
2524 // code references on its own.
2525 // See #26591, #27438
2526 fn create_msvc_imps(cgcx: &CodegenContext, llcx: &llvm::Context, llmod: &llvm::Module) {
2527 if !cgcx.msvc_imps_needed {
2530 // The x86 ABI seems to require that leading underscores are added to symbol
2531 // names, so we need an extra underscore on 32-bit. There's also a leading
2532 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2533 // underscores added in front).
2534 let prefix = if cgcx.target_pointer_width == "32" {
2540 let i8p_ty = Type::i8p_llcx(llcx);
2541 let globals = base::iter_globals(llmod)
2543 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
2544 llvm::LLVMIsDeclaration(val) == 0
2547 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2548 let mut imp_name = prefix.as_bytes().to_vec();
2549 imp_name.extend(name.to_bytes());
2550 let imp_name = CString::new(imp_name).unwrap();
2553 .collect::<Vec<_>>();
2554 for (imp_name, val) in globals {
2555 let imp = llvm::LLVMAddGlobal(llmod,
2557 imp_name.as_ptr() as *const _);
2558 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
2559 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);