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