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