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