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