]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/back/write.rs
Rollup merge of #55745 - nnethercote:outlives_components-SmallVec, r=matthewjasper
[rust.git] / src / librustc_codegen_llvm / back / write.rs
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.
4 //
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.
10
11 use attributes;
12 use back::bytecode::{self, RLIB_BYTECODE_EXTENSION};
13 use back::lto::{self, ThinBuffer, SerializedModule};
14 use back::link::{self, get_linker, remove};
15 use base;
16 use consts;
17 use memmap;
18 use rustc_incremental::{copy_cgu_workproducts_to_incr_comp_cache_dir,
19                         in_incr_comp_dir, in_incr_comp_dir_sess};
20 use rustc::dep_graph::{WorkProduct, WorkProductId, WorkProductFileKind};
21 use rustc::dep_graph::cgu_reuse_tracker::CguReuseTracker;
22 use rustc::middle::cstore::EncodedMetadata;
23 use rustc::session::config::{self, OutputFilenames, OutputType, Passes, Sanitizer, Lto};
24 use rustc::session::Session;
25 use rustc::util::nodemap::FxHashMap;
26 use time_graph::{self, TimeGraph, Timeline};
27 use llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
28 use llvm_util;
29 use {CodegenResults, ModuleCodegen, CompiledModule, ModuleKind, // ModuleLlvm,
30      CachedModuleCodegen};
31 use CrateInfo;
32 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
33 use rustc::ty::TyCtxt;
34 use rustc::util::common::{time_ext, time_depth, set_time_depth, print_time_passes_entry};
35 use rustc_fs_util::{path2cstr, link_or_copy};
36 use rustc_data_structures::small_c_str::SmallCStr;
37 use rustc_data_structures::svh::Svh;
38 use rustc_codegen_utils::command::Command;
39 use rustc_codegen_utils::linker::LinkerInfo;
40 use rustc_codegen_utils::symbol_export::ExportedSymbols;
41 use errors::{self, Handler, Level, DiagnosticBuilder, FatalError, DiagnosticId};
42 use errors::emitter::{Emitter};
43 use syntax::attr;
44 use syntax::ext::hygiene::Mark;
45 use syntax_pos::MultiSpan;
46 use syntax_pos::symbol::Symbol;
47 use type_::Type;
48 use context::{is_pie_binary, get_reloc_model};
49 use common::{C_bytes_in_context, val_ty};
50 use jobserver::{Client, Acquired};
51 use rustc_demangle;
52
53 use std::any::Any;
54 use std::ffi::{CString, CStr};
55 use std::fs;
56 use std::io::{self, Write};
57 use std::mem;
58 use std::path::{Path, PathBuf};
59 use std::str;
60 use std::sync::Arc;
61 use std::sync::mpsc::{channel, Sender, Receiver};
62 use std::slice;
63 use std::time::Instant;
64 use std::thread;
65 use libc::{c_uint, c_void, c_char, size_t};
66
67 pub const RELOC_MODEL_ARGS : [(&'static str, llvm::RelocMode); 7] = [
68     ("pic", llvm::RelocMode::PIC),
69     ("static", llvm::RelocMode::Static),
70     ("default", llvm::RelocMode::Default),
71     ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
72     ("ropi", llvm::RelocMode::ROPI),
73     ("rwpi", llvm::RelocMode::RWPI),
74     ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
75 ];
76
77 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
78     ("small", llvm::CodeModel::Small),
79     ("kernel", llvm::CodeModel::Kernel),
80     ("medium", llvm::CodeModel::Medium),
81     ("large", llvm::CodeModel::Large),
82 ];
83
84 pub const TLS_MODEL_ARGS : [(&'static str, llvm::ThreadLocalMode); 4] = [
85     ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
86     ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
87     ("initial-exec", llvm::ThreadLocalMode::InitialExec),
88     ("local-exec", llvm::ThreadLocalMode::LocalExec),
89 ];
90
91 const PRE_THIN_LTO_BC_EXT: &str = "pre-thin-lto.bc";
92
93 pub fn llvm_err(handler: &errors::Handler, msg: String) -> FatalError {
94     match llvm::last_error() {
95         Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
96         None => handler.fatal(&msg),
97     }
98 }
99
100 pub fn write_output_file(
101         handler: &errors::Handler,
102         target: &'ll llvm::TargetMachine,
103         pm: &llvm::PassManager<'ll>,
104         m: &'ll llvm::Module,
105         output: &Path,
106         file_type: llvm::FileType) -> Result<(), FatalError> {
107     unsafe {
108         let output_c = path2cstr(output);
109         let result = llvm::LLVMRustWriteOutputFile(
110                 target, pm, m, output_c.as_ptr(), file_type);
111         if result.into_result().is_err() {
112             let msg = format!("could not write output to {}", output.display());
113             Err(llvm_err(handler, msg))
114         } else {
115             Ok(())
116         }
117     }
118 }
119
120 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
121     match optimize {
122       config::OptLevel::No => llvm::CodeGenOptLevel::None,
123       config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
124       config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
125       config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
126       _ => llvm::CodeGenOptLevel::Default,
127     }
128 }
129
130 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
131     match optimize {
132       config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
133       config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
134       _ => llvm::CodeGenOptSizeNone,
135     }
136 }
137
138 pub fn create_target_machine(
139     sess: &Session,
140     find_features: bool,
141 ) -> &'static mut llvm::TargetMachine {
142     target_machine_factory(sess, find_features)().unwrap_or_else(|err| {
143         llvm_err(sess.diagnostic(), err).raise()
144     })
145 }
146
147 // If find_features is true this won't access `sess.crate_types` by assuming
148 // that `is_pie_binary` is false. When we discover LLVM target features
149 // `sess.crate_types` is uninitialized so we cannot access it.
150 pub fn target_machine_factory(sess: &Session, find_features: bool)
151     -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>
152 {
153     let reloc_model = get_reloc_model(sess);
154
155     let opt_level = get_llvm_opt_level(sess.opts.optimize);
156     let use_softfp = sess.opts.cg.soft_float;
157
158     let ffunction_sections = sess.target.target.options.function_sections;
159     let fdata_sections = ffunction_sections;
160
161     let code_model_arg = sess.opts.cg.code_model.as_ref().or(
162         sess.target.target.options.code_model.as_ref(),
163     );
164
165     let code_model = match code_model_arg {
166         Some(s) => {
167             match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
168                 Some(x) => x.1,
169                 _ => {
170                     sess.err(&format!("{:?} is not a valid code model",
171                                       code_model_arg));
172                     sess.abort_if_errors();
173                     bug!();
174                 }
175             }
176         }
177         None => llvm::CodeModel::None,
178     };
179
180     let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
181     let mut singlethread = sess.target.target.options.singlethread;
182
183     // On the wasm target once the `atomics` feature is enabled that means that
184     // we're no longer single-threaded, or otherwise we don't want LLVM to
185     // lower atomic operations to single-threaded operations.
186     if singlethread &&
187         sess.target.target.llvm_target.contains("wasm32") &&
188         features.iter().any(|s| *s == "+atomics")
189     {
190         singlethread = false;
191     }
192
193     let triple = SmallCStr::new(&sess.target.target.llvm_target);
194     let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
195     let features = features.join(",");
196     let features = CString::new(features).unwrap();
197     let is_pie_binary = !find_features && is_pie_binary(sess);
198     let trap_unreachable = sess.target.target.options.trap_unreachable;
199     let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
200
201     let asm_comments = sess.asm_comments();
202
203     Arc::new(move || {
204         let tm = unsafe {
205             llvm::LLVMRustCreateTargetMachine(
206                 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
207                 code_model,
208                 reloc_model,
209                 opt_level,
210                 use_softfp,
211                 is_pie_binary,
212                 ffunction_sections,
213                 fdata_sections,
214                 trap_unreachable,
215                 singlethread,
216                 asm_comments,
217                 emit_stack_size_section,
218             )
219         };
220
221         tm.ok_or_else(|| {
222             format!("Could not create LLVM TargetMachine for triple: {}",
223                     triple.to_str().unwrap())
224         })
225     })
226 }
227
228 /// Module-specific configuration for `optimize_and_codegen`.
229 pub struct ModuleConfig {
230     /// Names of additional optimization passes to run.
231     passes: Vec<String>,
232     /// Some(level) to optimize at a certain level, or None to run
233     /// absolutely no optimizations (used for the metadata module).
234     pub opt_level: Option<llvm::CodeGenOptLevel>,
235
236     /// Some(level) to optimize binary size, or None to not affect program size.
237     opt_size: Option<llvm::CodeGenOptSize>,
238
239     pgo_gen: Option<String>,
240     pgo_use: String,
241
242     // Flags indicating which outputs to produce.
243     pub emit_pre_thin_lto_bc: bool,
244     emit_no_opt_bc: bool,
245     emit_bc: bool,
246     emit_bc_compressed: bool,
247     emit_lto_bc: bool,
248     emit_ir: bool,
249     emit_asm: bool,
250     emit_obj: bool,
251     // Miscellaneous flags.  These are mostly copied from command-line
252     // options.
253     pub verify_llvm_ir: bool,
254     no_prepopulate_passes: bool,
255     no_builtins: bool,
256     time_passes: bool,
257     vectorize_loop: bool,
258     vectorize_slp: bool,
259     merge_functions: bool,
260     inline_threshold: Option<usize>,
261     // Instead of creating an object file by doing LLVM codegen, just
262     // make the object file bitcode. Provides easy compatibility with
263     // emscripten's ecc compiler, when used as the linker.
264     obj_is_bitcode: bool,
265     no_integrated_as: bool,
266     embed_bitcode: bool,
267     embed_bitcode_marker: bool,
268 }
269
270 impl ModuleConfig {
271     fn new(passes: Vec<String>) -> ModuleConfig {
272         ModuleConfig {
273             passes,
274             opt_level: None,
275             opt_size: None,
276
277             pgo_gen: None,
278             pgo_use: String::new(),
279
280             emit_no_opt_bc: false,
281             emit_pre_thin_lto_bc: false,
282             emit_bc: false,
283             emit_bc_compressed: false,
284             emit_lto_bc: false,
285             emit_ir: false,
286             emit_asm: false,
287             emit_obj: false,
288             obj_is_bitcode: false,
289             embed_bitcode: false,
290             embed_bitcode_marker: false,
291             no_integrated_as: false,
292
293             verify_llvm_ir: false,
294             no_prepopulate_passes: false,
295             no_builtins: false,
296             time_passes: false,
297             vectorize_loop: false,
298             vectorize_slp: false,
299             merge_functions: false,
300             inline_threshold: None
301         }
302     }
303
304     fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
305         self.verify_llvm_ir = sess.verify_llvm_ir();
306         self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
307         self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
308         self.time_passes = sess.time_passes();
309         self.inline_threshold = sess.opts.cg.inline_threshold;
310         self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
311                               sess.opts.debugging_opts.cross_lang_lto.enabled();
312         let embed_bitcode = sess.target.target.options.embed_bitcode ||
313                             sess.opts.debugging_opts.embed_bitcode;
314         if embed_bitcode {
315             match sess.opts.optimize {
316                 config::OptLevel::No |
317                 config::OptLevel::Less => {
318                     self.embed_bitcode_marker = embed_bitcode;
319                 }
320                 _ => self.embed_bitcode = embed_bitcode,
321             }
322         }
323
324         // Copy what clang does by turning on loop vectorization at O2 and
325         // slp vectorization at O3. Otherwise configure other optimization aspects
326         // of this pass manager builder.
327         // Turn off vectorization for emscripten, as it's not very well supported.
328         self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
329                              (sess.opts.optimize == config::OptLevel::Default ||
330                               sess.opts.optimize == config::OptLevel::Aggressive) &&
331                              !sess.target.target.options.is_like_emscripten;
332
333         self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
334                             sess.opts.optimize == config::OptLevel::Aggressive &&
335                             !sess.target.target.options.is_like_emscripten;
336
337         self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
338                                sess.opts.optimize == config::OptLevel::Aggressive;
339     }
340
341     pub fn bitcode_needed(&self) -> bool {
342         self.emit_bc || self.obj_is_bitcode
343             || self.emit_bc_compressed || self.embed_bitcode
344     }
345 }
346
347 /// Assembler name and command used by codegen when no_integrated_as is enabled
348 struct AssemblerCommand {
349     name: PathBuf,
350     cmd: Command,
351 }
352
353 /// Additional resources used by optimize_and_codegen (not module specific)
354 #[derive(Clone)]
355 pub struct CodegenContext {
356     // Resources needed when running LTO
357     pub time_passes: bool,
358     pub lto: Lto,
359     pub no_landing_pads: bool,
360     pub save_temps: bool,
361     pub fewer_names: bool,
362     pub exported_symbols: Option<Arc<ExportedSymbols>>,
363     pub opts: Arc<config::Options>,
364     pub crate_types: Vec<config::CrateType>,
365     pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
366     output_filenames: Arc<OutputFilenames>,
367     regular_module_config: Arc<ModuleConfig>,
368     metadata_module_config: Arc<ModuleConfig>,
369     allocator_module_config: Arc<ModuleConfig>,
370     pub tm_factory: Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>,
371     pub msvc_imps_needed: bool,
372     pub target_pointer_width: String,
373     debuginfo: config::DebugInfo,
374
375     // Number of cgus excluding the allocator/metadata modules
376     pub total_cgus: usize,
377     // Handler to use for diagnostics produced during codegen.
378     pub diag_emitter: SharedEmitter,
379     // LLVM passes added by plugins.
380     pub plugin_passes: Vec<String>,
381     // LLVM optimizations for which we want to print remarks.
382     pub remark: Passes,
383     // Worker thread number
384     pub worker: usize,
385     // The incremental compilation session directory, or None if we are not
386     // compiling incrementally
387     pub incr_comp_session_dir: Option<PathBuf>,
388     // Used to update CGU re-use information during the thinlto phase.
389     pub cgu_reuse_tracker: CguReuseTracker,
390     // Channel back to the main control thread to send messages to
391     coordinator_send: Sender<Box<dyn Any + Send>>,
392     // A reference to the TimeGraph so we can register timings. None means that
393     // measuring is disabled.
394     time_graph: Option<TimeGraph>,
395     // The assembler command if no_integrated_as option is enabled, None otherwise
396     assembler_cmd: Option<Arc<AssemblerCommand>>,
397 }
398
399 impl CodegenContext {
400     pub fn create_diag_handler(&self) -> Handler {
401         Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
402     }
403
404     pub(crate) fn config(&self, kind: ModuleKind) -> &ModuleConfig {
405         match kind {
406             ModuleKind::Regular => &self.regular_module_config,
407             ModuleKind::Metadata => &self.metadata_module_config,
408             ModuleKind::Allocator => &self.allocator_module_config,
409         }
410     }
411
412     pub(crate) fn save_temp_bitcode(&self, module: &ModuleCodegen, name: &str) {
413         if !self.save_temps {
414             return
415         }
416         unsafe {
417             let ext = format!("{}.bc", name);
418             let cgu = Some(&module.name[..]);
419             let path = self.output_filenames.temp_path_ext(&ext, cgu);
420             let cstr = path2cstr(&path);
421             let llmod = module.module_llvm.llmod();
422             llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
423         }
424     }
425 }
426
427 pub struct DiagnosticHandlers<'a> {
428     data: *mut (&'a CodegenContext, &'a Handler),
429     llcx: &'a llvm::Context,
430 }
431
432 impl<'a> DiagnosticHandlers<'a> {
433     pub fn new(cgcx: &'a CodegenContext,
434                handler: &'a Handler,
435                llcx: &'a llvm::Context) -> Self {
436         let data = Box::into_raw(Box::new((cgcx, handler)));
437         unsafe {
438             llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
439             llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
440         }
441         DiagnosticHandlers { data, llcx }
442     }
443 }
444
445 impl<'a> Drop for DiagnosticHandlers<'a> {
446     fn drop(&mut self) {
447         use std::ptr::null_mut;
448         unsafe {
449             llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
450             llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
451             drop(Box::from_raw(self.data));
452         }
453     }
454 }
455
456 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
457                                                msg: &'b str,
458                                                cookie: c_uint) {
459     cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_string());
460 }
461
462 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
463                                         user: *const c_void,
464                                         cookie: c_uint) {
465     if user.is_null() {
466         return
467     }
468     let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
469
470     let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
471         .expect("non-UTF8 SMDiagnostic");
472
473     report_inline_asm(cgcx, &msg, cookie);
474 }
475
476 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
477     if user.is_null() {
478         return
479     }
480     let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
481
482     match llvm::diagnostic::Diagnostic::unpack(info) {
483         llvm::diagnostic::InlineAsm(inline) => {
484             report_inline_asm(cgcx,
485                               &llvm::twine_to_string(inline.message),
486                               inline.cookie);
487         }
488
489         llvm::diagnostic::Optimization(opt) => {
490             let enabled = match cgcx.remark {
491                 Passes::All => true,
492                 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
493             };
494
495             if enabled {
496                 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
497                                                 opt.kind.describe(),
498                                                 opt.pass_name,
499                                                 opt.filename,
500                                                 opt.line,
501                                                 opt.column,
502                                                 opt.message));
503             }
504         }
505         llvm::diagnostic::PGO(diagnostic_ref) |
506         llvm::diagnostic::Linker(diagnostic_ref) => {
507             let msg = llvm::build_string(|s| {
508                 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
509             }).expect("non-UTF8 diagnostic");
510             diag_handler.warn(&msg);
511         }
512         llvm::diagnostic::UnknownDiagnostic(..) => {},
513     }
514 }
515
516 // Unsafe due to LLVM calls.
517 unsafe fn optimize(cgcx: &CodegenContext,
518                    diag_handler: &Handler,
519                    module: &ModuleCodegen,
520                    config: &ModuleConfig,
521                    timeline: &mut Timeline)
522     -> Result<(), FatalError>
523 {
524     let llmod = module.module_llvm.llmod();
525     let llcx = &*module.module_llvm.llcx;
526     let tm = &*module.module_llvm.tm;
527     let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
528
529     let module_name = module.name.clone();
530     let module_name = Some(&module_name[..]);
531
532     if config.emit_no_opt_bc {
533         let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
534         let out = path2cstr(&out);
535         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
536     }
537
538     if config.opt_level.is_some() {
539         // Create the two optimizing pass managers. These mirror what clang
540         // does, and are by populated by LLVM's default PassManagerBuilder.
541         // Each manager has a different set of passes, but they also share
542         // some common passes.
543         let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
544         let mpm = llvm::LLVMCreatePassManager();
545
546         {
547             // If we're verifying or linting, add them to the function pass
548             // manager.
549             let addpass = |pass_name: &str| {
550                 let pass_name = SmallCStr::new(pass_name);
551                 let pass = match llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr()) {
552                     Some(pass) => pass,
553                     None => return false,
554                 };
555                 let pass_manager = match llvm::LLVMRustPassKind(pass) {
556                     llvm::PassKind::Function => &*fpm,
557                     llvm::PassKind::Module => &*mpm,
558                     llvm::PassKind::Other => {
559                         diag_handler.err("Encountered LLVM pass kind we can't handle");
560                         return true
561                     },
562                 };
563                 llvm::LLVMRustAddPass(pass_manager, pass);
564                 true
565             };
566
567             if config.verify_llvm_ir { assert!(addpass("verify")); }
568
569             // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
570             // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
571             // we'll get errors in LLVM.
572             let using_thin_buffers = config.bitcode_needed();
573             let mut have_name_anon_globals_pass = false;
574             if !config.no_prepopulate_passes {
575                 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
576                 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
577                 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
578                 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal ||
579                     (cgcx.lto != Lto::Fat && cgcx.opts.debugging_opts.cross_lang_lto.enabled());
580                 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
581                 if using_thin_buffers && !prepare_for_thin_lto {
582                     assert!(addpass("name-anon-globals"));
583                     have_name_anon_globals_pass = true;
584                 }
585                 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
586                     llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
587                     llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
588                 })
589             }
590
591             for pass in &config.passes {
592                 if !addpass(pass) {
593                     diag_handler.warn(&format!("unknown pass `{}`, ignoring",
594                                             pass));
595                 }
596                 if pass == "name-anon-globals" {
597                     have_name_anon_globals_pass = true;
598                 }
599             }
600
601             for pass in &cgcx.plugin_passes {
602                 if !addpass(pass) {
603                     diag_handler.err(&format!("a plugin asked for LLVM pass \
604                                             `{}` but LLVM does not \
605                                             recognize it", pass));
606                 }
607                 if pass == "name-anon-globals" {
608                     have_name_anon_globals_pass = true;
609                 }
610             }
611
612             if using_thin_buffers && !have_name_anon_globals_pass {
613                 // As described above, this will probably cause an error in LLVM
614                 if config.no_prepopulate_passes {
615                     diag_handler.err("The current compilation is going to use thin LTO buffers \
616                                      without running LLVM's NameAnonGlobals pass. \
617                                      This will likely cause errors in LLVM. Consider adding \
618                                      -C passes=name-anon-globals to the compiler command line.");
619                 } else {
620                     bug!("We are using thin LTO buffers without running the NameAnonGlobals pass. \
621                          This will likely cause errors in LLVM and should never happen.");
622                 }
623             }
624         }
625
626         diag_handler.abort_if_errors();
627
628         // Finally, run the actual optimization passes
629         time_ext(config.time_passes,
630                  None,
631                  &format!("llvm function passes [{}]", module_name.unwrap()),
632                  || {
633             llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
634         });
635         timeline.record("fpm");
636         time_ext(config.time_passes,
637                  None,
638                  &format!("llvm module passes [{}]", module_name.unwrap()),
639                  || {
640             llvm::LLVMRunPassManager(mpm, llmod)
641         });
642
643         // Deallocate managers that we're now done with
644         llvm::LLVMDisposePassManager(fpm);
645         llvm::LLVMDisposePassManager(mpm);
646     }
647     Ok(())
648 }
649
650 fn generate_lto_work(cgcx: &CodegenContext,
651                      modules: Vec<ModuleCodegen>,
652                      import_only_modules: Vec<(SerializedModule, WorkProduct)>)
653     -> Vec<(WorkItem, u64)>
654 {
655     let mut timeline = cgcx.time_graph.as_ref().map(|tg| {
656         tg.start(CODEGEN_WORKER_TIMELINE,
657                  CODEGEN_WORK_PACKAGE_KIND,
658                  "generate lto")
659     }).unwrap_or(Timeline::noop());
660     let (lto_modules, copy_jobs) = lto::run(cgcx, modules, import_only_modules, &mut timeline)
661         .unwrap_or_else(|e| e.raise());
662
663     let lto_modules = lto_modules.into_iter().map(|module| {
664         let cost = module.cost();
665         (WorkItem::LTO(module), cost)
666     });
667
668     let copy_jobs = copy_jobs.into_iter().map(|wp| {
669         (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
670             name: wp.cgu_name.clone(),
671             source: wp,
672         }), 0)
673     });
674
675     lto_modules.chain(copy_jobs).collect()
676 }
677
678 unsafe fn codegen(cgcx: &CodegenContext,
679                   diag_handler: &Handler,
680                   module: ModuleCodegen,
681                   config: &ModuleConfig,
682                   timeline: &mut Timeline)
683     -> Result<CompiledModule, FatalError>
684 {
685     timeline.record("codegen");
686     {
687         let llmod = module.module_llvm.llmod();
688         let llcx = &*module.module_llvm.llcx;
689         let tm = &*module.module_llvm.tm;
690         let module_name = module.name.clone();
691         let module_name = Some(&module_name[..]);
692         let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
693
694         if cgcx.msvc_imps_needed {
695             create_msvc_imps(cgcx, llcx, llmod);
696         }
697
698         // A codegen-specific pass manager is used to generate object
699         // files for an LLVM module.
700         //
701         // Apparently each of these pass managers is a one-shot kind of
702         // thing, so we create a new one for each type of output. The
703         // pass manager passed to the closure should be ensured to not
704         // escape the closure itself, and the manager should only be
705         // used once.
706         unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine,
707                                     llmod: &'ll llvm::Module,
708                                     no_builtins: bool,
709                                     f: F) -> R
710             where F: FnOnce(&'ll mut PassManager<'ll>) -> R,
711         {
712             let cpm = llvm::LLVMCreatePassManager();
713             llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
714             llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
715             f(cpm)
716         }
717
718         // If we don't have the integrated assembler, then we need to emit asm
719         // from LLVM and use `gcc` to create the object file.
720         let asm_to_obj = config.emit_obj && config.no_integrated_as;
721
722         // Change what we write and cleanup based on whether obj files are
723         // just llvm bitcode. In that case write bitcode, and possibly
724         // delete the bitcode if it wasn't requested. Don't generate the
725         // machine code, instead copy the .o file from the .bc
726         let write_bc = config.emit_bc || config.obj_is_bitcode;
727         let rm_bc = !config.emit_bc && config.obj_is_bitcode;
728         let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
729         let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
730
731         let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
732         let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
733
734
735         if write_bc || config.emit_bc_compressed || config.embed_bitcode {
736             let thin = ThinBuffer::new(llmod);
737             let data = thin.data();
738             timeline.record("make-bc");
739
740             if write_bc {
741                 if let Err(e) = fs::write(&bc_out, data) {
742                     diag_handler.err(&format!("failed to write bytecode: {}", e));
743                 }
744                 timeline.record("write-bc");
745             }
746
747             if config.embed_bitcode {
748                 embed_bitcode(cgcx, llcx, llmod, Some(data));
749                 timeline.record("embed-bc");
750             }
751
752             if config.emit_bc_compressed {
753                 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
754                 let data = bytecode::encode(&module.name, data);
755                 if let Err(e) = fs::write(&dst, data) {
756                     diag_handler.err(&format!("failed to write bytecode: {}", e));
757                 }
758                 timeline.record("compress-bc");
759             }
760         } else if config.embed_bitcode_marker {
761             embed_bitcode(cgcx, llcx, llmod, None);
762         }
763
764         time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
765             || -> Result<(), FatalError> {
766             if config.emit_ir {
767                 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
768                 let out = path2cstr(&out);
769
770                 extern "C" fn demangle_callback(input_ptr: *const c_char,
771                                                 input_len: size_t,
772                                                 output_ptr: *mut c_char,
773                                                 output_len: size_t) -> size_t {
774                     let input = unsafe {
775                         slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
776                     };
777
778                     let input = match str::from_utf8(input) {
779                         Ok(s) => s,
780                         Err(_) => return 0,
781                     };
782
783                     let output = unsafe {
784                         slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
785                     };
786                     let mut cursor = io::Cursor::new(output);
787
788                     let demangled = match rustc_demangle::try_demangle(input) {
789                         Ok(d) => d,
790                         Err(_) => return 0,
791                     };
792
793                     if let Err(_) = write!(cursor, "{:#}", demangled) {
794                         // Possible only if provided buffer is not big enough
795                         return 0;
796                     }
797
798                     cursor.position() as size_t
799                 }
800
801                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
802                     llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
803                     llvm::LLVMDisposePassManager(cpm);
804                 });
805                 timeline.record("ir");
806             }
807
808             if config.emit_asm || asm_to_obj {
809                 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
810
811                 // We can't use the same module for asm and binary output, because that triggers
812                 // various errors like invalid IR or broken binaries, so we might have to clone the
813                 // module to produce the asm output
814                 let llmod = if config.emit_obj {
815                     llvm::LLVMCloneModule(llmod)
816                 } else {
817                     llmod
818                 };
819                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
820                     write_output_file(diag_handler, tm, cpm, llmod, &path,
821                                     llvm::FileType::AssemblyFile)
822                 })?;
823                 timeline.record("asm");
824             }
825
826             if write_obj {
827                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
828                     write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
829                                     llvm::FileType::ObjectFile)
830                 })?;
831                 timeline.record("obj");
832             } else if asm_to_obj {
833                 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
834                 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
835                 timeline.record("asm_to_obj");
836
837                 if !config.emit_asm && !cgcx.save_temps {
838                     drop(fs::remove_file(&assembly));
839                 }
840             }
841
842             Ok(())
843         })?;
844
845         if copy_bc_to_obj {
846             debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
847             if let Err(e) = link_or_copy(&bc_out, &obj_out) {
848                 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
849             }
850         }
851
852         if rm_bc {
853             debug!("removing_bitcode {:?}", bc_out);
854             if let Err(e) = fs::remove_file(&bc_out) {
855                 diag_handler.err(&format!("failed to remove bitcode: {}", e));
856             }
857         }
858
859         drop(handlers);
860     }
861     Ok(module.into_compiled_module(config.emit_obj,
862                                    config.emit_bc,
863                                    config.emit_bc_compressed,
864                                    &cgcx.output_filenames))
865 }
866
867 /// Embed the bitcode of an LLVM module in the LLVM module itself.
868 ///
869 /// This is done primarily for iOS where it appears to be standard to compile C
870 /// code at least with `-fembed-bitcode` which creates two sections in the
871 /// executable:
872 ///
873 /// * __LLVM,__bitcode
874 /// * __LLVM,__cmdline
875 ///
876 /// It appears *both* of these sections are necessary to get the linker to
877 /// recognize what's going on. For us though we just always throw in an empty
878 /// cmdline section.
879 ///
880 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
881 /// embed an empty section.
882 ///
883 /// Basically all of this is us attempting to follow in the footsteps of clang
884 /// on iOS. See #35968 for lots more info.
885 unsafe fn embed_bitcode(cgcx: &CodegenContext,
886                         llcx: &llvm::Context,
887                         llmod: &llvm::Module,
888                         bitcode: Option<&[u8]>) {
889     let llconst = C_bytes_in_context(llcx, bitcode.unwrap_or(&[]));
890     let llglobal = llvm::LLVMAddGlobal(
891         llmod,
892         val_ty(llconst),
893         "rustc.embedded.module\0".as_ptr() as *const _,
894     );
895     llvm::LLVMSetInitializer(llglobal, llconst);
896
897     let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
898                    cgcx.opts.target_triple.triple().contains("-darwin");
899
900     let section = if is_apple {
901         "__LLVM,__bitcode\0"
902     } else {
903         ".llvmbc\0"
904     };
905     llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
906     llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
907     llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
908
909     let llconst = C_bytes_in_context(llcx, &[]);
910     let llglobal = llvm::LLVMAddGlobal(
911         llmod,
912         val_ty(llconst),
913         "rustc.embedded.cmdline\0".as_ptr() as *const _,
914     );
915     llvm::LLVMSetInitializer(llglobal, llconst);
916     let section = if  is_apple {
917         "__LLVM,__cmdline\0"
918     } else {
919         ".llvmcmd\0"
920     };
921     llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
922     llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
923 }
924
925 pub(crate) struct CompiledModules {
926     pub modules: Vec<CompiledModule>,
927     pub metadata_module: CompiledModule,
928     pub allocator_module: Option<CompiledModule>,
929 }
930
931 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
932     sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
933     sess.opts.output_types.contains_key(&OutputType::Exe)
934 }
935
936 fn need_pre_thin_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
937     if sess.opts.incremental.is_none() {
938         return false
939     }
940
941     match sess.lto() {
942         Lto::Fat |
943         Lto::No => false,
944         Lto::Thin |
945         Lto::ThinLocal => true,
946     }
947 }
948
949 pub fn start_async_codegen(tcx: TyCtxt,
950                                time_graph: Option<TimeGraph>,
951                                metadata: EncodedMetadata,
952                                coordinator_receive: Receiver<Box<dyn Any + Send>>,
953                                total_cgus: usize)
954                                -> OngoingCodegen {
955     let sess = tcx.sess;
956     let crate_name = tcx.crate_name(LOCAL_CRATE);
957     let crate_hash = tcx.crate_hash(LOCAL_CRATE);
958     let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
959     let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
960                                                        "windows_subsystem");
961     let windows_subsystem = subsystem.map(|subsystem| {
962         if subsystem != "windows" && subsystem != "console" {
963             tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
964                                      `windows` and `console` are allowed",
965                                     subsystem));
966         }
967         subsystem.to_string()
968     });
969
970     let linker_info = LinkerInfo::new(tcx);
971     let crate_info = CrateInfo::new(tcx);
972
973     // Figure out what we actually need to build.
974     let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
975     let mut metadata_config = ModuleConfig::new(vec![]);
976     let mut allocator_config = ModuleConfig::new(vec![]);
977
978     if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
979         match *sanitizer {
980             Sanitizer::Address => {
981                 modules_config.passes.push("asan".to_owned());
982                 modules_config.passes.push("asan-module".to_owned());
983             }
984             Sanitizer::Memory => {
985                 modules_config.passes.push("msan".to_owned())
986             }
987             Sanitizer::Thread => {
988                 modules_config.passes.push("tsan".to_owned())
989             }
990             _ => {}
991         }
992     }
993
994     if sess.opts.debugging_opts.profile {
995         modules_config.passes.push("insert-gcov-profiling".to_owned())
996     }
997
998     modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
999     modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
1000
1001     modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
1002     modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
1003
1004     // Save all versions of the bytecode if we're saving our temporaries.
1005     if sess.opts.cg.save_temps {
1006         modules_config.emit_no_opt_bc = true;
1007         modules_config.emit_pre_thin_lto_bc = true;
1008         modules_config.emit_bc = true;
1009         modules_config.emit_lto_bc = true;
1010         metadata_config.emit_bc = true;
1011         allocator_config.emit_bc = true;
1012     }
1013
1014     // Emit compressed bitcode files for the crate if we're emitting an rlib.
1015     // Whenever an rlib is created, the bitcode is inserted into the archive in
1016     // order to allow LTO against it.
1017     if need_crate_bitcode_for_rlib(sess) {
1018         modules_config.emit_bc_compressed = true;
1019         allocator_config.emit_bc_compressed = true;
1020     }
1021
1022     modules_config.emit_pre_thin_lto_bc =
1023         need_pre_thin_lto_bitcode_for_incr_comp(sess);
1024
1025     modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
1026         tcx.sess.target.target.options.no_integrated_as;
1027
1028     for output_type in sess.opts.output_types.keys() {
1029         match *output_type {
1030             OutputType::Bitcode => { modules_config.emit_bc = true; }
1031             OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
1032             OutputType::Assembly => {
1033                 modules_config.emit_asm = true;
1034                 // If we're not using the LLVM assembler, this function
1035                 // could be invoked specially with output_type_assembly, so
1036                 // in this case we still want the metadata object file.
1037                 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
1038                     metadata_config.emit_obj = true;
1039                     allocator_config.emit_obj = true;
1040                 }
1041             }
1042             OutputType::Object => { modules_config.emit_obj = true; }
1043             OutputType::Metadata => { metadata_config.emit_obj = true; }
1044             OutputType::Exe => {
1045                 modules_config.emit_obj = true;
1046                 metadata_config.emit_obj = true;
1047                 allocator_config.emit_obj = true;
1048             },
1049             OutputType::Mir => {}
1050             OutputType::DepInfo => {}
1051         }
1052     }
1053
1054     modules_config.set_flags(sess, no_builtins);
1055     metadata_config.set_flags(sess, no_builtins);
1056     allocator_config.set_flags(sess, no_builtins);
1057
1058     // Exclude metadata and allocator modules from time_passes output, since
1059     // they throw off the "LLVM passes" measurement.
1060     metadata_config.time_passes = false;
1061     allocator_config.time_passes = false;
1062
1063     let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
1064     let (codegen_worker_send, codegen_worker_receive) = channel();
1065
1066     let coordinator_thread = start_executing_work(tcx,
1067                                                   &crate_info,
1068                                                   shared_emitter,
1069                                                   codegen_worker_send,
1070                                                   coordinator_receive,
1071                                                   total_cgus,
1072                                                   sess.jobserver.clone(),
1073                                                   time_graph.clone(),
1074                                                   Arc::new(modules_config),
1075                                                   Arc::new(metadata_config),
1076                                                   Arc::new(allocator_config));
1077
1078     OngoingCodegen {
1079         crate_name,
1080         crate_hash,
1081         metadata,
1082         windows_subsystem,
1083         linker_info,
1084         crate_info,
1085
1086         time_graph,
1087         coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
1088         codegen_worker_receive,
1089         shared_emitter_main,
1090         future: coordinator_thread,
1091         output_filenames: tcx.output_filenames(LOCAL_CRATE),
1092     }
1093 }
1094
1095 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
1096     sess: &Session,
1097     compiled_modules: &CompiledModules,
1098 ) -> FxHashMap<WorkProductId, WorkProduct> {
1099     let mut work_products = FxHashMap::default();
1100
1101     if sess.opts.incremental.is_none() {
1102         return work_products;
1103     }
1104
1105     for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
1106         let mut files = vec![];
1107
1108         if let Some(ref path) = module.object {
1109             files.push((WorkProductFileKind::Object, path.clone()));
1110         }
1111         if let Some(ref path) = module.bytecode {
1112             files.push((WorkProductFileKind::Bytecode, path.clone()));
1113         }
1114         if let Some(ref path) = module.bytecode_compressed {
1115             files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
1116         }
1117
1118         if let Some((id, product)) =
1119                 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
1120             work_products.insert(id, product);
1121         }
1122     }
1123
1124     work_products
1125 }
1126
1127 fn produce_final_output_artifacts(sess: &Session,
1128                                   compiled_modules: &CompiledModules,
1129                                   crate_output: &OutputFilenames) {
1130     let mut user_wants_bitcode = false;
1131     let mut user_wants_objects = false;
1132
1133     // Produce final compile outputs.
1134     let copy_gracefully = |from: &Path, to: &Path| {
1135         if let Err(e) = fs::copy(from, to) {
1136             sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
1137         }
1138     };
1139
1140     let copy_if_one_unit = |output_type: OutputType,
1141                             keep_numbered: bool| {
1142         if compiled_modules.modules.len() == 1 {
1143             // 1) Only one codegen unit.  In this case it's no difficulty
1144             //    to copy `foo.0.x` to `foo.x`.
1145             let module_name = Some(&compiled_modules.modules[0].name[..]);
1146             let path = crate_output.temp_path(output_type, module_name);
1147             copy_gracefully(&path,
1148                             &crate_output.path(output_type));
1149             if !sess.opts.cg.save_temps && !keep_numbered {
1150                 // The user just wants `foo.x`, not `foo.#module-name#.x`.
1151                 remove(sess, &path);
1152             }
1153         } else {
1154             let ext = crate_output.temp_path(output_type, None)
1155                                   .extension()
1156                                   .unwrap()
1157                                   .to_str()
1158                                   .unwrap()
1159                                   .to_owned();
1160
1161             if crate_output.outputs.contains_key(&output_type) {
1162                 // 2) Multiple codegen units, with `--emit foo=some_name`.  We have
1163                 //    no good solution for this case, so warn the user.
1164                 sess.warn(&format!("ignoring emit path because multiple .{} files \
1165                                     were produced", ext));
1166             } else if crate_output.single_output_file.is_some() {
1167                 // 3) Multiple codegen units, with `-o some_name`.  We have
1168                 //    no good solution for this case, so warn the user.
1169                 sess.warn(&format!("ignoring -o because multiple .{} files \
1170                                     were produced", ext));
1171             } else {
1172                 // 4) Multiple codegen units, but no explicit name.  We
1173                 //    just leave the `foo.0.x` files in place.
1174                 // (We don't have to do any work in this case.)
1175             }
1176         }
1177     };
1178
1179     // Flag to indicate whether the user explicitly requested bitcode.
1180     // Otherwise, we produced it only as a temporary output, and will need
1181     // to get rid of it.
1182     for output_type in crate_output.outputs.keys() {
1183         match *output_type {
1184             OutputType::Bitcode => {
1185                 user_wants_bitcode = true;
1186                 // Copy to .bc, but always keep the .0.bc.  There is a later
1187                 // check to figure out if we should delete .0.bc files, or keep
1188                 // them for making an rlib.
1189                 copy_if_one_unit(OutputType::Bitcode, true);
1190             }
1191             OutputType::LlvmAssembly => {
1192                 copy_if_one_unit(OutputType::LlvmAssembly, false);
1193             }
1194             OutputType::Assembly => {
1195                 copy_if_one_unit(OutputType::Assembly, false);
1196             }
1197             OutputType::Object => {
1198                 user_wants_objects = true;
1199                 copy_if_one_unit(OutputType::Object, true);
1200             }
1201             OutputType::Mir |
1202             OutputType::Metadata |
1203             OutputType::Exe |
1204             OutputType::DepInfo => {}
1205         }
1206     }
1207
1208     // Clean up unwanted temporary files.
1209
1210     // We create the following files by default:
1211     //  - #crate#.#module-name#.bc
1212     //  - #crate#.#module-name#.o
1213     //  - #crate#.crate.metadata.bc
1214     //  - #crate#.crate.metadata.o
1215     //  - #crate#.o (linked from crate.##.o)
1216     //  - #crate#.bc (copied from crate.##.bc)
1217     // We may create additional files if requested by the user (through
1218     // `-C save-temps` or `--emit=` flags).
1219
1220     if !sess.opts.cg.save_temps {
1221         // Remove the temporary .#module-name#.o objects.  If the user didn't
1222         // explicitly request bitcode (with --emit=bc), and the bitcode is not
1223         // needed for building an rlib, then we must remove .#module-name#.bc as
1224         // well.
1225
1226         // Specific rules for keeping .#module-name#.bc:
1227         //  - If the user requested bitcode (`user_wants_bitcode`), and
1228         //    codegen_units > 1, then keep it.
1229         //  - If the user requested bitcode but codegen_units == 1, then we
1230         //    can toss .#module-name#.bc because we copied it to .bc earlier.
1231         //  - If we're not building an rlib and the user didn't request
1232         //    bitcode, then delete .#module-name#.bc.
1233         // If you change how this works, also update back::link::link_rlib,
1234         // where .#module-name#.bc files are (maybe) deleted after making an
1235         // rlib.
1236         let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
1237
1238         let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
1239
1240         let keep_numbered_objects = needs_crate_object ||
1241                 (user_wants_objects && sess.codegen_units() > 1);
1242
1243         for module in compiled_modules.modules.iter() {
1244             if let Some(ref path) = module.object {
1245                 if !keep_numbered_objects {
1246                     remove(sess, path);
1247                 }
1248             }
1249
1250             if let Some(ref path) = module.bytecode {
1251                 if !keep_numbered_bitcode {
1252                     remove(sess, path);
1253                 }
1254             }
1255         }
1256
1257         if !user_wants_bitcode {
1258             if let Some(ref path) = compiled_modules.metadata_module.bytecode {
1259                 remove(sess, &path);
1260             }
1261
1262             if let Some(ref allocator_module) = compiled_modules.allocator_module {
1263                 if let Some(ref path) = allocator_module.bytecode {
1264                     remove(sess, path);
1265                 }
1266             }
1267         }
1268     }
1269
1270     // We leave the following files around by default:
1271     //  - #crate#.o
1272     //  - #crate#.crate.metadata.o
1273     //  - #crate#.bc
1274     // These are used in linking steps and will be cleaned up afterward.
1275 }
1276
1277 pub(crate) fn dump_incremental_data(_codegen_results: &CodegenResults) {
1278     // FIXME(mw): This does not work at the moment because the situation has
1279     //            become more complicated due to incremental LTO. Now a CGU
1280     //            can have more than two caching states.
1281     // println!("[incremental] Re-using {} out of {} modules",
1282     //           codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
1283     //           codegen_results.modules.len());
1284 }
1285
1286 enum WorkItem {
1287     /// Optimize a newly codegened, totally unoptimized module.
1288     Optimize(ModuleCodegen),
1289     /// Copy the post-LTO artifacts from the incremental cache to the output
1290     /// directory.
1291     CopyPostLtoArtifacts(CachedModuleCodegen),
1292     /// Perform (Thin)LTO on the given module.
1293     LTO(lto::LtoModuleCodegen),
1294 }
1295
1296 impl WorkItem {
1297     fn module_kind(&self) -> ModuleKind {
1298         match *self {
1299             WorkItem::Optimize(ref m) => m.kind,
1300             WorkItem::CopyPostLtoArtifacts(_) |
1301             WorkItem::LTO(_) => ModuleKind::Regular,
1302         }
1303     }
1304
1305     fn name(&self) -> String {
1306         match *self {
1307             WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
1308             WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
1309             WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
1310         }
1311     }
1312 }
1313
1314 enum WorkItemResult {
1315     Compiled(CompiledModule),
1316     NeedsLTO(ModuleCodegen),
1317 }
1318
1319 fn execute_work_item(cgcx: &CodegenContext,
1320                      work_item: WorkItem,
1321                      timeline: &mut Timeline)
1322     -> Result<WorkItemResult, FatalError>
1323 {
1324     let module_config = cgcx.config(work_item.module_kind());
1325
1326     match work_item {
1327         WorkItem::Optimize(module) => {
1328             execute_optimize_work_item(cgcx, module, module_config, timeline)
1329         }
1330         WorkItem::CopyPostLtoArtifacts(module) => {
1331             execute_copy_from_cache_work_item(cgcx, module, module_config, timeline)
1332         }
1333         WorkItem::LTO(module) => {
1334             execute_lto_work_item(cgcx, module, module_config, timeline)
1335         }
1336     }
1337 }
1338
1339 fn execute_optimize_work_item(cgcx: &CodegenContext,
1340                               module: ModuleCodegen,
1341                               module_config: &ModuleConfig,
1342                               timeline: &mut Timeline)
1343     -> Result<WorkItemResult, FatalError>
1344 {
1345     let diag_handler = cgcx.create_diag_handler();
1346
1347     unsafe {
1348         optimize(cgcx, &diag_handler, &module, module_config, timeline)?;
1349     }
1350
1351     let linker_does_lto = cgcx.opts.debugging_opts.cross_lang_lto.enabled();
1352
1353     // After we've done the initial round of optimizations we need to
1354     // decide whether to synchronously codegen this module or ship it
1355     // back to the coordinator thread for further LTO processing (which
1356     // has to wait for all the initial modules to be optimized).
1357     //
1358     // Here we dispatch based on the `cgcx.lto` and kind of module we're
1359     // codegenning...
1360     let needs_lto = match cgcx.lto {
1361         Lto::No => false,
1362
1363         // If the linker does LTO, we don't have to do it. Note that we
1364         // keep doing full LTO, if it is requested, as not to break the
1365         // assumption that the output will be a single module.
1366         Lto::Thin | Lto::ThinLocal if linker_does_lto => false,
1367
1368         // Here we've got a full crate graph LTO requested. We ignore
1369         // this, however, if the crate type is only an rlib as there's
1370         // no full crate graph to process, that'll happen later.
1371         //
1372         // This use case currently comes up primarily for targets that
1373         // require LTO so the request for LTO is always unconditionally
1374         // passed down to the backend, but we don't actually want to do
1375         // anything about it yet until we've got a final product.
1376         Lto::Fat | Lto::Thin => {
1377             cgcx.crate_types.len() != 1 ||
1378                 cgcx.crate_types[0] != config::CrateType::Rlib
1379         }
1380
1381         // When we're automatically doing ThinLTO for multi-codegen-unit
1382         // builds we don't actually want to LTO the allocator modules if
1383         // it shows up. This is due to various linker shenanigans that
1384         // we'll encounter later.
1385         Lto::ThinLocal => {
1386             module.kind != ModuleKind::Allocator
1387         }
1388     };
1389
1390     // Metadata modules never participate in LTO regardless of the lto
1391     // settings.
1392     let needs_lto = needs_lto && module.kind != ModuleKind::Metadata;
1393
1394     if needs_lto {
1395         Ok(WorkItemResult::NeedsLTO(module))
1396     } else {
1397         let module = unsafe {
1398             codegen(cgcx, &diag_handler, module, module_config, timeline)?
1399         };
1400         Ok(WorkItemResult::Compiled(module))
1401     }
1402 }
1403
1404 fn execute_copy_from_cache_work_item(cgcx: &CodegenContext,
1405                                      module: CachedModuleCodegen,
1406                                      module_config: &ModuleConfig,
1407                                      _: &mut Timeline)
1408     -> Result<WorkItemResult, FatalError>
1409 {
1410     let incr_comp_session_dir = cgcx.incr_comp_session_dir
1411                                     .as_ref()
1412                                     .unwrap();
1413     let mut object = None;
1414     let mut bytecode = None;
1415     let mut bytecode_compressed = None;
1416     for (kind, saved_file) in &module.source.saved_files {
1417         let obj_out = match kind {
1418             WorkProductFileKind::Object => {
1419                 let path = cgcx.output_filenames.temp_path(OutputType::Object,
1420                                                            Some(&module.name));
1421                 object = Some(path.clone());
1422                 path
1423             }
1424             WorkProductFileKind::Bytecode => {
1425                 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1426                                                            Some(&module.name));
1427                 bytecode = Some(path.clone());
1428                 path
1429             }
1430             WorkProductFileKind::BytecodeCompressed => {
1431                 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1432                                                            Some(&module.name))
1433                     .with_extension(RLIB_BYTECODE_EXTENSION);
1434                 bytecode_compressed = Some(path.clone());
1435                 path
1436             }
1437         };
1438         let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1439                                            &saved_file);
1440         debug!("copying pre-existing module `{}` from {:?} to {}",
1441                module.name,
1442                source_file,
1443                obj_out.display());
1444         match link_or_copy(&source_file, &obj_out) {
1445             Ok(_) => { }
1446             Err(err) => {
1447                 let diag_handler = cgcx.create_diag_handler();
1448                 diag_handler.err(&format!("unable to copy {} to {}: {}",
1449                                           source_file.display(),
1450                                           obj_out.display(),
1451                                           err));
1452             }
1453         }
1454     }
1455
1456     assert_eq!(object.is_some(), module_config.emit_obj);
1457     assert_eq!(bytecode.is_some(), module_config.emit_bc);
1458     assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
1459
1460     Ok(WorkItemResult::Compiled(CompiledModule {
1461         name: module.name,
1462         kind: ModuleKind::Regular,
1463         object,
1464         bytecode,
1465         bytecode_compressed,
1466     }))
1467 }
1468
1469 fn execute_lto_work_item(cgcx: &CodegenContext,
1470                          mut module: lto::LtoModuleCodegen,
1471                          module_config: &ModuleConfig,
1472                          timeline: &mut Timeline)
1473     -> Result<WorkItemResult, FatalError>
1474 {
1475     let diag_handler = cgcx.create_diag_handler();
1476
1477     unsafe {
1478         let module = module.optimize(cgcx, timeline)?;
1479         let module = codegen(cgcx, &diag_handler, module, module_config, timeline)?;
1480         Ok(WorkItemResult::Compiled(module))
1481     }
1482 }
1483
1484 enum Message {
1485     Token(io::Result<Acquired>),
1486     NeedsLTO {
1487         result: ModuleCodegen,
1488         worker_id: usize,
1489     },
1490     Done {
1491         result: Result<CompiledModule, ()>,
1492         worker_id: usize,
1493     },
1494     CodegenDone {
1495         llvm_work_item: WorkItem,
1496         cost: u64,
1497     },
1498     AddImportOnlyModule {
1499         module_data: SerializedModule,
1500         work_product: WorkProduct,
1501     },
1502     CodegenComplete,
1503     CodegenItem,
1504     CodegenAborted,
1505 }
1506
1507 struct Diagnostic {
1508     msg: String,
1509     code: Option<DiagnosticId>,
1510     lvl: Level,
1511 }
1512
1513 #[derive(PartialEq, Clone, Copy, Debug)]
1514 enum MainThreadWorkerState {
1515     Idle,
1516     Codegenning,
1517     LLVMing,
1518 }
1519
1520 fn start_executing_work(tcx: TyCtxt,
1521                         crate_info: &CrateInfo,
1522                         shared_emitter: SharedEmitter,
1523                         codegen_worker_send: Sender<Message>,
1524                         coordinator_receive: Receiver<Box<dyn Any + Send>>,
1525                         total_cgus: usize,
1526                         jobserver: Client,
1527                         time_graph: Option<TimeGraph>,
1528                         modules_config: Arc<ModuleConfig>,
1529                         metadata_config: Arc<ModuleConfig>,
1530                         allocator_config: Arc<ModuleConfig>)
1531                         -> thread::JoinHandle<Result<CompiledModules, ()>> {
1532     let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1533     let sess = tcx.sess;
1534
1535     // Compute the set of symbols we need to retain when doing LTO (if we need to)
1536     let exported_symbols = {
1537         let mut exported_symbols = FxHashMap::default();
1538
1539         let copy_symbols = |cnum| {
1540             let symbols = tcx.exported_symbols(cnum)
1541                              .iter()
1542                              .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1543                              .collect();
1544             Arc::new(symbols)
1545         };
1546
1547         match sess.lto() {
1548             Lto::No => None,
1549             Lto::ThinLocal => {
1550                 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1551                 Some(Arc::new(exported_symbols))
1552             }
1553             Lto::Fat | Lto::Thin => {
1554                 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1555                 for &cnum in tcx.crates().iter() {
1556                     exported_symbols.insert(cnum, copy_symbols(cnum));
1557                 }
1558                 Some(Arc::new(exported_symbols))
1559             }
1560         }
1561     };
1562
1563     // First up, convert our jobserver into a helper thread so we can use normal
1564     // mpsc channels to manage our messages and such.
1565     // After we've requested tokens then we'll, when we can,
1566     // get tokens on `coordinator_receive` which will
1567     // get managed in the main loop below.
1568     let coordinator_send2 = coordinator_send.clone();
1569     let helper = jobserver.into_helper_thread(move |token| {
1570         drop(coordinator_send2.send(Box::new(Message::Token(token))));
1571     }).expect("failed to spawn helper thread");
1572
1573     let mut each_linked_rlib_for_lto = Vec::new();
1574     drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1575         if link::ignored_for_lto(sess, crate_info, cnum) {
1576             return
1577         }
1578         each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1579     }));
1580
1581     let assembler_cmd = if modules_config.no_integrated_as {
1582         // HACK: currently we use linker (gcc) as our assembler
1583         let (linker, flavor) = link::linker_and_flavor(sess);
1584
1585         let (name, mut cmd) = get_linker(sess, &linker, flavor);
1586         cmd.args(&sess.target.target.options.asm_args);
1587         Some(Arc::new(AssemblerCommand {
1588             name,
1589             cmd,
1590         }))
1591     } else {
1592         None
1593     };
1594
1595     let cgcx = CodegenContext {
1596         crate_types: sess.crate_types.borrow().clone(),
1597         each_linked_rlib_for_lto,
1598         lto: sess.lto(),
1599         no_landing_pads: sess.no_landing_pads(),
1600         fewer_names: sess.fewer_names(),
1601         save_temps: sess.opts.cg.save_temps,
1602         opts: Arc::new(sess.opts.clone()),
1603         time_passes: sess.time_passes(),
1604         exported_symbols,
1605         plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1606         remark: sess.opts.cg.remark.clone(),
1607         worker: 0,
1608         incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1609         cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1610         coordinator_send,
1611         diag_emitter: shared_emitter.clone(),
1612         time_graph,
1613         output_filenames: tcx.output_filenames(LOCAL_CRATE),
1614         regular_module_config: modules_config,
1615         metadata_module_config: metadata_config,
1616         allocator_module_config: allocator_config,
1617         tm_factory: target_machine_factory(tcx.sess, false),
1618         total_cgus,
1619         msvc_imps_needed: msvc_imps_needed(tcx),
1620         target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1621         debuginfo: tcx.sess.opts.debuginfo,
1622         assembler_cmd,
1623     };
1624
1625     // This is the "main loop" of parallel work happening for parallel codegen.
1626     // It's here that we manage parallelism, schedule work, and work with
1627     // messages coming from clients.
1628     //
1629     // There are a few environmental pre-conditions that shape how the system
1630     // is set up:
1631     //
1632     // - Error reporting only can happen on the main thread because that's the
1633     //   only place where we have access to the compiler `Session`.
1634     // - LLVM work can be done on any thread.
1635     // - Codegen can only happen on the main thread.
1636     // - Each thread doing substantial work most be in possession of a `Token`
1637     //   from the `Jobserver`.
1638     // - The compiler process always holds one `Token`. Any additional `Tokens`
1639     //   have to be requested from the `Jobserver`.
1640     //
1641     // Error Reporting
1642     // ===============
1643     // The error reporting restriction is handled separately from the rest: We
1644     // set up a `SharedEmitter` the holds an open channel to the main thread.
1645     // When an error occurs on any thread, the shared emitter will send the
1646     // error message to the receiver main thread (`SharedEmitterMain`). The
1647     // main thread will periodically query this error message queue and emit
1648     // any error messages it has received. It might even abort compilation if
1649     // has received a fatal error. In this case we rely on all other threads
1650     // being torn down automatically with the main thread.
1651     // Since the main thread will often be busy doing codegen work, error
1652     // reporting will be somewhat delayed, since the message queue can only be
1653     // checked in between to work packages.
1654     //
1655     // Work Processing Infrastructure
1656     // ==============================
1657     // The work processing infrastructure knows three major actors:
1658     //
1659     // - the coordinator thread,
1660     // - the main thread, and
1661     // - LLVM worker threads
1662     //
1663     // The coordinator thread is running a message loop. It instructs the main
1664     // thread about what work to do when, and it will spawn off LLVM worker
1665     // threads as open LLVM WorkItems become available.
1666     //
1667     // The job of the main thread is to codegen CGUs into LLVM work package
1668     // (since the main thread is the only thread that can do this). The main
1669     // thread will block until it receives a message from the coordinator, upon
1670     // which it will codegen one CGU, send it to the coordinator and block
1671     // again. This way the coordinator can control what the main thread is
1672     // doing.
1673     //
1674     // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1675     // available, it will spawn off a new LLVM worker thread and let it process
1676     // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1677     // it will just shut down, which also frees all resources associated with
1678     // the given LLVM module, and sends a message to the coordinator that the
1679     // has been completed.
1680     //
1681     // Work Scheduling
1682     // ===============
1683     // The scheduler's goal is to minimize the time it takes to complete all
1684     // work there is, however, we also want to keep memory consumption low
1685     // if possible. These two goals are at odds with each other: If memory
1686     // consumption were not an issue, we could just let the main thread produce
1687     // LLVM WorkItems at full speed, assuring maximal utilization of
1688     // Tokens/LLVM worker threads. However, since codegen usual is faster
1689     // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1690     // WorkItem potentially holds on to a substantial amount of memory.
1691     //
1692     // So the actual goal is to always produce just enough LLVM WorkItems as
1693     // not to starve our LLVM worker threads. That means, once we have enough
1694     // WorkItems in our queue, we can block the main thread, so it does not
1695     // produce more until we need them.
1696     //
1697     // Doing LLVM Work on the Main Thread
1698     // ----------------------------------
1699     // Since the main thread owns the compiler processes implicit `Token`, it is
1700     // wasteful to keep it blocked without doing any work. Therefore, what we do
1701     // in this case is: We spawn off an additional LLVM worker thread that helps
1702     // reduce the queue. The work it is doing corresponds to the implicit
1703     // `Token`. The coordinator will mark the main thread as being busy with
1704     // LLVM work. (The actual work happens on another OS thread but we just care
1705     // about `Tokens`, not actual threads).
1706     //
1707     // When any LLVM worker thread finishes while the main thread is marked as
1708     // "busy with LLVM work", we can do a little switcheroo: We give the Token
1709     // of the just finished thread to the LLVM worker thread that is working on
1710     // behalf of the main thread's implicit Token, thus freeing up the main
1711     // thread again. The coordinator can then again decide what the main thread
1712     // should do. This allows the coordinator to make decisions at more points
1713     // in time.
1714     //
1715     // Striking a Balance between Throughput and Memory Consumption
1716     // ------------------------------------------------------------
1717     // Since our two goals, (1) use as many Tokens as possible and (2) keep
1718     // memory consumption as low as possible, are in conflict with each other,
1719     // we have to find a trade off between them. Right now, the goal is to keep
1720     // all workers busy, which means that no worker should find the queue empty
1721     // when it is ready to start.
1722     // How do we do achieve this? Good question :) We actually never know how
1723     // many `Tokens` are potentially available so it's hard to say how much to
1724     // fill up the queue before switching the main thread to LLVM work. Also we
1725     // currently don't have a means to estimate how long a running LLVM worker
1726     // will still be busy with it's current WorkItem. However, we know the
1727     // maximal count of available Tokens that makes sense (=the number of CPU
1728     // cores), so we can take a conservative guess. The heuristic we use here
1729     // is implemented in the `queue_full_enough()` function.
1730     //
1731     // Some Background on Jobservers
1732     // -----------------------------
1733     // It's worth also touching on the management of parallelism here. We don't
1734     // want to just spawn a thread per work item because while that's optimal
1735     // parallelism it may overload a system with too many threads or violate our
1736     // configuration for the maximum amount of cpu to use for this process. To
1737     // manage this we use the `jobserver` crate.
1738     //
1739     // Job servers are an artifact of GNU make and are used to manage
1740     // parallelism between processes. A jobserver is a glorified IPC semaphore
1741     // basically. Whenever we want to run some work we acquire the semaphore,
1742     // and whenever we're done with that work we release the semaphore. In this
1743     // manner we can ensure that the maximum number of parallel workers is
1744     // capped at any one point in time.
1745     //
1746     // LTO and the coordinator thread
1747     // ------------------------------
1748     //
1749     // The final job the coordinator thread is responsible for is managing LTO
1750     // and how that works. When LTO is requested what we'll to is collect all
1751     // optimized LLVM modules into a local vector on the coordinator. Once all
1752     // modules have been codegened and optimized we hand this to the `lto`
1753     // module for further optimization. The `lto` module will return back a list
1754     // of more modules to work on, which the coordinator will continue to spawn
1755     // work for.
1756     //
1757     // Each LLVM module is automatically sent back to the coordinator for LTO if
1758     // necessary. There's already optimizations in place to avoid sending work
1759     // back to the coordinator if LTO isn't requested.
1760     return thread::spawn(move || {
1761         // We pretend to be within the top-level LLVM time-passes task here:
1762         set_time_depth(1);
1763
1764         let max_workers = ::num_cpus::get();
1765         let mut worker_id_counter = 0;
1766         let mut free_worker_ids = Vec::new();
1767         let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1768             if let Some(id) = free_worker_ids.pop() {
1769                 id
1770             } else {
1771                 let id = worker_id_counter;
1772                 worker_id_counter += 1;
1773                 id
1774             }
1775         };
1776
1777         // This is where we collect codegen units that have gone all the way
1778         // through codegen and LLVM.
1779         let mut compiled_modules = vec![];
1780         let mut compiled_metadata_module = None;
1781         let mut compiled_allocator_module = None;
1782         let mut needs_lto = Vec::new();
1783         let mut lto_import_only_modules = Vec::new();
1784         let mut started_lto = false;
1785         let mut codegen_aborted = false;
1786
1787         // This flag tracks whether all items have gone through codegens
1788         let mut codegen_done = false;
1789
1790         // This is the queue of LLVM work items that still need processing.
1791         let mut work_items = Vec::<(WorkItem, u64)>::new();
1792
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();
1796
1797         let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1798         let mut running = 0;
1799
1800         let mut llvm_start_time = None;
1801
1802         // Run the message loop while there's still anything that needs message
1803         // processing. Note that as soon as codegen is aborted we simply want to
1804         // wait for all existing work to finish, so many of the conditions here
1805         // only apply if codegen hasn't been aborted as they represent pending
1806         // work to be done.
1807         while !codegen_done ||
1808               running > 0 ||
1809               (!codegen_aborted && (
1810                   work_items.len() > 0 ||
1811                   needs_lto.len() > 0 ||
1812                   lto_import_only_modules.len() > 0 ||
1813                   main_thread_worker_state != MainThreadWorkerState::Idle
1814               ))
1815         {
1816
1817             // While there are still CGUs to be codegened, the coordinator has
1818             // to decide how to utilize the compiler processes implicit Token:
1819             // For codegenning more CGU or for running them through LLVM.
1820             if !codegen_done {
1821                 if main_thread_worker_state == MainThreadWorkerState::Idle {
1822                     if !queue_full_enough(work_items.len(), running, max_workers) {
1823                         // The queue is not full enough, codegen more items:
1824                         if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1825                             panic!("Could not send Message::CodegenItem to main thread")
1826                         }
1827                         main_thread_worker_state = MainThreadWorkerState::Codegenning;
1828                     } else {
1829                         // The queue is full enough to not let the worker
1830                         // threads starve. Use the implicit Token to do some
1831                         // LLVM work too.
1832                         let (item, _) = work_items.pop()
1833                             .expect("queue empty - queue_full_enough() broken?");
1834                         let cgcx = CodegenContext {
1835                             worker: get_worker_id(&mut free_worker_ids),
1836                             .. cgcx.clone()
1837                         };
1838                         maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1839                                                &mut llvm_start_time);
1840                         main_thread_worker_state = MainThreadWorkerState::LLVMing;
1841                         spawn_work(cgcx, item);
1842                     }
1843                 }
1844             } else if codegen_aborted {
1845                 // don't queue up any more work if codegen was aborted, we're
1846                 // just waiting for our existing children to finish
1847             } else {
1848                 // If we've finished everything related to normal codegen
1849                 // then it must be the case that we've got some LTO work to do.
1850                 // Perform the serial work here of figuring out what we're
1851                 // going to LTO and then push a bunch of work items onto our
1852                 // queue to do LTO
1853                 if work_items.len() == 0 &&
1854                    running == 0 &&
1855                    main_thread_worker_state == MainThreadWorkerState::Idle {
1856                     assert!(!started_lto);
1857                     assert!(needs_lto.len() + lto_import_only_modules.len() > 0);
1858                     started_lto = true;
1859                     let modules = mem::replace(&mut needs_lto, Vec::new());
1860                     let import_only_modules =
1861                         mem::replace(&mut lto_import_only_modules, Vec::new());
1862                     for (work, cost) in generate_lto_work(&cgcx, modules, import_only_modules) {
1863                         let insertion_index = work_items
1864                             .binary_search_by_key(&cost, |&(_, cost)| cost)
1865                             .unwrap_or_else(|e| e);
1866                         work_items.insert(insertion_index, (work, cost));
1867                         if !cgcx.opts.debugging_opts.no_parallel_llvm {
1868                             helper.request_token();
1869                         }
1870                     }
1871                 }
1872
1873                 // In this branch, we know that everything has been codegened,
1874                 // so it's just a matter of determining whether the implicit
1875                 // Token is free to use for LLVM work.
1876                 match main_thread_worker_state {
1877                     MainThreadWorkerState::Idle => {
1878                         if let Some((item, _)) = work_items.pop() {
1879                             let cgcx = CodegenContext {
1880                                 worker: get_worker_id(&mut free_worker_ids),
1881                                 .. cgcx.clone()
1882                             };
1883                             maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1884                                                    &mut llvm_start_time);
1885                             main_thread_worker_state = MainThreadWorkerState::LLVMing;
1886                             spawn_work(cgcx, item);
1887                         } else {
1888                             // There is no unstarted work, so let the main thread
1889                             // take over for a running worker. Otherwise the
1890                             // implicit token would just go to waste.
1891                             // We reduce the `running` counter by one. The
1892                             // `tokens.truncate()` below will take care of
1893                             // giving the Token back.
1894                             debug_assert!(running > 0);
1895                             running -= 1;
1896                             main_thread_worker_state = MainThreadWorkerState::LLVMing;
1897                         }
1898                     }
1899                     MainThreadWorkerState::Codegenning => {
1900                         bug!("codegen worker should not be codegenning after \
1901                               codegen was already completed")
1902                     }
1903                     MainThreadWorkerState::LLVMing => {
1904                         // Already making good use of that token
1905                     }
1906                 }
1907             }
1908
1909             // Spin up what work we can, only doing this while we've got available
1910             // parallelism slots and work left to spawn.
1911             while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1912                 let (item, _) = work_items.pop().unwrap();
1913
1914                 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1915                                        &mut llvm_start_time);
1916
1917                 let cgcx = CodegenContext {
1918                     worker: get_worker_id(&mut free_worker_ids),
1919                     .. cgcx.clone()
1920                 };
1921
1922                 spawn_work(cgcx, item);
1923                 running += 1;
1924             }
1925
1926             // Relinquish accidentally acquired extra tokens
1927             tokens.truncate(running);
1928
1929             let msg = coordinator_receive.recv().unwrap();
1930             match *msg.downcast::<Message>().ok().unwrap() {
1931                 // Save the token locally and the next turn of the loop will use
1932                 // this to spawn a new unit of work, or it may get dropped
1933                 // immediately if we have no more work to spawn.
1934                 Message::Token(token) => {
1935                     match token {
1936                         Ok(token) => {
1937                             tokens.push(token);
1938
1939                             if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1940                                 // If the main thread token is used for LLVM work
1941                                 // at the moment, we turn that thread into a regular
1942                                 // LLVM worker thread, so the main thread is free
1943                                 // to react to codegen demand.
1944                                 main_thread_worker_state = MainThreadWorkerState::Idle;
1945                                 running += 1;
1946                             }
1947                         }
1948                         Err(e) => {
1949                             let msg = &format!("failed to acquire jobserver token: {}", e);
1950                             shared_emitter.fatal(msg);
1951                             // Exit the coordinator thread
1952                             panic!("{}", msg)
1953                         }
1954                     }
1955                 }
1956
1957                 Message::CodegenDone { llvm_work_item, cost } => {
1958                     // We keep the queue sorted by estimated processing cost,
1959                     // so that more expensive items are processed earlier. This
1960                     // is good for throughput as it gives the main thread more
1961                     // time to fill up the queue and it avoids scheduling
1962                     // expensive items to the end.
1963                     // Note, however, that this is not ideal for memory
1964                     // consumption, as LLVM module sizes are not evenly
1965                     // distributed.
1966                     let insertion_index =
1967                         work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1968                     let insertion_index = match insertion_index {
1969                         Ok(idx) | Err(idx) => idx
1970                     };
1971                     work_items.insert(insertion_index, (llvm_work_item, cost));
1972
1973                     if !cgcx.opts.debugging_opts.no_parallel_llvm {
1974                         helper.request_token();
1975                     }
1976                     assert!(!codegen_aborted);
1977                     assert_eq!(main_thread_worker_state,
1978                                MainThreadWorkerState::Codegenning);
1979                     main_thread_worker_state = MainThreadWorkerState::Idle;
1980                 }
1981
1982                 Message::CodegenComplete => {
1983                     codegen_done = true;
1984                     assert!(!codegen_aborted);
1985                     assert_eq!(main_thread_worker_state,
1986                                MainThreadWorkerState::Codegenning);
1987                     main_thread_worker_state = MainThreadWorkerState::Idle;
1988                 }
1989
1990                 // If codegen is aborted that means translation was aborted due
1991                 // to some normal-ish compiler error. In this situation we want
1992                 // to exit as soon as possible, but we want to make sure all
1993                 // existing work has finished. Flag codegen as being done, and
1994                 // then conditions above will ensure no more work is spawned but
1995                 // we'll keep executing this loop until `running` hits 0.
1996                 Message::CodegenAborted => {
1997                     assert!(!codegen_aborted);
1998                     codegen_done = true;
1999                     codegen_aborted = true;
2000                     assert_eq!(main_thread_worker_state,
2001                                MainThreadWorkerState::Codegenning);
2002                 }
2003
2004                 // If a thread exits successfully then we drop a token associated
2005                 // with that worker and update our `running` count. We may later
2006                 // re-acquire a token to continue running more work. We may also not
2007                 // actually drop a token here if the worker was running with an
2008                 // "ephemeral token"
2009                 //
2010                 // Note that if the thread failed that means it panicked, so we
2011                 // abort immediately.
2012                 Message::Done { result: Ok(compiled_module), worker_id } => {
2013                     if main_thread_worker_state == MainThreadWorkerState::LLVMing {
2014                         main_thread_worker_state = MainThreadWorkerState::Idle;
2015                     } else {
2016                         running -= 1;
2017                     }
2018
2019                     free_worker_ids.push(worker_id);
2020
2021                     match compiled_module.kind {
2022                         ModuleKind::Regular => {
2023                             compiled_modules.push(compiled_module);
2024                         }
2025                         ModuleKind::Metadata => {
2026                             assert!(compiled_metadata_module.is_none());
2027                             compiled_metadata_module = Some(compiled_module);
2028                         }
2029                         ModuleKind::Allocator => {
2030                             assert!(compiled_allocator_module.is_none());
2031                             compiled_allocator_module = Some(compiled_module);
2032                         }
2033                     }
2034                 }
2035                 Message::NeedsLTO { result, worker_id } => {
2036                     assert!(!started_lto);
2037                     if main_thread_worker_state == MainThreadWorkerState::LLVMing {
2038                         main_thread_worker_state = MainThreadWorkerState::Idle;
2039                     } else {
2040                         running -= 1;
2041                     }
2042                     free_worker_ids.push(worker_id);
2043                     needs_lto.push(result);
2044                 }
2045                 Message::AddImportOnlyModule { module_data, work_product } => {
2046                     assert!(!started_lto);
2047                     assert!(!codegen_done);
2048                     assert_eq!(main_thread_worker_state,
2049                                MainThreadWorkerState::Codegenning);
2050                     lto_import_only_modules.push((module_data, work_product));
2051                     main_thread_worker_state = MainThreadWorkerState::Idle;
2052                 }
2053                 Message::Done { result: Err(()), worker_id: _ } => {
2054                     bug!("worker thread panicked");
2055                 }
2056                 Message::CodegenItem => {
2057                     bug!("the coordinator should not receive codegen requests")
2058                 }
2059             }
2060         }
2061
2062         if let Some(llvm_start_time) = llvm_start_time {
2063             let total_llvm_time = Instant::now().duration_since(llvm_start_time);
2064             // This is the top-level timing for all of LLVM, set the time-depth
2065             // to zero.
2066             set_time_depth(0);
2067             print_time_passes_entry(cgcx.time_passes,
2068                                     "LLVM passes",
2069                                     total_llvm_time);
2070         }
2071
2072         // Regardless of what order these modules completed in, report them to
2073         // the backend in the same order every time to ensure that we're handing
2074         // out deterministic results.
2075         compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
2076
2077         let compiled_metadata_module = compiled_metadata_module
2078             .expect("Metadata module not compiled?");
2079
2080         Ok(CompiledModules {
2081             modules: compiled_modules,
2082             metadata_module: compiled_metadata_module,
2083             allocator_module: compiled_allocator_module,
2084         })
2085     });
2086
2087     // A heuristic that determines if we have enough LLVM WorkItems in the
2088     // queue so that the main thread can do LLVM work instead of codegen
2089     fn queue_full_enough(items_in_queue: usize,
2090                          workers_running: usize,
2091                          max_workers: usize) -> bool {
2092         // Tune me, plz.
2093         items_in_queue > 0 &&
2094         items_in_queue >= max_workers.saturating_sub(workers_running / 2)
2095     }
2096
2097     fn maybe_start_llvm_timer(config: &ModuleConfig,
2098                               llvm_start_time: &mut Option<Instant>) {
2099         // We keep track of the -Ztime-passes output manually,
2100         // since the closure-based interface does not fit well here.
2101         if config.time_passes {
2102             if llvm_start_time.is_none() {
2103                 *llvm_start_time = Some(Instant::now());
2104             }
2105         }
2106     }
2107 }
2108
2109 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
2110 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
2111     time_graph::TimelineId(CODEGEN_WORKER_ID);
2112 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2113     time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
2114 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2115     time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
2116
2117 fn spawn_work(cgcx: CodegenContext, work: WorkItem) {
2118     let depth = time_depth();
2119
2120     thread::spawn(move || {
2121         set_time_depth(depth);
2122
2123         // Set up a destructor which will fire off a message that we're done as
2124         // we exit.
2125         struct Bomb {
2126             coordinator_send: Sender<Box<dyn Any + Send>>,
2127             result: Option<WorkItemResult>,
2128             worker_id: usize,
2129         }
2130         impl Drop for Bomb {
2131             fn drop(&mut self) {
2132                 let worker_id = self.worker_id;
2133                 let msg = match self.result.take() {
2134                     Some(WorkItemResult::Compiled(m)) => {
2135                         Message::Done { result: Ok(m), worker_id }
2136                     }
2137                     Some(WorkItemResult::NeedsLTO(m)) => {
2138                         Message::NeedsLTO { result: m, worker_id }
2139                     }
2140                     None => Message::Done { result: Err(()), worker_id }
2141                 };
2142                 drop(self.coordinator_send.send(Box::new(msg)));
2143             }
2144         }
2145
2146         let mut bomb = Bomb {
2147             coordinator_send: cgcx.coordinator_send.clone(),
2148             result: None,
2149             worker_id: cgcx.worker,
2150         };
2151
2152         // Execute the work itself, and if it finishes successfully then flag
2153         // ourselves as a success as well.
2154         //
2155         // Note that we ignore any `FatalError` coming out of `execute_work_item`,
2156         // as a diagnostic was already sent off to the main thread - just
2157         // surface that there was an error in this worker.
2158         bomb.result = {
2159             let timeline = cgcx.time_graph.as_ref().map(|tg| {
2160                 tg.start(time_graph::TimelineId(cgcx.worker),
2161                          LLVM_WORK_PACKAGE_KIND,
2162                          &work.name())
2163             });
2164             let mut timeline = timeline.unwrap_or(Timeline::noop());
2165             execute_work_item(&cgcx, work, &mut timeline).ok()
2166         };
2167     });
2168 }
2169
2170 pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, object: &Path) {
2171     let assembler = cgcx.assembler_cmd
2172         .as_ref()
2173         .expect("cgcx.assembler_cmd is missing?");
2174
2175     let pname = &assembler.name;
2176     let mut cmd = assembler.cmd.clone();
2177     cmd.arg("-c").arg("-o").arg(object).arg(assembly);
2178     debug!("{:?}", cmd);
2179
2180     match cmd.output() {
2181         Ok(prog) => {
2182             if !prog.status.success() {
2183                 let mut note = prog.stderr.clone();
2184                 note.extend_from_slice(&prog.stdout);
2185
2186                 handler.struct_err(&format!("linking with `{}` failed: {}",
2187                                             pname.display(),
2188                                             prog.status))
2189                     .note(&format!("{:?}", &cmd))
2190                     .note(str::from_utf8(&note[..]).unwrap())
2191                     .emit();
2192                 handler.abort_if_errors();
2193             }
2194         },
2195         Err(e) => {
2196             handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
2197             handler.abort_if_errors();
2198         }
2199     }
2200 }
2201
2202 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
2203                             config: &ModuleConfig,
2204                             opt_level: llvm::CodeGenOptLevel,
2205                             prepare_for_thin_lto: bool,
2206                             f: &mut dyn FnMut(&llvm::PassManagerBuilder)) {
2207     use std::ptr;
2208
2209     // Create the PassManagerBuilder for LLVM. We configure it with
2210     // reasonable defaults and prepare it to actually populate the pass
2211     // manager.
2212     let builder = llvm::LLVMPassManagerBuilderCreate();
2213     let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
2214     let inline_threshold = config.inline_threshold;
2215
2216     let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
2217         let s = if s.is_empty() { "default_%m.profraw" } else { s };
2218         CString::new(s.as_bytes()).unwrap()
2219     });
2220
2221     let pgo_use_path = if config.pgo_use.is_empty() {
2222         None
2223     } else {
2224         Some(CString::new(config.pgo_use.as_bytes()).unwrap())
2225     };
2226
2227     llvm::LLVMRustConfigurePassManagerBuilder(
2228         builder,
2229         opt_level,
2230         config.merge_functions,
2231         config.vectorize_slp,
2232         config.vectorize_loop,
2233         prepare_for_thin_lto,
2234         pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2235         pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2236     );
2237
2238     llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
2239
2240     if opt_size != llvm::CodeGenOptSizeNone {
2241         llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
2242     }
2243
2244     llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
2245
2246     // Here we match what clang does (kinda). For O0 we only inline
2247     // always-inline functions (but don't add lifetime intrinsics), at O1 we
2248     // inline with lifetime intrinsics, and O2+ we add an inliner with a
2249     // thresholds copied from clang.
2250     match (opt_level, opt_size, inline_threshold) {
2251         (.., Some(t)) => {
2252             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
2253         }
2254         (llvm::CodeGenOptLevel::Aggressive, ..) => {
2255             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
2256         }
2257         (_, llvm::CodeGenOptSizeDefault, _) => {
2258             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
2259         }
2260         (_, llvm::CodeGenOptSizeAggressive, _) => {
2261             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
2262         }
2263         (llvm::CodeGenOptLevel::None, ..) => {
2264             llvm::LLVMRustAddAlwaysInlinePass(builder, false);
2265         }
2266         (llvm::CodeGenOptLevel::Less, ..) => {
2267             llvm::LLVMRustAddAlwaysInlinePass(builder, true);
2268         }
2269         (llvm::CodeGenOptLevel::Default, ..) => {
2270             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
2271         }
2272         (llvm::CodeGenOptLevel::Other, ..) => {
2273             bug!("CodeGenOptLevel::Other selected")
2274         }
2275     }
2276
2277     f(builder);
2278     llvm::LLVMPassManagerBuilderDispose(builder);
2279 }
2280
2281
2282 enum SharedEmitterMessage {
2283     Diagnostic(Diagnostic),
2284     InlineAsmError(u32, String),
2285     AbortIfErrors,
2286     Fatal(String),
2287 }
2288
2289 #[derive(Clone)]
2290 pub struct SharedEmitter {
2291     sender: Sender<SharedEmitterMessage>,
2292 }
2293
2294 pub struct SharedEmitterMain {
2295     receiver: Receiver<SharedEmitterMessage>,
2296 }
2297
2298 impl SharedEmitter {
2299     pub fn new() -> (SharedEmitter, SharedEmitterMain) {
2300         let (sender, receiver) = channel();
2301
2302         (SharedEmitter { sender }, SharedEmitterMain { receiver })
2303     }
2304
2305     fn inline_asm_error(&self, cookie: u32, msg: String) {
2306         drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
2307     }
2308
2309     fn fatal(&self, msg: &str) {
2310         drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2311     }
2312 }
2313
2314 impl Emitter for SharedEmitter {
2315     fn emit(&mut self, db: &DiagnosticBuilder) {
2316         drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2317             msg: db.message(),
2318             code: db.code.clone(),
2319             lvl: db.level,
2320         })));
2321         for child in &db.children {
2322             drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2323                 msg: child.message(),
2324                 code: None,
2325                 lvl: child.level,
2326             })));
2327         }
2328         drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
2329     }
2330 }
2331
2332 impl SharedEmitterMain {
2333     pub fn check(&self, sess: &Session, blocking: bool) {
2334         loop {
2335             let message = if blocking {
2336                 match self.receiver.recv() {
2337                     Ok(message) => Ok(message),
2338                     Err(_) => Err(()),
2339                 }
2340             } else {
2341                 match self.receiver.try_recv() {
2342                     Ok(message) => Ok(message),
2343                     Err(_) => Err(()),
2344                 }
2345             };
2346
2347             match message {
2348                 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2349                     let handler = sess.diagnostic();
2350                     match diag.code {
2351                         Some(ref code) => {
2352                             handler.emit_with_code(&MultiSpan::new(),
2353                                                    &diag.msg,
2354                                                    code.clone(),
2355                                                    diag.lvl);
2356                         }
2357                         None => {
2358                             handler.emit(&MultiSpan::new(),
2359                                          &diag.msg,
2360                                          diag.lvl);
2361                         }
2362                     }
2363                 }
2364                 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
2365                     match Mark::from_u32(cookie).expn_info() {
2366                         Some(ei) => sess.span_err(ei.call_site, &msg),
2367                         None     => sess.err(&msg),
2368                     }
2369                 }
2370                 Ok(SharedEmitterMessage::AbortIfErrors) => {
2371                     sess.abort_if_errors();
2372                 }
2373                 Ok(SharedEmitterMessage::Fatal(msg)) => {
2374                     sess.fatal(&msg);
2375                 }
2376                 Err(_) => {
2377                     break;
2378                 }
2379             }
2380
2381         }
2382     }
2383 }
2384
2385 pub struct OngoingCodegen {
2386     crate_name: Symbol,
2387     crate_hash: Svh,
2388     metadata: EncodedMetadata,
2389     windows_subsystem: Option<String>,
2390     linker_info: LinkerInfo,
2391     crate_info: CrateInfo,
2392     time_graph: Option<TimeGraph>,
2393     coordinator_send: Sender<Box<dyn Any + Send>>,
2394     codegen_worker_receive: Receiver<Message>,
2395     shared_emitter_main: SharedEmitterMain,
2396     future: thread::JoinHandle<Result<CompiledModules, ()>>,
2397     output_filenames: Arc<OutputFilenames>,
2398 }
2399
2400 impl OngoingCodegen {
2401     pub(crate) fn join(
2402         self,
2403         sess: &Session
2404     ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
2405         self.shared_emitter_main.check(sess, true);
2406         let compiled_modules = match self.future.join() {
2407             Ok(Ok(compiled_modules)) => compiled_modules,
2408             Ok(Err(())) => {
2409                 sess.abort_if_errors();
2410                 panic!("expected abort due to worker thread errors")
2411             },
2412             Err(_) => {
2413                 bug!("panic during codegen/LLVM phase");
2414             }
2415         };
2416
2417         sess.cgu_reuse_tracker.check_expected_reuse(sess);
2418
2419         sess.abort_if_errors();
2420
2421         if let Some(time_graph) = self.time_graph {
2422             time_graph.dump(&format!("{}-timings", self.crate_name));
2423         }
2424
2425         let work_products =
2426             copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
2427                                                              &compiled_modules);
2428         produce_final_output_artifacts(sess,
2429                                        &compiled_modules,
2430                                        &self.output_filenames);
2431
2432         // FIXME: time_llvm_passes support - does this use a global context or
2433         // something?
2434         if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2435             unsafe { llvm::LLVMRustPrintPassTimings(); }
2436         }
2437
2438         (CodegenResults {
2439             crate_name: self.crate_name,
2440             crate_hash: self.crate_hash,
2441             metadata: self.metadata,
2442             windows_subsystem: self.windows_subsystem,
2443             linker_info: self.linker_info,
2444             crate_info: self.crate_info,
2445
2446             modules: compiled_modules.modules,
2447             allocator_module: compiled_modules.allocator_module,
2448             metadata_module: compiled_modules.metadata_module,
2449         }, work_products)
2450     }
2451
2452     pub(crate) fn submit_pre_codegened_module_to_llvm(&self,
2453                                                        tcx: TyCtxt,
2454                                                        module: ModuleCodegen) {
2455         self.wait_for_signal_to_codegen_item();
2456         self.check_for_errors(tcx.sess);
2457
2458         // These are generally cheap and won't through off scheduling.
2459         let cost = 0;
2460         submit_codegened_module_to_llvm(tcx, module, cost);
2461     }
2462
2463     pub fn codegen_finished(&self, tcx: TyCtxt) {
2464         self.wait_for_signal_to_codegen_item();
2465         self.check_for_errors(tcx.sess);
2466         drop(self.coordinator_send.send(Box::new(Message::CodegenComplete)));
2467     }
2468
2469     /// Consume this context indicating that codegen was entirely aborted, and
2470     /// we need to exit as quickly as possible.
2471     ///
2472     /// This method blocks the current thread until all worker threads have
2473     /// finished, and all worker threads should have exited or be real close to
2474     /// exiting at this point.
2475     pub fn codegen_aborted(self) {
2476         // Signal to the coordinator it should spawn no more work and start
2477         // shutdown.
2478         drop(self.coordinator_send.send(Box::new(Message::CodegenAborted)));
2479         drop(self.future.join());
2480     }
2481
2482     pub fn check_for_errors(&self, sess: &Session) {
2483         self.shared_emitter_main.check(sess, false);
2484     }
2485
2486     pub fn wait_for_signal_to_codegen_item(&self) {
2487         match self.codegen_worker_receive.recv() {
2488             Ok(Message::CodegenItem) => {
2489                 // Nothing to do
2490             }
2491             Ok(_) => panic!("unexpected message"),
2492             Err(_) => {
2493                 // One of the LLVM threads must have panicked, fall through so
2494                 // error handling can be reached.
2495             }
2496         }
2497     }
2498 }
2499
2500 // impl Drop for OngoingCodegen {
2501 //     fn drop(&mut self) {
2502 //     }
2503 // }
2504
2505 pub(crate) fn submit_codegened_module_to_llvm(tcx: TyCtxt,
2506                                               module: ModuleCodegen,
2507                                               cost: u64) {
2508     let llvm_work_item = WorkItem::Optimize(module);
2509     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2510         llvm_work_item,
2511         cost,
2512     })));
2513 }
2514
2515 pub(crate) fn submit_post_lto_module_to_llvm(tcx: TyCtxt,
2516                                              module: CachedModuleCodegen) {
2517     let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2518     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2519         llvm_work_item,
2520         cost: 0,
2521     })));
2522 }
2523
2524 pub(crate) fn submit_pre_lto_module_to_llvm(tcx: TyCtxt,
2525                                             module: CachedModuleCodegen) {
2526     let filename = pre_lto_bitcode_filename(&module.name);
2527     let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2528     let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
2529         panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
2530     });
2531
2532     let mmap = unsafe {
2533         memmap::Mmap::map(&file).unwrap_or_else(|e| {
2534             panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2535         })
2536     };
2537
2538     // Schedule the module to be loaded
2539     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::AddImportOnlyModule {
2540         module_data: SerializedModule::FromUncompressedFile(mmap),
2541         work_product: module.source,
2542     })));
2543 }
2544
2545 pub(super) fn pre_lto_bitcode_filename(module_name: &str) -> String {
2546     format!("{}.{}", module_name, PRE_THIN_LTO_BC_EXT)
2547 }
2548
2549 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2550     // This should never be true (because it's not supported). If it is true,
2551     // something is wrong with commandline arg validation.
2552     assert!(!(tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() &&
2553               tcx.sess.target.target.options.is_like_msvc &&
2554               tcx.sess.opts.cg.prefer_dynamic));
2555
2556     tcx.sess.target.target.options.is_like_msvc &&
2557         tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
2558     // ThinLTO can't handle this workaround in all cases, so we don't
2559     // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2560     // dynamic linking when cross-language LTO is enabled.
2561     !tcx.sess.opts.debugging_opts.cross_lang_lto.enabled()
2562 }
2563
2564 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2565 // This is required to satisfy `dllimport` references to static data in .rlibs
2566 // when using MSVC linker.  We do this only for data, as linker can fix up
2567 // code references on its own.
2568 // See #26591, #27438
2569 fn create_msvc_imps(cgcx: &CodegenContext, llcx: &llvm::Context, llmod: &llvm::Module) {
2570     if !cgcx.msvc_imps_needed {
2571         return
2572     }
2573     // The x86 ABI seems to require that leading underscores are added to symbol
2574     // names, so we need an extra underscore on 32-bit. There's also a leading
2575     // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2576     // underscores added in front).
2577     let prefix = if cgcx.target_pointer_width == "32" {
2578         "\x01__imp__"
2579     } else {
2580         "\x01__imp_"
2581     };
2582     unsafe {
2583         let i8p_ty = Type::i8p_llcx(llcx);
2584         let globals = base::iter_globals(llmod)
2585             .filter(|&val| {
2586                 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
2587                     llvm::LLVMIsDeclaration(val) == 0
2588             })
2589             .map(move |val| {
2590                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2591                 let mut imp_name = prefix.as_bytes().to_vec();
2592                 imp_name.extend(name.to_bytes());
2593                 let imp_name = CString::new(imp_name).unwrap();
2594                 (imp_name, val)
2595             })
2596             .collect::<Vec<_>>();
2597         for (imp_name, val) in globals {
2598             let imp = llvm::LLVMAddGlobal(llmod,
2599                                           i8p_ty,
2600                                           imp_name.as_ptr() as *const _);
2601             llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
2602             llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
2603         }
2604     }
2605 }