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