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