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