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};
14 use back::link::{self, get_linker, remove};
15 use back::command::Command;
16 use back::linker::LinkerInfo;
17 use back::symbol_export::ExportedSymbols;
20 use rustc_incremental::{copy_cgu_workproducts_to_incr_comp_cache_dir, in_incr_comp_dir};
21 use rustc::dep_graph::{WorkProduct, WorkProductId, WorkProductFileKind};
22 use rustc::middle::cstore::{LinkMeta, EncodedMetadata};
23 use rustc::session::config::{self, OutputFilenames, OutputType, Passes, SomePasses,
24 AllPasses, Sanitizer, Lto};
25 use rustc::session::Session;
26 use rustc::util::nodemap::FxHashMap;
27 use time_graph::{self, TimeGraph, Timeline};
29 use llvm::{TargetMachineRef, PassManagerRef, DiagnosticInfoRef};
30 use llvm::SMDiagnosticRef;
31 use {CodegenResults, ModuleSource, ModuleCodegen, CompiledModule, ModuleKind};
33 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
34 use rustc::ty::TyCtxt;
35 use rustc::util::common::{time_ext, time_depth, set_time_depth, print_time_passes_entry};
36 use rustc::util::common::path2cstr;
37 use rustc::util::fs::{link_or_copy};
38 use errors::{self, Handler, Level, DiagnosticBuilder, FatalError, DiagnosticId};
39 use errors::emitter::{Emitter};
41 use syntax::ext::hygiene::Mark;
42 use syntax_pos::MultiSpan;
43 use syntax_pos::symbol::Symbol;
45 use context::{is_pie_binary, get_reloc_model};
46 use common::{C_bytes_in_context, val_ty};
47 use jobserver::{Client, Acquired};
51 use std::ffi::{CString, CStr};
53 use std::io::{self, Write};
55 use std::path::{Path, PathBuf};
58 use std::sync::mpsc::{channel, Sender, Receiver};
60 use std::time::Instant;
62 use libc::{c_uint, c_void, c_char, size_t};
64 pub const RELOC_MODEL_ARGS : [(&'static str, llvm::RelocMode); 7] = [
65 ("pic", llvm::RelocMode::PIC),
66 ("static", llvm::RelocMode::Static),
67 ("default", llvm::RelocMode::Default),
68 ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
69 ("ropi", llvm::RelocMode::ROPI),
70 ("rwpi", llvm::RelocMode::RWPI),
71 ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
74 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
75 ("small", llvm::CodeModel::Small),
76 ("kernel", llvm::CodeModel::Kernel),
77 ("medium", llvm::CodeModel::Medium),
78 ("large", llvm::CodeModel::Large),
81 pub const TLS_MODEL_ARGS : [(&'static str, llvm::ThreadLocalMode); 4] = [
82 ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
83 ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
84 ("initial-exec", llvm::ThreadLocalMode::InitialExec),
85 ("local-exec", llvm::ThreadLocalMode::LocalExec),
88 pub fn llvm_err(handler: &errors::Handler, msg: String) -> FatalError {
89 match llvm::last_error() {
90 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
91 None => handler.fatal(&msg),
95 pub fn write_output_file(
96 handler: &errors::Handler,
97 target: llvm::TargetMachineRef,
98 pm: llvm::PassManagerRef,
101 file_type: llvm::FileType) -> Result<(), FatalError> {
103 let output_c = path2cstr(output);
104 let result = llvm::LLVMRustWriteOutputFile(
105 target, pm, m, output_c.as_ptr(), file_type);
106 if result.into_result().is_err() {
107 let msg = format!("could not write output to {}", output.display());
108 Err(llvm_err(handler, msg))
115 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
117 config::OptLevel::No => llvm::CodeGenOptLevel::None,
118 config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
119 config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
120 config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
121 _ => llvm::CodeGenOptLevel::Default,
125 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
127 config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
128 config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
129 _ => llvm::CodeGenOptSizeNone,
133 pub fn create_target_machine(sess: &Session, find_features: bool) -> &'static mut llvm::TargetMachine {
134 target_machine_factory(sess, find_features)().unwrap_or_else(|err| {
135 llvm_err(sess.diagnostic(), err).raise()
139 // If find_features is true this won't access `sess.crate_types` by assuming
140 // that `is_pie_binary` is false. When we discover LLVM target features
141 // `sess.crate_types` is uninitialized so we cannot access it.
142 pub fn target_machine_factory(sess: &Session, find_features: bool)
143 -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>
145 let reloc_model = get_reloc_model(sess);
147 let opt_level = get_llvm_opt_level(sess.opts.optimize);
148 let use_softfp = sess.opts.cg.soft_float;
150 let ffunction_sections = sess.target.target.options.function_sections;
151 let fdata_sections = ffunction_sections;
153 let code_model_arg = sess.opts.cg.code_model.as_ref().or(
154 sess.target.target.options.code_model.as_ref(),
157 let code_model = match code_model_arg {
159 match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
162 sess.err(&format!("{:?} is not a valid code model",
164 sess.abort_if_errors();
169 None => llvm::CodeModel::None,
172 let singlethread = sess.target.target.options.singlethread;
174 let triple = &sess.target.target.llvm_target;
176 let triple = CString::new(triple.as_bytes()).unwrap();
177 let cpu = sess.target_cpu();
178 let cpu = CString::new(cpu.as_bytes()).unwrap();
179 let features = attributes::llvm_target_features(sess)
182 let features = CString::new(features).unwrap();
183 let is_pie_binary = !find_features && is_pie_binary(sess);
184 let trap_unreachable = sess.target.target.options.trap_unreachable;
188 llvm::LLVMRustCreateTargetMachine(
189 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
203 format!("Could not create LLVM TargetMachine for triple: {}",
204 triple.to_str().unwrap())
209 /// Module-specific configuration for `optimize_and_codegen`.
210 pub struct ModuleConfig {
211 /// Names of additional optimization passes to run.
213 /// Some(level) to optimize at a certain level, or None to run
214 /// absolutely no optimizations (used for the metadata module).
215 pub opt_level: Option<llvm::CodeGenOptLevel>,
217 /// Some(level) to optimize binary size, or None to not affect program size.
218 opt_size: Option<llvm::CodeGenOptSize>,
220 pgo_gen: Option<String>,
223 // Flags indicating which outputs to produce.
224 emit_no_opt_bc: bool,
226 emit_bc_compressed: bool,
231 // Miscellaneous flags. These are mostly copied from command-line
233 pub verify_llvm_ir: bool,
234 no_prepopulate_passes: bool,
237 vectorize_loop: bool,
239 merge_functions: bool,
240 inline_threshold: Option<usize>,
241 // Instead of creating an object file by doing LLVM codegen, just
242 // make the object file bitcode. Provides easy compatibility with
243 // emscripten's ecc compiler, when used as the linker.
244 obj_is_bitcode: bool,
245 no_integrated_as: bool,
247 embed_bitcode_marker: bool,
251 fn new(passes: Vec<String>) -> ModuleConfig {
258 pgo_use: String::new(),
260 emit_no_opt_bc: false,
262 emit_bc_compressed: false,
267 obj_is_bitcode: false,
268 embed_bitcode: false,
269 embed_bitcode_marker: false,
270 no_integrated_as: false,
272 verify_llvm_ir: false,
273 no_prepopulate_passes: false,
276 vectorize_loop: false,
277 vectorize_slp: false,
278 merge_functions: false,
279 inline_threshold: None
283 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
284 self.verify_llvm_ir = sess.verify_llvm_ir();
285 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
286 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
287 self.time_passes = sess.time_passes();
288 self.inline_threshold = sess.opts.cg.inline_threshold;
289 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
290 sess.opts.debugging_opts.cross_lang_lto.enabled();
291 let embed_bitcode = sess.target.target.options.embed_bitcode ||
292 sess.opts.debugging_opts.embed_bitcode;
294 match sess.opts.optimize {
295 config::OptLevel::No |
296 config::OptLevel::Less => {
297 self.embed_bitcode_marker = embed_bitcode;
299 _ => self.embed_bitcode = embed_bitcode,
303 // Copy what clang does by turning on loop vectorization at O2 and
304 // slp vectorization at O3. Otherwise configure other optimization aspects
305 // of this pass manager builder.
306 // Turn off vectorization for emscripten, as it's not very well supported.
307 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
308 (sess.opts.optimize == config::OptLevel::Default ||
309 sess.opts.optimize == config::OptLevel::Aggressive) &&
310 !sess.target.target.options.is_like_emscripten;
312 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
313 sess.opts.optimize == config::OptLevel::Aggressive &&
314 !sess.target.target.options.is_like_emscripten;
316 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
317 sess.opts.optimize == config::OptLevel::Aggressive;
321 /// Assembler name and command used by codegen when no_integrated_as is enabled
322 struct AssemblerCommand {
327 /// Additional resources used by optimize_and_codegen (not module specific)
329 pub struct CodegenContext {
330 // Resouces needed when running LTO
331 pub time_passes: bool,
333 pub no_landing_pads: bool,
334 pub save_temps: bool,
335 pub fewer_names: bool,
336 pub exported_symbols: Option<Arc<ExportedSymbols>>,
337 pub opts: Arc<config::Options>,
338 pub crate_types: Vec<config::CrateType>,
339 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
340 output_filenames: Arc<OutputFilenames>,
341 regular_module_config: Arc<ModuleConfig>,
342 metadata_module_config: Arc<ModuleConfig>,
343 allocator_module_config: Arc<ModuleConfig>,
344 pub tm_factory: Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>,
345 pub msvc_imps_needed: bool,
346 pub target_pointer_width: String,
347 debuginfo: config::DebugInfoLevel,
349 // Number of cgus excluding the allocator/metadata modules
350 pub total_cgus: usize,
351 // Handler to use for diagnostics produced during codegen.
352 pub diag_emitter: SharedEmitter,
353 // LLVM passes added by plugins.
354 pub plugin_passes: Vec<String>,
355 // LLVM optimizations for which we want to print remarks.
357 // Worker thread number
359 // The incremental compilation session directory, or None if we are not
360 // compiling incrementally
361 pub incr_comp_session_dir: Option<PathBuf>,
362 // Channel back to the main control thread to send messages to
363 coordinator_send: Sender<Box<dyn Any + Send>>,
364 // A reference to the TimeGraph so we can register timings. None means that
365 // measuring is disabled.
366 time_graph: Option<TimeGraph>,
367 // The assembler command if no_integrated_as option is enabled, None otherwise
368 assembler_cmd: Option<Arc<AssemblerCommand>>,
371 impl CodegenContext {
372 pub fn create_diag_handler(&self) -> Handler {
373 Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
376 pub(crate) fn config(&self, kind: ModuleKind) -> &ModuleConfig {
378 ModuleKind::Regular => &self.regular_module_config,
379 ModuleKind::Metadata => &self.metadata_module_config,
380 ModuleKind::Allocator => &self.allocator_module_config,
384 pub(crate) fn save_temp_bitcode(&self, module: &ModuleCodegen, name: &str) {
385 if !self.save_temps {
389 let ext = format!("{}.bc", name);
390 let cgu = Some(&module.name[..]);
391 let path = self.output_filenames.temp_path_ext(&ext, cgu);
392 let cstr = path2cstr(&path);
393 let llmod = module.llvm().unwrap().llmod();
394 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
399 struct DiagnosticHandlers<'a> {
400 data: *mut (&'a CodegenContext, &'a Handler),
401 llcx: &'a llvm::Context,
404 impl<'a> DiagnosticHandlers<'a> {
405 fn new(cgcx: &'a CodegenContext,
406 handler: &'a Handler,
407 llcx: &'a llvm::Context) -> Self {
408 let data = Box::into_raw(Box::new((cgcx, handler)));
410 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
411 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
413 DiagnosticHandlers { data, llcx }
417 impl<'a> Drop for DiagnosticHandlers<'a> {
419 use std::ptr::null_mut;
421 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
422 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
423 drop(Box::from_raw(self.data));
428 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
431 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_string());
434 unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
440 let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
442 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
443 .expect("non-UTF8 SMDiagnostic");
445 report_inline_asm(cgcx, &msg, cookie);
448 unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
452 let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
454 match llvm::diagnostic::Diagnostic::unpack(info) {
455 llvm::diagnostic::InlineAsm(inline) => {
456 report_inline_asm(cgcx,
457 &llvm::twine_to_string(inline.message),
461 llvm::diagnostic::Optimization(opt) => {
462 let enabled = match cgcx.remark {
464 SomePasses(ref v) => v.iter().any(|s| *s == opt.pass_name),
468 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
477 llvm::diagnostic::PGO(diagnostic_ref) => {
478 let msg = llvm::build_string(|s| {
479 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
480 }).expect("non-UTF8 PGO diagnostic");
481 diag_handler.warn(&msg);
483 llvm::diagnostic::UnknownDiagnostic(..) => {},
487 // Unsafe due to LLVM calls.
488 unsafe fn optimize(cgcx: &CodegenContext,
489 diag_handler: &Handler,
490 module: &ModuleCodegen,
491 config: &ModuleConfig,
492 timeline: &mut Timeline)
493 -> Result<(), FatalError>
495 let (llmod, llcx, tm) = match module.source {
496 ModuleSource::Codegened(ref llvm) => (llvm.llmod(), &*llvm.llcx, &*llvm.tm),
497 ModuleSource::Preexisting(_) => {
498 bug!("optimize_and_codegen: called with ModuleSource::Preexisting")
502 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
504 let module_name = module.name.clone();
505 let module_name = Some(&module_name[..]);
507 if config.emit_no_opt_bc {
508 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
509 let out = path2cstr(&out);
510 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
513 if config.opt_level.is_some() {
514 // Create the two optimizing pass managers. These mirror what clang
515 // does, and are by populated by LLVM's default PassManagerBuilder.
516 // Each manager has a different set of passes, but they also share
517 // some common passes.
518 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
519 let mpm = llvm::LLVMCreatePassManager();
521 // If we're verifying or linting, add them to the function pass
523 let addpass = |pass_name: &str| {
524 let pass_name = CString::new(pass_name).unwrap();
525 let pass = llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr());
529 let pass_manager = match llvm::LLVMRustPassKind(pass) {
530 llvm::PassKind::Function => fpm,
531 llvm::PassKind::Module => mpm,
532 llvm::PassKind::Other => {
533 diag_handler.err("Encountered LLVM pass kind we can't handle");
537 llvm::LLVMRustAddPass(pass_manager, pass);
541 if config.verify_llvm_ir { assert!(addpass("verify")); }
542 if !config.no_prepopulate_passes {
543 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
544 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
545 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
546 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal;
547 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
548 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
549 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
553 for pass in &config.passes {
555 diag_handler.warn(&format!("unknown pass `{}`, ignoring",
560 for pass in &cgcx.plugin_passes {
562 diag_handler.err(&format!("a plugin asked for LLVM pass \
563 `{}` but LLVM does not \
564 recognize it", pass));
568 diag_handler.abort_if_errors();
570 // Finally, run the actual optimization passes
571 time_ext(config.time_passes,
573 &format!("llvm function passes [{}]", module_name.unwrap()),
575 llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
577 timeline.record("fpm");
578 time_ext(config.time_passes,
580 &format!("llvm module passes [{}]", module_name.unwrap()),
582 llvm::LLVMRunPassManager(mpm, llmod)
585 // Deallocate managers that we're now done with
586 llvm::LLVMDisposePassManager(fpm);
587 llvm::LLVMDisposePassManager(mpm);
592 fn generate_lto_work(cgcx: &CodegenContext,
593 modules: Vec<ModuleCodegen>)
594 -> Vec<(WorkItem, u64)>
596 let mut timeline = cgcx.time_graph.as_ref().map(|tg| {
597 tg.start(CODEGEN_WORKER_TIMELINE,
598 CODEGEN_WORK_PACKAGE_KIND,
600 }).unwrap_or(Timeline::noop());
601 let lto_modules = lto::run(cgcx, modules, &mut timeline)
602 .unwrap_or_else(|e| e.raise());
604 lto_modules.into_iter().map(|module| {
605 let cost = module.cost();
606 (WorkItem::LTO(module), cost)
610 unsafe fn codegen(cgcx: &CodegenContext,
611 diag_handler: &Handler,
612 module: ModuleCodegen,
613 config: &ModuleConfig,
614 timeline: &mut Timeline)
615 -> Result<CompiledModule, FatalError>
617 timeline.record("codegen");
619 let (llmod, llcx, tm) = match module.source {
620 ModuleSource::Codegened(ref llvm) => (llvm.llmod(), &*llvm.llcx, &*llvm.tm),
621 ModuleSource::Preexisting(_) => {
622 bug!("codegen: called with ModuleSource::Preexisting")
625 let module_name = module.name.clone();
626 let module_name = Some(&module_name[..]);
627 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
629 if cgcx.msvc_imps_needed {
630 create_msvc_imps(cgcx, llcx, llmod);
633 // A codegen-specific pass manager is used to generate object
634 // files for an LLVM module.
636 // Apparently each of these pass managers is a one-shot kind of
637 // thing, so we create a new one for each type of output. The
638 // pass manager passed to the closure should be ensured to not
639 // escape the closure itself, and the manager should only be
641 unsafe fn with_codegen<F, R>(tm: TargetMachineRef,
642 llmod: &llvm::Module,
645 where F: FnOnce(PassManagerRef) -> R,
647 let cpm = llvm::LLVMCreatePassManager();
648 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
649 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
653 // If we don't have the integrated assembler, then we need to emit asm
654 // from LLVM and use `gcc` to create the object file.
655 let asm_to_obj = config.emit_obj && config.no_integrated_as;
657 // Change what we write and cleanup based on whether obj files are
658 // just llvm bitcode. In that case write bitcode, and possibly
659 // delete the bitcode if it wasn't requested. Don't generate the
660 // machine code, instead copy the .o file from the .bc
661 let write_bc = config.emit_bc || config.obj_is_bitcode;
662 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
663 let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
664 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
666 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
667 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
670 if write_bc || config.emit_bc_compressed || config.embed_bitcode {
673 let data = if llvm::LLVMRustThinLTOAvailable() {
674 thin = ThinBuffer::new(llmod);
677 old = ModuleBuffer::new(llmod);
680 timeline.record("make-bc");
683 if let Err(e) = fs::write(&bc_out, data) {
684 diag_handler.err(&format!("failed to write bytecode: {}", e));
686 timeline.record("write-bc");
689 if config.embed_bitcode {
690 embed_bitcode(cgcx, llcx, llmod, Some(data));
691 timeline.record("embed-bc");
694 if config.emit_bc_compressed {
695 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
696 let data = bytecode::encode(&module.llmod_id, data);
697 if let Err(e) = fs::write(&dst, data) {
698 diag_handler.err(&format!("failed to write bytecode: {}", e));
700 timeline.record("compress-bc");
702 } else if config.embed_bitcode_marker {
703 embed_bitcode(cgcx, llcx, llmod, None);
706 time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
707 || -> Result<(), FatalError> {
709 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
710 let out = path2cstr(&out);
712 extern "C" fn demangle_callback(input_ptr: *const c_char,
714 output_ptr: *mut c_char,
715 output_len: size_t) -> size_t {
717 slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
720 let input = match str::from_utf8(input) {
725 let output = unsafe {
726 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
728 let mut cursor = io::Cursor::new(output);
730 let demangled = match rustc_demangle::try_demangle(input) {
735 if let Err(_) = write!(cursor, "{:#}", demangled) {
736 // Possible only if provided buffer is not big enough
740 cursor.position() as size_t
743 with_codegen(tm, llmod, config.no_builtins, |cpm| {
744 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
745 llvm::LLVMDisposePassManager(cpm);
747 timeline.record("ir");
750 if config.emit_asm || asm_to_obj {
751 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
753 // We can't use the same module for asm and binary output, because that triggers
754 // various errors like invalid IR or broken binaries, so we might have to clone the
755 // module to produce the asm output
756 let llmod = if config.emit_obj {
757 llvm::LLVMCloneModule(llmod)
761 with_codegen(tm, llmod, config.no_builtins, |cpm| {
762 write_output_file(diag_handler, tm, cpm, llmod, &path,
763 llvm::FileType::AssemblyFile)
765 timeline.record("asm");
769 with_codegen(tm, llmod, config.no_builtins, |cpm| {
770 write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
771 llvm::FileType::ObjectFile)
773 timeline.record("obj");
774 } else if asm_to_obj {
775 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
776 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
777 timeline.record("asm_to_obj");
779 if !config.emit_asm && !cgcx.save_temps {
780 drop(fs::remove_file(&assembly));
788 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
789 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
790 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
795 debug!("removing_bitcode {:?}", bc_out);
796 if let Err(e) = fs::remove_file(&bc_out) {
797 diag_handler.err(&format!("failed to remove bitcode: {}", e));
803 Ok(module.into_compiled_module(config.emit_obj,
805 config.emit_bc_compressed,
806 &cgcx.output_filenames))
809 /// Embed the bitcode of an LLVM module in the LLVM module itself.
811 /// This is done primarily for iOS where it appears to be standard to compile C
812 /// code at least with `-fembed-bitcode` which creates two sections in the
815 /// * __LLVM,__bitcode
816 /// * __LLVM,__cmdline
818 /// It appears *both* of these sections are necessary to get the linker to
819 /// recognize what's going on. For us though we just always throw in an empty
822 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
823 /// embed an empty section.
825 /// Basically all of this is us attempting to follow in the footsteps of clang
826 /// on iOS. See #35968 for lots more info.
827 unsafe fn embed_bitcode(cgcx: &CodegenContext,
828 llcx: &llvm::Context,
829 llmod: &llvm::Module,
830 bitcode: Option<&[u8]>) {
831 let llconst = C_bytes_in_context(llcx, bitcode.unwrap_or(&[]));
832 let llglobal = llvm::LLVMAddGlobal(
834 val_ty(llconst).to_ref(),
835 "rustc.embedded.module\0".as_ptr() as *const _,
837 llvm::LLVMSetInitializer(llglobal, llconst);
839 let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
840 cgcx.opts.target_triple.triple().contains("-darwin");
842 let section = if is_apple {
847 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
848 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
849 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
851 let llconst = C_bytes_in_context(llcx, &[]);
852 let llglobal = llvm::LLVMAddGlobal(
854 val_ty(llconst).to_ref(),
855 "rustc.embedded.cmdline\0".as_ptr() as *const _,
857 llvm::LLVMSetInitializer(llglobal, llconst);
858 let section = if is_apple {
863 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
864 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
867 pub(crate) struct CompiledModules {
868 pub modules: Vec<CompiledModule>,
869 pub metadata_module: CompiledModule,
870 pub allocator_module: Option<CompiledModule>,
873 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
874 sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
875 sess.opts.output_types.contains_key(&OutputType::Exe)
878 pub fn start_async_codegen(tcx: TyCtxt,
879 time_graph: Option<TimeGraph>,
881 metadata: EncodedMetadata,
882 coordinator_receive: Receiver<Box<dyn Any + Send>>,
886 let crate_name = tcx.crate_name(LOCAL_CRATE);
887 let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
888 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
889 "windows_subsystem");
890 let windows_subsystem = subsystem.map(|subsystem| {
891 if subsystem != "windows" && subsystem != "console" {
892 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
893 `windows` and `console` are allowed",
896 subsystem.to_string()
899 let linker_info = LinkerInfo::new(tcx);
900 let crate_info = CrateInfo::new(tcx);
902 // Figure out what we actually need to build.
903 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
904 let mut metadata_config = ModuleConfig::new(vec![]);
905 let mut allocator_config = ModuleConfig::new(vec![]);
907 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
909 Sanitizer::Address => {
910 modules_config.passes.push("asan".to_owned());
911 modules_config.passes.push("asan-module".to_owned());
913 Sanitizer::Memory => {
914 modules_config.passes.push("msan".to_owned())
916 Sanitizer::Thread => {
917 modules_config.passes.push("tsan".to_owned())
923 if sess.opts.debugging_opts.profile {
924 modules_config.passes.push("insert-gcov-profiling".to_owned())
927 modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
928 modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
930 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
931 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
933 // Save all versions of the bytecode if we're saving our temporaries.
934 if sess.opts.cg.save_temps {
935 modules_config.emit_no_opt_bc = true;
936 modules_config.emit_bc = true;
937 modules_config.emit_lto_bc = true;
938 metadata_config.emit_bc = true;
939 allocator_config.emit_bc = true;
942 // Emit compressed bitcode files for the crate if we're emitting an rlib.
943 // Whenever an rlib is created, the bitcode is inserted into the archive in
944 // order to allow LTO against it.
945 if need_crate_bitcode_for_rlib(sess) {
946 modules_config.emit_bc_compressed = true;
947 allocator_config.emit_bc_compressed = true;
950 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
951 tcx.sess.target.target.options.no_integrated_as;
953 for output_type in sess.opts.output_types.keys() {
955 OutputType::Bitcode => { modules_config.emit_bc = true; }
956 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
957 OutputType::Assembly => {
958 modules_config.emit_asm = true;
959 // If we're not using the LLVM assembler, this function
960 // could be invoked specially with output_type_assembly, so
961 // in this case we still want the metadata object file.
962 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
963 metadata_config.emit_obj = true;
964 allocator_config.emit_obj = true;
967 OutputType::Object => { modules_config.emit_obj = true; }
968 OutputType::Metadata => { metadata_config.emit_obj = true; }
970 modules_config.emit_obj = true;
971 metadata_config.emit_obj = true;
972 allocator_config.emit_obj = true;
974 OutputType::Mir => {}
975 OutputType::DepInfo => {}
979 modules_config.set_flags(sess, no_builtins);
980 metadata_config.set_flags(sess, no_builtins);
981 allocator_config.set_flags(sess, no_builtins);
983 // Exclude metadata and allocator modules from time_passes output, since
984 // they throw off the "LLVM passes" measurement.
985 metadata_config.time_passes = false;
986 allocator_config.time_passes = false;
988 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
989 let (codegen_worker_send, codegen_worker_receive) = channel();
991 let coordinator_thread = start_executing_work(tcx,
997 sess.jobserver.clone(),
999 Arc::new(modules_config),
1000 Arc::new(metadata_config),
1001 Arc::new(allocator_config));
1012 coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
1013 codegen_worker_receive,
1014 shared_emitter_main,
1015 future: coordinator_thread,
1016 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1020 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
1022 compiled_modules: &CompiledModules
1023 ) -> FxHashMap<WorkProductId, WorkProduct> {
1024 let mut work_products = FxHashMap::default();
1026 if sess.opts.incremental.is_none() {
1027 return work_products;
1030 for module in compiled_modules.modules.iter() {
1031 let mut files = vec![];
1033 if let Some(ref path) = module.object {
1034 files.push((WorkProductFileKind::Object, path.clone()));
1036 if let Some(ref path) = module.bytecode {
1037 files.push((WorkProductFileKind::Bytecode, path.clone()));
1039 if let Some(ref path) = module.bytecode_compressed {
1040 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
1043 if let Some((id, product)) =
1044 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
1045 work_products.insert(id, product);
1052 fn produce_final_output_artifacts(sess: &Session,
1053 compiled_modules: &CompiledModules,
1054 crate_output: &OutputFilenames) {
1055 let mut user_wants_bitcode = false;
1056 let mut user_wants_objects = false;
1058 // Produce final compile outputs.
1059 let copy_gracefully = |from: &Path, to: &Path| {
1060 if let Err(e) = fs::copy(from, to) {
1061 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
1065 let copy_if_one_unit = |output_type: OutputType,
1066 keep_numbered: bool| {
1067 if compiled_modules.modules.len() == 1 {
1068 // 1) Only one codegen unit. In this case it's no difficulty
1069 // to copy `foo.0.x` to `foo.x`.
1070 let module_name = Some(&compiled_modules.modules[0].name[..]);
1071 let path = crate_output.temp_path(output_type, module_name);
1072 copy_gracefully(&path,
1073 &crate_output.path(output_type));
1074 if !sess.opts.cg.save_temps && !keep_numbered {
1075 // The user just wants `foo.x`, not `foo.#module-name#.x`.
1076 remove(sess, &path);
1079 let ext = crate_output.temp_path(output_type, None)
1086 if crate_output.outputs.contains_key(&output_type) {
1087 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
1088 // no good solution for this case, so warn the user.
1089 sess.warn(&format!("ignoring emit path because multiple .{} files \
1090 were produced", ext));
1091 } else if crate_output.single_output_file.is_some() {
1092 // 3) Multiple codegen units, with `-o some_name`. We have
1093 // no good solution for this case, so warn the user.
1094 sess.warn(&format!("ignoring -o because multiple .{} files \
1095 were produced", ext));
1097 // 4) Multiple codegen units, but no explicit name. We
1098 // just leave the `foo.0.x` files in place.
1099 // (We don't have to do any work in this case.)
1104 // Flag to indicate whether the user explicitly requested bitcode.
1105 // Otherwise, we produced it only as a temporary output, and will need
1106 // to get rid of it.
1107 for output_type in crate_output.outputs.keys() {
1108 match *output_type {
1109 OutputType::Bitcode => {
1110 user_wants_bitcode = true;
1111 // Copy to .bc, but always keep the .0.bc. There is a later
1112 // check to figure out if we should delete .0.bc files, or keep
1113 // them for making an rlib.
1114 copy_if_one_unit(OutputType::Bitcode, true);
1116 OutputType::LlvmAssembly => {
1117 copy_if_one_unit(OutputType::LlvmAssembly, false);
1119 OutputType::Assembly => {
1120 copy_if_one_unit(OutputType::Assembly, false);
1122 OutputType::Object => {
1123 user_wants_objects = true;
1124 copy_if_one_unit(OutputType::Object, true);
1127 OutputType::Metadata |
1129 OutputType::DepInfo => {}
1133 // Clean up unwanted temporary files.
1135 // We create the following files by default:
1136 // - #crate#.#module-name#.bc
1137 // - #crate#.#module-name#.o
1138 // - #crate#.crate.metadata.bc
1139 // - #crate#.crate.metadata.o
1140 // - #crate#.o (linked from crate.##.o)
1141 // - #crate#.bc (copied from crate.##.bc)
1142 // We may create additional files if requested by the user (through
1143 // `-C save-temps` or `--emit=` flags).
1145 if !sess.opts.cg.save_temps {
1146 // Remove the temporary .#module-name#.o objects. If the user didn't
1147 // explicitly request bitcode (with --emit=bc), and the bitcode is not
1148 // needed for building an rlib, then we must remove .#module-name#.bc as
1151 // Specific rules for keeping .#module-name#.bc:
1152 // - If the user requested bitcode (`user_wants_bitcode`), and
1153 // codegen_units > 1, then keep it.
1154 // - If the user requested bitcode but codegen_units == 1, then we
1155 // can toss .#module-name#.bc because we copied it to .bc earlier.
1156 // - If we're not building an rlib and the user didn't request
1157 // bitcode, then delete .#module-name#.bc.
1158 // If you change how this works, also update back::link::link_rlib,
1159 // where .#module-name#.bc files are (maybe) deleted after making an
1161 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
1163 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
1165 let keep_numbered_objects = needs_crate_object ||
1166 (user_wants_objects && sess.codegen_units() > 1);
1168 for module in compiled_modules.modules.iter() {
1169 if let Some(ref path) = module.object {
1170 if !keep_numbered_objects {
1175 if let Some(ref path) = module.bytecode {
1176 if !keep_numbered_bitcode {
1182 if !user_wants_bitcode {
1183 if let Some(ref path) = compiled_modules.metadata_module.bytecode {
1184 remove(sess, &path);
1187 if let Some(ref allocator_module) = compiled_modules.allocator_module {
1188 if let Some(ref path) = allocator_module.bytecode {
1195 // We leave the following files around by default:
1197 // - #crate#.crate.metadata.o
1199 // These are used in linking steps and will be cleaned up afterward.
1202 pub(crate) fn dump_incremental_data(codegen_results: &CodegenResults) {
1203 println!("[incremental] Re-using {} out of {} modules",
1204 codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
1205 codegen_results.modules.len());
1209 Optimize(ModuleCodegen),
1210 LTO(lto::LtoModuleCodegen),
1214 fn kind(&self) -> ModuleKind {
1216 WorkItem::Optimize(ref m) => m.kind,
1217 WorkItem::LTO(_) => ModuleKind::Regular,
1221 fn name(&self) -> String {
1223 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
1224 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
1229 enum WorkItemResult {
1230 Compiled(CompiledModule),
1231 NeedsLTO(ModuleCodegen),
1234 fn execute_work_item(cgcx: &CodegenContext,
1235 work_item: WorkItem,
1236 timeline: &mut Timeline)
1237 -> Result<WorkItemResult, FatalError>
1239 let diag_handler = cgcx.create_diag_handler();
1240 let config = cgcx.config(work_item.kind());
1241 let module = match work_item {
1242 WorkItem::Optimize(module) => module,
1243 WorkItem::LTO(mut lto) => {
1245 let module = lto.optimize(cgcx, timeline)?;
1246 let module = codegen(cgcx, &diag_handler, module, config, timeline)?;
1247 return Ok(WorkItemResult::Compiled(module))
1251 let module_name = module.name.clone();
1253 let pre_existing = match module.source {
1254 ModuleSource::Codegened(_) => None,
1255 ModuleSource::Preexisting(ref wp) => Some(wp.clone()),
1258 if let Some(wp) = pre_existing {
1259 let incr_comp_session_dir = cgcx.incr_comp_session_dir
1262 let name = &module.name;
1263 let mut object = None;
1264 let mut bytecode = None;
1265 let mut bytecode_compressed = None;
1266 for (kind, saved_file) in wp.saved_files {
1267 let obj_out = match kind {
1268 WorkProductFileKind::Object => {
1269 let path = cgcx.output_filenames.temp_path(OutputType::Object, Some(name));
1270 object = Some(path.clone());
1273 WorkProductFileKind::Bytecode => {
1274 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(name));
1275 bytecode = Some(path.clone());
1278 WorkProductFileKind::BytecodeCompressed => {
1279 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(name))
1280 .with_extension(RLIB_BYTECODE_EXTENSION);
1281 bytecode_compressed = Some(path.clone());
1285 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1287 debug!("copying pre-existing module `{}` from {:?} to {}",
1291 match link_or_copy(&source_file, &obj_out) {
1294 diag_handler.err(&format!("unable to copy {} to {}: {}",
1295 source_file.display(),
1301 assert_eq!(object.is_some(), config.emit_obj);
1302 assert_eq!(bytecode.is_some(), config.emit_bc);
1303 assert_eq!(bytecode_compressed.is_some(), config.emit_bc_compressed);
1305 Ok(WorkItemResult::Compiled(CompiledModule {
1306 llmod_id: module.llmod_id.clone(),
1308 kind: ModuleKind::Regular,
1312 bytecode_compressed,
1315 debug!("llvm-optimizing {:?}", module_name);
1318 optimize(cgcx, &diag_handler, &module, config, timeline)?;
1320 // After we've done the initial round of optimizations we need to
1321 // decide whether to synchronously codegen this module or ship it
1322 // back to the coordinator thread for further LTO processing (which
1323 // has to wait for all the initial modules to be optimized).
1325 // Here we dispatch based on the `cgcx.lto` and kind of module we're
1327 let needs_lto = match cgcx.lto {
1330 // Here we've got a full crate graph LTO requested. We ignore
1331 // this, however, if the crate type is only an rlib as there's
1332 // no full crate graph to process, that'll happen later.
1334 // This use case currently comes up primarily for targets that
1335 // require LTO so the request for LTO is always unconditionally
1336 // passed down to the backend, but we don't actually want to do
1337 // anything about it yet until we've got a final product.
1338 Lto::Yes | Lto::Fat | Lto::Thin => {
1339 cgcx.crate_types.len() != 1 ||
1340 cgcx.crate_types[0] != config::CrateTypeRlib
1343 // When we're automatically doing ThinLTO for multi-codegen-unit
1344 // builds we don't actually want to LTO the allocator modules if
1345 // it shows up. This is due to various linker shenanigans that
1346 // we'll encounter later.
1348 // Additionally here's where we also factor in the current LLVM
1349 // version. If it doesn't support ThinLTO we skip this.
1351 module.kind != ModuleKind::Allocator &&
1352 llvm::LLVMRustThinLTOAvailable()
1356 // Metadata modules never participate in LTO regardless of the lto
1358 let needs_lto = needs_lto && module.kind != ModuleKind::Metadata;
1360 // Don't run LTO passes when cross-lang LTO is enabled. The linker
1361 // will do that for us in this case.
1362 let needs_lto = needs_lto &&
1363 !cgcx.opts.debugging_opts.cross_lang_lto.enabled();
1366 Ok(WorkItemResult::NeedsLTO(module))
1368 let module = codegen(cgcx, &diag_handler, module, config, timeline)?;
1369 Ok(WorkItemResult::Compiled(module))
1376 Token(io::Result<Acquired>),
1378 result: ModuleCodegen,
1382 result: Result<CompiledModule, ()>,
1386 llvm_work_item: WorkItem,
1395 code: Option<DiagnosticId>,
1399 #[derive(PartialEq, Clone, Copy, Debug)]
1400 enum MainThreadWorkerState {
1406 fn start_executing_work(tcx: TyCtxt,
1407 crate_info: &CrateInfo,
1408 shared_emitter: SharedEmitter,
1409 codegen_worker_send: Sender<Message>,
1410 coordinator_receive: Receiver<Box<dyn Any + Send>>,
1413 time_graph: Option<TimeGraph>,
1414 modules_config: Arc<ModuleConfig>,
1415 metadata_config: Arc<ModuleConfig>,
1416 allocator_config: Arc<ModuleConfig>)
1417 -> thread::JoinHandle<Result<CompiledModules, ()>> {
1418 let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1419 let sess = tcx.sess;
1421 // Compute the set of symbols we need to retain when doing LTO (if we need to)
1422 let exported_symbols = {
1423 let mut exported_symbols = FxHashMap();
1425 let copy_symbols = |cnum| {
1426 let symbols = tcx.exported_symbols(cnum)
1428 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1436 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1437 Some(Arc::new(exported_symbols))
1439 Lto::Yes | Lto::Fat | Lto::Thin => {
1440 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1441 for &cnum in tcx.crates().iter() {
1442 exported_symbols.insert(cnum, copy_symbols(cnum));
1444 Some(Arc::new(exported_symbols))
1449 // First up, convert our jobserver into a helper thread so we can use normal
1450 // mpsc channels to manage our messages and such.
1451 // After we've requested tokens then we'll, when we can,
1452 // get tokens on `coordinator_receive` which will
1453 // get managed in the main loop below.
1454 let coordinator_send2 = coordinator_send.clone();
1455 let helper = jobserver.into_helper_thread(move |token| {
1456 drop(coordinator_send2.send(Box::new(Message::Token(token))));
1457 }).expect("failed to spawn helper thread");
1459 let mut each_linked_rlib_for_lto = Vec::new();
1460 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1461 if link::ignored_for_lto(sess, crate_info, cnum) {
1464 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1467 let assembler_cmd = if modules_config.no_integrated_as {
1468 // HACK: currently we use linker (gcc) as our assembler
1469 let (name, mut cmd) = get_linker(sess);
1470 cmd.args(&sess.target.target.options.asm_args);
1471 Some(Arc::new(AssemblerCommand {
1479 let cgcx = CodegenContext {
1480 crate_types: sess.crate_types.borrow().clone(),
1481 each_linked_rlib_for_lto,
1483 no_landing_pads: sess.no_landing_pads(),
1484 fewer_names: sess.fewer_names(),
1485 save_temps: sess.opts.cg.save_temps,
1486 opts: Arc::new(sess.opts.clone()),
1487 time_passes: sess.time_passes(),
1489 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1490 remark: sess.opts.cg.remark.clone(),
1492 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1494 diag_emitter: shared_emitter.clone(),
1496 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1497 regular_module_config: modules_config,
1498 metadata_module_config: metadata_config,
1499 allocator_module_config: allocator_config,
1500 tm_factory: target_machine_factory(tcx.sess, false),
1502 msvc_imps_needed: msvc_imps_needed(tcx),
1503 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1504 debuginfo: tcx.sess.opts.debuginfo,
1508 // This is the "main loop" of parallel work happening for parallel codegen.
1509 // It's here that we manage parallelism, schedule work, and work with
1510 // messages coming from clients.
1512 // There are a few environmental pre-conditions that shape how the system
1515 // - Error reporting only can happen on the main thread because that's the
1516 // only place where we have access to the compiler `Session`.
1517 // - LLVM work can be done on any thread.
1518 // - Codegen can only happen on the main thread.
1519 // - Each thread doing substantial work most be in possession of a `Token`
1520 // from the `Jobserver`.
1521 // - The compiler process always holds one `Token`. Any additional `Tokens`
1522 // have to be requested from the `Jobserver`.
1526 // The error reporting restriction is handled separately from the rest: We
1527 // set up a `SharedEmitter` the holds an open channel to the main thread.
1528 // When an error occurs on any thread, the shared emitter will send the
1529 // error message to the receiver main thread (`SharedEmitterMain`). The
1530 // main thread will periodically query this error message queue and emit
1531 // any error messages it has received. It might even abort compilation if
1532 // has received a fatal error. In this case we rely on all other threads
1533 // being torn down automatically with the main thread.
1534 // Since the main thread will often be busy doing codegen work, error
1535 // reporting will be somewhat delayed, since the message queue can only be
1536 // checked in between to work packages.
1538 // Work Processing Infrastructure
1539 // ==============================
1540 // The work processing infrastructure knows three major actors:
1542 // - the coordinator thread,
1543 // - the main thread, and
1544 // - LLVM worker threads
1546 // The coordinator thread is running a message loop. It instructs the main
1547 // thread about what work to do when, and it will spawn off LLVM worker
1548 // threads as open LLVM WorkItems become available.
1550 // The job of the main thread is to codegen CGUs into LLVM work package
1551 // (since the main thread is the only thread that can do this). The main
1552 // thread will block until it receives a message from the coordinator, upon
1553 // which it will codegen one CGU, send it to the coordinator and block
1554 // again. This way the coordinator can control what the main thread is
1557 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1558 // available, it will spawn off a new LLVM worker thread and let it process
1559 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1560 // it will just shut down, which also frees all resources associated with
1561 // the given LLVM module, and sends a message to the coordinator that the
1562 // has been completed.
1566 // The scheduler's goal is to minimize the time it takes to complete all
1567 // work there is, however, we also want to keep memory consumption low
1568 // if possible. These two goals are at odds with each other: If memory
1569 // consumption were not an issue, we could just let the main thread produce
1570 // LLVM WorkItems at full speed, assuring maximal utilization of
1571 // Tokens/LLVM worker threads. However, since codegen usual is faster
1572 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1573 // WorkItem potentially holds on to a substantial amount of memory.
1575 // So the actual goal is to always produce just enough LLVM WorkItems as
1576 // not to starve our LLVM worker threads. That means, once we have enough
1577 // WorkItems in our queue, we can block the main thread, so it does not
1578 // produce more until we need them.
1580 // Doing LLVM Work on the Main Thread
1581 // ----------------------------------
1582 // Since the main thread owns the compiler processes implicit `Token`, it is
1583 // wasteful to keep it blocked without doing any work. Therefore, what we do
1584 // in this case is: We spawn off an additional LLVM worker thread that helps
1585 // reduce the queue. The work it is doing corresponds to the implicit
1586 // `Token`. The coordinator will mark the main thread as being busy with
1587 // LLVM work. (The actual work happens on another OS thread but we just care
1588 // about `Tokens`, not actual threads).
1590 // When any LLVM worker thread finishes while the main thread is marked as
1591 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1592 // of the just finished thread to the LLVM worker thread that is working on
1593 // behalf of the main thread's implicit Token, thus freeing up the main
1594 // thread again. The coordinator can then again decide what the main thread
1595 // should do. This allows the coordinator to make decisions at more points
1598 // Striking a Balance between Throughput and Memory Consumption
1599 // ------------------------------------------------------------
1600 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1601 // memory consumption as low as possible, are in conflict with each other,
1602 // we have to find a trade off between them. Right now, the goal is to keep
1603 // all workers busy, which means that no worker should find the queue empty
1604 // when it is ready to start.
1605 // How do we do achieve this? Good question :) We actually never know how
1606 // many `Tokens` are potentially available so it's hard to say how much to
1607 // fill up the queue before switching the main thread to LLVM work. Also we
1608 // currently don't have a means to estimate how long a running LLVM worker
1609 // will still be busy with it's current WorkItem. However, we know the
1610 // maximal count of available Tokens that makes sense (=the number of CPU
1611 // cores), so we can take a conservative guess. The heuristic we use here
1612 // is implemented in the `queue_full_enough()` function.
1614 // Some Background on Jobservers
1615 // -----------------------------
1616 // It's worth also touching on the management of parallelism here. We don't
1617 // want to just spawn a thread per work item because while that's optimal
1618 // parallelism it may overload a system with too many threads or violate our
1619 // configuration for the maximum amount of cpu to use for this process. To
1620 // manage this we use the `jobserver` crate.
1622 // Job servers are an artifact of GNU make and are used to manage
1623 // parallelism between processes. A jobserver is a glorified IPC semaphore
1624 // basically. Whenever we want to run some work we acquire the semaphore,
1625 // and whenever we're done with that work we release the semaphore. In this
1626 // manner we can ensure that the maximum number of parallel workers is
1627 // capped at any one point in time.
1629 // LTO and the coordinator thread
1630 // ------------------------------
1632 // The final job the coordinator thread is responsible for is managing LTO
1633 // and how that works. When LTO is requested what we'll to is collect all
1634 // optimized LLVM modules into a local vector on the coordinator. Once all
1635 // modules have been codegened and optimized we hand this to the `lto`
1636 // module for further optimization. The `lto` module will return back a list
1637 // of more modules to work on, which the coordinator will continue to spawn
1640 // Each LLVM module is automatically sent back to the coordinator for LTO if
1641 // necessary. There's already optimizations in place to avoid sending work
1642 // back to the coordinator if LTO isn't requested.
1643 return thread::spawn(move || {
1644 // We pretend to be within the top-level LLVM time-passes task here:
1647 let max_workers = ::num_cpus::get();
1648 let mut worker_id_counter = 0;
1649 let mut free_worker_ids = Vec::new();
1650 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1651 if let Some(id) = free_worker_ids.pop() {
1654 let id = worker_id_counter;
1655 worker_id_counter += 1;
1660 // This is where we collect codegen units that have gone all the way
1661 // through codegen and LLVM.
1662 let mut compiled_modules = vec![];
1663 let mut compiled_metadata_module = None;
1664 let mut compiled_allocator_module = None;
1665 let mut needs_lto = Vec::new();
1666 let mut started_lto = false;
1668 // This flag tracks whether all items have gone through codegens
1669 let mut codegen_done = false;
1671 // This is the queue of LLVM work items that still need processing.
1672 let mut work_items = Vec::<(WorkItem, u64)>::new();
1674 // This are the Jobserver Tokens we currently hold. Does not include
1675 // the implicit Token the compiler process owns no matter what.
1676 let mut tokens = Vec::new();
1678 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1679 let mut running = 0;
1681 let mut llvm_start_time = None;
1683 // Run the message loop while there's still anything that needs message
1685 while !codegen_done ||
1686 work_items.len() > 0 ||
1688 needs_lto.len() > 0 ||
1689 main_thread_worker_state != MainThreadWorkerState::Idle {
1691 // While there are still CGUs to be codegened, the coordinator has
1692 // to decide how to utilize the compiler processes implicit Token:
1693 // For codegenning more CGU or for running them through LLVM.
1695 if main_thread_worker_state == MainThreadWorkerState::Idle {
1696 if !queue_full_enough(work_items.len(), running, max_workers) {
1697 // The queue is not full enough, codegen more items:
1698 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1699 panic!("Could not send Message::CodegenItem to main thread")
1701 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1703 // The queue is full enough to not let the worker
1704 // threads starve. Use the implicit Token to do some
1706 let (item, _) = work_items.pop()
1707 .expect("queue empty - queue_full_enough() broken?");
1708 let cgcx = CodegenContext {
1709 worker: get_worker_id(&mut free_worker_ids),
1712 maybe_start_llvm_timer(cgcx.config(item.kind()),
1713 &mut llvm_start_time);
1714 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1715 spawn_work(cgcx, item);
1719 // If we've finished everything related to normal codegen
1720 // then it must be the case that we've got some LTO work to do.
1721 // Perform the serial work here of figuring out what we're
1722 // going to LTO and then push a bunch of work items onto our
1724 if work_items.len() == 0 &&
1726 main_thread_worker_state == MainThreadWorkerState::Idle {
1727 assert!(!started_lto);
1728 assert!(needs_lto.len() > 0);
1730 let modules = mem::replace(&mut needs_lto, Vec::new());
1731 for (work, cost) in generate_lto_work(&cgcx, modules) {
1732 let insertion_index = work_items
1733 .binary_search_by_key(&cost, |&(_, cost)| cost)
1734 .unwrap_or_else(|e| e);
1735 work_items.insert(insertion_index, (work, cost));
1736 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1737 helper.request_token();
1742 // In this branch, we know that everything has been codegened,
1743 // so it's just a matter of determining whether the implicit
1744 // Token is free to use for LLVM work.
1745 match main_thread_worker_state {
1746 MainThreadWorkerState::Idle => {
1747 if let Some((item, _)) = work_items.pop() {
1748 let cgcx = CodegenContext {
1749 worker: get_worker_id(&mut free_worker_ids),
1752 maybe_start_llvm_timer(cgcx.config(item.kind()),
1753 &mut llvm_start_time);
1754 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1755 spawn_work(cgcx, item);
1757 // There is no unstarted work, so let the main thread
1758 // take over for a running worker. Otherwise the
1759 // implicit token would just go to waste.
1760 // We reduce the `running` counter by one. The
1761 // `tokens.truncate()` below will take care of
1762 // giving the Token back.
1763 debug_assert!(running > 0);
1765 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1768 MainThreadWorkerState::Codegenning => {
1769 bug!("codegen worker should not be codegenning after \
1770 codegen was already completed")
1772 MainThreadWorkerState::LLVMing => {
1773 // Already making good use of that token
1778 // Spin up what work we can, only doing this while we've got available
1779 // parallelism slots and work left to spawn.
1780 while work_items.len() > 0 && running < tokens.len() {
1781 let (item, _) = work_items.pop().unwrap();
1783 maybe_start_llvm_timer(cgcx.config(item.kind()),
1784 &mut llvm_start_time);
1786 let cgcx = CodegenContext {
1787 worker: get_worker_id(&mut free_worker_ids),
1791 spawn_work(cgcx, item);
1795 // Relinquish accidentally acquired extra tokens
1796 tokens.truncate(running);
1798 let msg = coordinator_receive.recv().unwrap();
1799 match *msg.downcast::<Message>().ok().unwrap() {
1800 // Save the token locally and the next turn of the loop will use
1801 // this to spawn a new unit of work, or it may get dropped
1802 // immediately if we have no more work to spawn.
1803 Message::Token(token) => {
1808 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1809 // If the main thread token is used for LLVM work
1810 // at the moment, we turn that thread into a regular
1811 // LLVM worker thread, so the main thread is free
1812 // to react to codegen demand.
1813 main_thread_worker_state = MainThreadWorkerState::Idle;
1818 let msg = &format!("failed to acquire jobserver token: {}", e);
1819 shared_emitter.fatal(msg);
1820 // Exit the coordinator thread
1826 Message::CodegenDone { llvm_work_item, cost } => {
1827 // We keep the queue sorted by estimated processing cost,
1828 // so that more expensive items are processed earlier. This
1829 // is good for throughput as it gives the main thread more
1830 // time to fill up the queue and it avoids scheduling
1831 // expensive items to the end.
1832 // Note, however, that this is not ideal for memory
1833 // consumption, as LLVM module sizes are not evenly
1835 let insertion_index =
1836 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1837 let insertion_index = match insertion_index {
1838 Ok(idx) | Err(idx) => idx
1840 work_items.insert(insertion_index, (llvm_work_item, cost));
1842 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1843 helper.request_token();
1845 assert_eq!(main_thread_worker_state,
1846 MainThreadWorkerState::Codegenning);
1847 main_thread_worker_state = MainThreadWorkerState::Idle;
1850 Message::CodegenComplete => {
1851 codegen_done = true;
1852 assert_eq!(main_thread_worker_state,
1853 MainThreadWorkerState::Codegenning);
1854 main_thread_worker_state = MainThreadWorkerState::Idle;
1857 // If a thread exits successfully then we drop a token associated
1858 // with that worker and update our `running` count. We may later
1859 // re-acquire a token to continue running more work. We may also not
1860 // actually drop a token here if the worker was running with an
1861 // "ephemeral token"
1863 // Note that if the thread failed that means it panicked, so we
1864 // abort immediately.
1865 Message::Done { result: Ok(compiled_module), worker_id } => {
1866 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1867 main_thread_worker_state = MainThreadWorkerState::Idle;
1872 free_worker_ids.push(worker_id);
1874 match compiled_module.kind {
1875 ModuleKind::Regular => {
1876 compiled_modules.push(compiled_module);
1878 ModuleKind::Metadata => {
1879 assert!(compiled_metadata_module.is_none());
1880 compiled_metadata_module = Some(compiled_module);
1882 ModuleKind::Allocator => {
1883 assert!(compiled_allocator_module.is_none());
1884 compiled_allocator_module = Some(compiled_module);
1888 Message::NeedsLTO { result, worker_id } => {
1889 assert!(!started_lto);
1890 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1891 main_thread_worker_state = MainThreadWorkerState::Idle;
1896 free_worker_ids.push(worker_id);
1897 needs_lto.push(result);
1899 Message::Done { result: Err(()), worker_id: _ } => {
1900 shared_emitter.fatal("aborting due to worker thread failure");
1901 // Exit the coordinator thread
1904 Message::CodegenItem => {
1905 bug!("the coordinator should not receive codegen requests")
1910 if let Some(llvm_start_time) = llvm_start_time {
1911 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1912 // This is the top-level timing for all of LLVM, set the time-depth
1915 print_time_passes_entry(cgcx.time_passes,
1920 // Regardless of what order these modules completed in, report them to
1921 // the backend in the same order every time to ensure that we're handing
1922 // out deterministic results.
1923 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1925 let compiled_metadata_module = compiled_metadata_module
1926 .expect("Metadata module not compiled?");
1928 Ok(CompiledModules {
1929 modules: compiled_modules,
1930 metadata_module: compiled_metadata_module,
1931 allocator_module: compiled_allocator_module,
1935 // A heuristic that determines if we have enough LLVM WorkItems in the
1936 // queue so that the main thread can do LLVM work instead of codegen
1937 fn queue_full_enough(items_in_queue: usize,
1938 workers_running: usize,
1939 max_workers: usize) -> bool {
1941 items_in_queue > 0 &&
1942 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1945 fn maybe_start_llvm_timer(config: &ModuleConfig,
1946 llvm_start_time: &mut Option<Instant>) {
1947 // We keep track of the -Ztime-passes output manually,
1948 // since the closure-based interface does not fit well here.
1949 if config.time_passes {
1950 if llvm_start_time.is_none() {
1951 *llvm_start_time = Some(Instant::now());
1957 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1958 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
1959 time_graph::TimelineId(CODEGEN_WORKER_ID);
1960 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1961 time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
1962 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1963 time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
1965 fn spawn_work(cgcx: CodegenContext, work: WorkItem) {
1966 let depth = time_depth();
1968 thread::spawn(move || {
1969 set_time_depth(depth);
1971 // Set up a destructor which will fire off a message that we're done as
1974 coordinator_send: Sender<Box<dyn Any + Send>>,
1975 result: Option<WorkItemResult>,
1978 impl Drop for Bomb {
1979 fn drop(&mut self) {
1980 let worker_id = self.worker_id;
1981 let msg = match self.result.take() {
1982 Some(WorkItemResult::Compiled(m)) => {
1983 Message::Done { result: Ok(m), worker_id }
1985 Some(WorkItemResult::NeedsLTO(m)) => {
1986 Message::NeedsLTO { result: m, worker_id }
1988 None => Message::Done { result: Err(()), worker_id }
1990 drop(self.coordinator_send.send(Box::new(msg)));
1994 let mut bomb = Bomb {
1995 coordinator_send: cgcx.coordinator_send.clone(),
1997 worker_id: cgcx.worker,
2000 // Execute the work itself, and if it finishes successfully then flag
2001 // ourselves as a success as well.
2003 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
2004 // as a diagnostic was already sent off to the main thread - just
2005 // surface that there was an error in this worker.
2007 let timeline = cgcx.time_graph.as_ref().map(|tg| {
2008 tg.start(time_graph::TimelineId(cgcx.worker),
2009 LLVM_WORK_PACKAGE_KIND,
2012 let mut timeline = timeline.unwrap_or(Timeline::noop());
2013 execute_work_item(&cgcx, work, &mut timeline).ok()
2018 pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, object: &Path) {
2019 let assembler = cgcx.assembler_cmd
2021 .expect("cgcx.assembler_cmd is missing?");
2023 let pname = &assembler.name;
2024 let mut cmd = assembler.cmd.clone();
2025 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
2026 debug!("{:?}", cmd);
2028 match cmd.output() {
2030 if !prog.status.success() {
2031 let mut note = prog.stderr.clone();
2032 note.extend_from_slice(&prog.stdout);
2034 handler.struct_err(&format!("linking with `{}` failed: {}",
2037 .note(&format!("{:?}", &cmd))
2038 .note(str::from_utf8(¬e[..]).unwrap())
2040 handler.abort_if_errors();
2044 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
2045 handler.abort_if_errors();
2050 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
2051 config: &ModuleConfig,
2052 opt_level: llvm::CodeGenOptLevel,
2053 prepare_for_thin_lto: bool,
2054 f: &mut dyn FnMut(llvm::PassManagerBuilderRef)) {
2057 // Create the PassManagerBuilder for LLVM. We configure it with
2058 // reasonable defaults and prepare it to actually populate the pass
2060 let builder = llvm::LLVMPassManagerBuilderCreate();
2061 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
2062 let inline_threshold = config.inline_threshold;
2064 let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
2065 let s = if s.is_empty() { "default_%m.profraw" } else { s };
2066 CString::new(s.as_bytes()).unwrap()
2069 let pgo_use_path = if config.pgo_use.is_empty() {
2072 Some(CString::new(config.pgo_use.as_bytes()).unwrap())
2075 llvm::LLVMRustConfigurePassManagerBuilder(
2078 config.merge_functions,
2079 config.vectorize_slp,
2080 config.vectorize_loop,
2081 prepare_for_thin_lto,
2082 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2083 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2086 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
2088 if opt_size != llvm::CodeGenOptSizeNone {
2089 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
2092 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
2094 // Here we match what clang does (kinda). For O0 we only inline
2095 // always-inline functions (but don't add lifetime intrinsics), at O1 we
2096 // inline with lifetime intrinsics, and O2+ we add an inliner with a
2097 // thresholds copied from clang.
2098 match (opt_level, opt_size, inline_threshold) {
2100 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
2102 (llvm::CodeGenOptLevel::Aggressive, ..) => {
2103 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
2105 (_, llvm::CodeGenOptSizeDefault, _) => {
2106 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
2108 (_, llvm::CodeGenOptSizeAggressive, _) => {
2109 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
2111 (llvm::CodeGenOptLevel::None, ..) => {
2112 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
2114 (llvm::CodeGenOptLevel::Less, ..) => {
2115 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
2117 (llvm::CodeGenOptLevel::Default, ..) => {
2118 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
2120 (llvm::CodeGenOptLevel::Other, ..) => {
2121 bug!("CodeGenOptLevel::Other selected")
2126 llvm::LLVMPassManagerBuilderDispose(builder);
2130 enum SharedEmitterMessage {
2131 Diagnostic(Diagnostic),
2132 InlineAsmError(u32, String),
2138 pub struct SharedEmitter {
2139 sender: Sender<SharedEmitterMessage>,
2142 pub struct SharedEmitterMain {
2143 receiver: Receiver<SharedEmitterMessage>,
2146 impl SharedEmitter {
2147 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
2148 let (sender, receiver) = channel();
2150 (SharedEmitter { sender }, SharedEmitterMain { receiver })
2153 fn inline_asm_error(&self, cookie: u32, msg: String) {
2154 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
2157 fn fatal(&self, msg: &str) {
2158 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2162 impl Emitter for SharedEmitter {
2163 fn emit(&mut self, db: &DiagnosticBuilder) {
2164 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2166 code: db.code.clone(),
2169 for child in &db.children {
2170 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2171 msg: child.message(),
2176 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
2180 impl SharedEmitterMain {
2181 pub fn check(&self, sess: &Session, blocking: bool) {
2183 let message = if blocking {
2184 match self.receiver.recv() {
2185 Ok(message) => Ok(message),
2189 match self.receiver.try_recv() {
2190 Ok(message) => Ok(message),
2196 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2197 let handler = sess.diagnostic();
2200 handler.emit_with_code(&MultiSpan::new(),
2206 handler.emit(&MultiSpan::new(),
2212 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
2213 match Mark::from_u32(cookie).expn_info() {
2214 Some(ei) => sess.span_err(ei.call_site, &msg),
2215 None => sess.err(&msg),
2218 Ok(SharedEmitterMessage::AbortIfErrors) => {
2219 sess.abort_if_errors();
2221 Ok(SharedEmitterMessage::Fatal(msg)) => {
2233 pub struct OngoingCodegen {
2236 metadata: EncodedMetadata,
2237 windows_subsystem: Option<String>,
2238 linker_info: LinkerInfo,
2239 crate_info: CrateInfo,
2240 time_graph: Option<TimeGraph>,
2241 coordinator_send: Sender<Box<dyn Any + Send>>,
2242 codegen_worker_receive: Receiver<Message>,
2243 shared_emitter_main: SharedEmitterMain,
2244 future: thread::JoinHandle<Result<CompiledModules, ()>>,
2245 output_filenames: Arc<OutputFilenames>,
2248 impl OngoingCodegen {
2252 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
2253 self.shared_emitter_main.check(sess, true);
2254 let compiled_modules = match self.future.join() {
2255 Ok(Ok(compiled_modules)) => compiled_modules,
2257 sess.abort_if_errors();
2258 panic!("expected abort due to worker thread errors")
2261 sess.fatal("Error during codegen/LLVM phase.");
2265 sess.abort_if_errors();
2267 if let Some(time_graph) = self.time_graph {
2268 time_graph.dump(&format!("{}-timings", self.crate_name));
2271 let work_products = copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
2274 produce_final_output_artifacts(sess,
2276 &self.output_filenames);
2278 // FIXME: time_llvm_passes support - does this use a global context or
2280 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2281 unsafe { llvm::LLVMRustPrintPassTimings(); }
2285 crate_name: self.crate_name,
2287 metadata: self.metadata,
2288 windows_subsystem: self.windows_subsystem,
2289 linker_info: self.linker_info,
2290 crate_info: self.crate_info,
2292 modules: compiled_modules.modules,
2293 allocator_module: compiled_modules.allocator_module,
2294 metadata_module: compiled_modules.metadata_module,
2298 pub(crate) fn submit_pre_codegened_module_to_llvm(&self,
2300 module: ModuleCodegen) {
2301 self.wait_for_signal_to_codegen_item();
2302 self.check_for_errors(tcx.sess);
2304 // These are generally cheap and won't through off scheduling.
2306 submit_codegened_module_to_llvm(tcx, module, cost);
2309 pub fn codegen_finished(&self, tcx: TyCtxt) {
2310 self.wait_for_signal_to_codegen_item();
2311 self.check_for_errors(tcx.sess);
2312 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete)));
2315 pub fn check_for_errors(&self, sess: &Session) {
2316 self.shared_emitter_main.check(sess, false);
2319 pub fn wait_for_signal_to_codegen_item(&self) {
2320 match self.codegen_worker_receive.recv() {
2321 Ok(Message::CodegenItem) => {
2324 Ok(_) => panic!("unexpected message"),
2326 // One of the LLVM threads must have panicked, fall through so
2327 // error handling can be reached.
2333 pub(crate) fn submit_codegened_module_to_llvm(tcx: TyCtxt,
2334 module: ModuleCodegen,
2336 let llvm_work_item = WorkItem::Optimize(module);
2337 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2343 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2344 tcx.sess.target.target.options.is_like_msvc &&
2345 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib)
2348 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2349 // This is required to satisfy `dllimport` references to static data in .rlibs
2350 // when using MSVC linker. We do this only for data, as linker can fix up
2351 // code references on its own.
2352 // See #26591, #27438
2353 fn create_msvc_imps(cgcx: &CodegenContext, llcx: &llvm::Context, llmod: &llvm::Module) {
2354 if !cgcx.msvc_imps_needed {
2357 // The x86 ABI seems to require that leading underscores are added to symbol
2358 // names, so we need an extra underscore on 32-bit. There's also a leading
2359 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2360 // underscores added in front).
2361 let prefix = if cgcx.target_pointer_width == "32" {
2367 let i8p_ty = Type::i8p_llcx(llcx);
2368 let globals = base::iter_globals(llmod)
2370 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
2371 llvm::LLVMIsDeclaration(val) == 0
2374 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2375 let mut imp_name = prefix.as_bytes().to_vec();
2376 imp_name.extend(name.to_bytes());
2377 let imp_name = CString::new(imp_name).unwrap();
2380 .collect::<Vec<_>>();
2381 for (imp_name, val) in globals {
2382 let imp = llvm::LLVMAddGlobal(llmod,
2384 imp_name.as_ptr() as *const _);
2385 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
2386 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);