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