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