]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/back/write.rs
Address mw nits
[rust.git] / src / librustc_trans / back / write.rs
1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use back::lto;
12 use back::link::{get_linker, remove};
13 use rustc_incremental::save_trans_partition;
14 use session::config::{OutputFilenames, Passes, SomePasses, AllPasses};
15 use session::Session;
16 use session::config::{self, OutputType};
17 use llvm;
18 use llvm::{ModuleRef, TargetMachineRef, PassManagerRef, DiagnosticInfoRef, ContextRef};
19 use llvm::SMDiagnosticRef;
20 use {CrateTranslation, ModuleLlvm, ModuleSource, ModuleTranslation};
21 use util::common::time;
22 use util::common::path2cstr;
23 use util::fs::link_or_copy;
24 use errors::{self, Handler, Level, DiagnosticBuilder};
25 use errors::emitter::Emitter;
26 use syntax_pos::MultiSpan;
27
28 use std::collections::HashMap;
29 use std::ffi::{CStr, CString};
30 use std::fs;
31 use std::path::{Path, PathBuf};
32 use std::str;
33 use std::sync::{Arc, Mutex};
34 use std::sync::mpsc::channel;
35 use std::thread;
36 use libc::{c_uint, c_void};
37
38 pub fn llvm_err(handler: &errors::Handler, msg: String) -> ! {
39     match llvm::last_error() {
40         Some(err) => panic!(handler.fatal(&format!("{}: {}", msg, err))),
41         None => panic!(handler.fatal(&msg)),
42     }
43 }
44
45 pub fn write_output_file(
46         handler: &errors::Handler,
47         target: llvm::TargetMachineRef,
48         pm: llvm::PassManagerRef,
49         m: ModuleRef,
50         output: &Path,
51         file_type: llvm::FileType) {
52     unsafe {
53         let output_c = path2cstr(output);
54         let result = llvm::LLVMRustWriteOutputFile(
55                 target, pm, m, output_c.as_ptr(), file_type);
56         if !result {
57             llvm_err(handler, format!("could not write output to {}", output.display()));
58         }
59     }
60 }
61
62
63 struct Diagnostic {
64     msg: String,
65     code: Option<String>,
66     lvl: Level,
67 }
68
69 // We use an Arc instead of just returning a list of diagnostics from the
70 // child thread because we need to make sure that the messages are seen even
71 // if the child thread panics (for example, when `fatal` is called).
72 #[derive(Clone)]
73 struct SharedEmitter {
74     buffer: Arc<Mutex<Vec<Diagnostic>>>,
75 }
76
77 impl SharedEmitter {
78     fn new() -> SharedEmitter {
79         SharedEmitter {
80             buffer: Arc::new(Mutex::new(Vec::new())),
81         }
82     }
83
84     fn dump(&mut self, handler: &Handler) {
85         let mut buffer = self.buffer.lock().unwrap();
86         for diag in &*buffer {
87             match diag.code {
88                 Some(ref code) => {
89                     handler.emit_with_code(&MultiSpan::new(),
90                                            &diag.msg,
91                                            &code[..],
92                                            diag.lvl);
93                 },
94                 None => {
95                     handler.emit(&MultiSpan::new(),
96                                  &diag.msg,
97                                  diag.lvl);
98                 },
99             }
100         }
101         buffer.clear();
102     }
103 }
104
105 impl Emitter for SharedEmitter {
106     fn emit(&mut self, db: &DiagnosticBuilder) {
107         self.buffer.lock().unwrap().push(Diagnostic {
108             msg: db.message.to_string(),
109             code: db.code.clone(),
110             lvl: db.level,
111         });
112         for child in &db.children {
113             self.buffer.lock().unwrap().push(Diagnostic {
114                 msg: child.message.to_string(),
115                 code: None,
116                 lvl: child.level,
117             });
118         }
119     }
120 }
121
122 // On android, we by default compile for armv7 processors. This enables
123 // things like double word CAS instructions (rather than emulating them)
124 // which are *far* more efficient. This is obviously undesirable in some
125 // cases, so if any sort of target feature is specified we don't append v7
126 // to the feature list.
127 //
128 // On iOS only armv7 and newer are supported. So it is useful to
129 // get all hardware potential via VFP3 (hardware floating point)
130 // and NEON (SIMD) instructions supported by LLVM.
131 // Note that without those flags various linking errors might
132 // arise as some of intrinsics are converted into function calls
133 // and nobody provides implementations those functions
134 fn target_feature(sess: &Session) -> String {
135     format!("{},{}", sess.target.target.options.features, sess.opts.cg.target_feature)
136 }
137
138 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
139     match optimize {
140       config::OptLevel::No => llvm::CodeGenLevelNone,
141       config::OptLevel::Less => llvm::CodeGenLevelLess,
142       config::OptLevel::Default => llvm::CodeGenLevelDefault,
143       config::OptLevel::Aggressive => llvm::CodeGenLevelAggressive,
144       _ => llvm::CodeGenLevelDefault,
145     }
146 }
147
148 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
149     match optimize {
150       config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
151       config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
152       _ => llvm::CodeGenOptSizeNone,
153     }
154 }
155
156 pub fn create_target_machine(sess: &Session) -> TargetMachineRef {
157     let reloc_model_arg = match sess.opts.cg.relocation_model {
158         Some(ref s) => &s[..],
159         None => &sess.target.target.options.relocation_model[..],
160     };
161     let reloc_model = match reloc_model_arg {
162         "pic" => llvm::RelocPIC,
163         "static" => llvm::RelocStatic,
164         "default" => llvm::RelocDefault,
165         "dynamic-no-pic" => llvm::RelocDynamicNoPic,
166         _ => {
167             sess.err(&format!("{:?} is not a valid relocation mode",
168                              sess.opts
169                                  .cg
170                                  .relocation_model));
171             sess.abort_if_errors();
172             bug!();
173         }
174     };
175
176     let opt_level = get_llvm_opt_level(sess.opts.optimize);
177     let use_softfp = sess.opts.cg.soft_float;
178
179     let any_library = sess.crate_types.borrow().iter().any(|ty| {
180         *ty != config::CrateTypeExecutable
181     });
182
183     let ffunction_sections = sess.target.target.options.function_sections;
184     let fdata_sections = ffunction_sections;
185
186     let code_model_arg = match sess.opts.cg.code_model {
187         Some(ref s) => &s[..],
188         None => &sess.target.target.options.code_model[..],
189     };
190
191     let code_model = match code_model_arg {
192         "default" => llvm::CodeModelDefault,
193         "small" => llvm::CodeModelSmall,
194         "kernel" => llvm::CodeModelKernel,
195         "medium" => llvm::CodeModelMedium,
196         "large" => llvm::CodeModelLarge,
197         _ => {
198             sess.err(&format!("{:?} is not a valid code model",
199                              sess.opts
200                                  .cg
201                                  .code_model));
202             sess.abort_if_errors();
203             bug!();
204         }
205     };
206
207     let triple = &sess.target.target.llvm_target;
208
209     let tm = unsafe {
210         let triple = CString::new(triple.as_bytes()).unwrap();
211         let cpu = match sess.opts.cg.target_cpu {
212             Some(ref s) => &**s,
213             None => &*sess.target.target.options.cpu
214         };
215         let cpu = CString::new(cpu.as_bytes()).unwrap();
216         let features = CString::new(target_feature(sess).as_bytes()).unwrap();
217         llvm::LLVMRustCreateTargetMachine(
218             triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
219             code_model,
220             reloc_model,
221             opt_level,
222             use_softfp,
223             !any_library && reloc_model == llvm::RelocPIC,
224             ffunction_sections,
225             fdata_sections,
226         )
227     };
228
229     if tm.is_null() {
230         llvm_err(sess.diagnostic(),
231                  format!("Could not create LLVM TargetMachine for triple: {}",
232                          triple).to_string());
233     } else {
234         return tm;
235     };
236 }
237
238
239 /// Module-specific configuration for `optimize_and_codegen`.
240 #[derive(Clone)]
241 pub struct ModuleConfig {
242     /// LLVM TargetMachine to use for codegen.
243     tm: TargetMachineRef,
244     /// Names of additional optimization passes to run.
245     passes: Vec<String>,
246     /// Some(level) to optimize at a certain level, or None to run
247     /// absolutely no optimizations (used for the metadata module).
248     opt_level: Option<llvm::CodeGenOptLevel>,
249
250     /// Some(level) to optimize binary size, or None to not affect program size.
251     opt_size: Option<llvm::CodeGenOptSize>,
252
253     // Flags indicating which outputs to produce.
254     emit_no_opt_bc: bool,
255     emit_bc: bool,
256     emit_lto_bc: bool,
257     emit_ir: bool,
258     emit_asm: bool,
259     emit_obj: bool,
260     // Miscellaneous flags.  These are mostly copied from command-line
261     // options.
262     no_verify: bool,
263     no_prepopulate_passes: bool,
264     no_builtins: bool,
265     time_passes: bool,
266     vectorize_loop: bool,
267     vectorize_slp: bool,
268     merge_functions: bool,
269     inline_threshold: Option<usize>,
270     // Instead of creating an object file by doing LLVM codegen, just
271     // make the object file bitcode. Provides easy compatibility with
272     // emscripten's ecc compiler, when used as the linker.
273     obj_is_bitcode: bool,
274 }
275
276 unsafe impl Send for ModuleConfig { }
277
278 impl ModuleConfig {
279     fn new(tm: TargetMachineRef, passes: Vec<String>) -> ModuleConfig {
280         ModuleConfig {
281             tm: tm,
282             passes: passes,
283             opt_level: None,
284             opt_size: None,
285
286             emit_no_opt_bc: false,
287             emit_bc: false,
288             emit_lto_bc: false,
289             emit_ir: false,
290             emit_asm: false,
291             emit_obj: false,
292             obj_is_bitcode: false,
293
294             no_verify: false,
295             no_prepopulate_passes: false,
296             no_builtins: false,
297             time_passes: false,
298             vectorize_loop: false,
299             vectorize_slp: false,
300             merge_functions: false,
301             inline_threshold: None
302         }
303     }
304
305     fn set_flags(&mut self, sess: &Session, trans: &CrateTranslation) {
306         self.no_verify = sess.no_verify();
307         self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
308         self.no_builtins = trans.no_builtins;
309         self.time_passes = sess.time_passes();
310         self.inline_threshold = sess.opts.cg.inline_threshold;
311         self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode;
312
313         // Copy what clang does by turning on loop vectorization at O2 and
314         // slp vectorization at O3. Otherwise configure other optimization aspects
315         // of this pass manager builder.
316         self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
317                              (sess.opts.optimize == config::OptLevel::Default ||
318                               sess.opts.optimize == config::OptLevel::Aggressive);
319         self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
320                             sess.opts.optimize == config::OptLevel::Aggressive;
321
322         self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
323                                sess.opts.optimize == config::OptLevel::Aggressive;
324     }
325 }
326
327 /// Additional resources used by optimize_and_codegen (not module specific)
328 struct CodegenContext<'a> {
329     // Extra resources used for LTO: (sess, reachable).  This will be `None`
330     // when running in a worker thread.
331     lto_ctxt: Option<(&'a Session, &'a [String])>,
332     // Handler to use for diagnostics produced during codegen.
333     handler: &'a Handler,
334     // LLVM passes added by plugins.
335     plugin_passes: Vec<String>,
336     // LLVM optimizations for which we want to print remarks.
337     remark: Passes,
338     // Worker thread number
339     worker: usize,
340 }
341
342 impl<'a> CodegenContext<'a> {
343     fn new_with_session(sess: &'a Session, reachable: &'a [String]) -> CodegenContext<'a> {
344         CodegenContext {
345             lto_ctxt: Some((sess, reachable)),
346             handler: sess.diagnostic(),
347             plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
348             remark: sess.opts.cg.remark.clone(),
349             worker: 0,
350         }
351     }
352 }
353
354 struct HandlerFreeVars<'a> {
355     llcx: ContextRef,
356     cgcx: &'a CodegenContext<'a>,
357 }
358
359 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext<'a>,
360                                                msg: &'b str,
361                                                cookie: c_uint) {
362     use syntax_pos::ExpnId;
363
364     match cgcx.lto_ctxt {
365         Some((sess, _)) => {
366             sess.codemap().with_expn_info(ExpnId::from_u32(cookie), |info| match info {
367                 Some(ei) => sess.span_err(ei.call_site, msg),
368                 None     => sess.err(msg),
369             });
370         }
371
372         None => {
373             cgcx.handler.struct_err(msg)
374                         .note("build without -C codegen-units for more exact errors")
375                         .emit();
376         }
377     }
378 }
379
380 unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
381                                         user: *const c_void,
382                                         cookie: c_uint) {
383     let HandlerFreeVars { cgcx, .. } = *(user as *const HandlerFreeVars);
384
385     let msg = llvm::build_string(|s| llvm::LLVMWriteSMDiagnosticToString(diag, s))
386         .expect("non-UTF8 SMDiagnostic");
387
388     report_inline_asm(cgcx, &msg[..], cookie);
389 }
390
391 unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
392     let HandlerFreeVars { llcx, cgcx } = *(user as *const HandlerFreeVars);
393
394     match llvm::diagnostic::Diagnostic::unpack(info) {
395         llvm::diagnostic::InlineAsm(inline) => {
396             report_inline_asm(cgcx,
397                               &llvm::twine_to_string(inline.message),
398                               inline.cookie);
399         }
400
401         llvm::diagnostic::Optimization(opt) => {
402             let pass_name = str::from_utf8(CStr::from_ptr(opt.pass_name).to_bytes())
403                                 .ok()
404                                 .expect("got a non-UTF8 pass name from LLVM");
405             let enabled = match cgcx.remark {
406                 AllPasses => true,
407                 SomePasses(ref v) => v.iter().any(|s| *s == pass_name),
408             };
409
410             if enabled {
411                 let loc = llvm::debug_loc_to_string(llcx, opt.debug_loc);
412                 cgcx.handler.note_without_error(&format!("optimization {} for {} at {}: {}",
413                                                 opt.kind.describe(),
414                                                 pass_name,
415                                                 if loc.is_empty() { "[unknown]" } else { &*loc },
416                                                 llvm::twine_to_string(opt.message)));
417             }
418         }
419
420         _ => (),
421     }
422 }
423
424 // Unsafe due to LLVM calls.
425 unsafe fn optimize_and_codegen(cgcx: &CodegenContext,
426                                mtrans: ModuleTranslation,
427                                mllvm: ModuleLlvm,
428                                config: ModuleConfig,
429                                output_names: OutputFilenames) {
430     let llmod = mllvm.llmod;
431     let llcx = mllvm.llcx;
432     let tm = config.tm;
433
434     // llcx doesn't outlive this function, so we can put this on the stack.
435     let fv = HandlerFreeVars {
436         llcx: llcx,
437         cgcx: cgcx,
438     };
439     let fv = &fv as *const HandlerFreeVars as *mut c_void;
440
441     llvm::LLVMSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, fv);
442     llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, fv);
443
444     let module_name = Some(&mtrans.name[..]);
445
446     if config.emit_no_opt_bc {
447         let out = output_names.temp_path_ext("no-opt.bc", module_name);
448         let out = path2cstr(&out);
449         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
450     }
451
452     if config.opt_level.is_some() {
453         // Create the two optimizing pass managers. These mirror what clang
454         // does, and are by populated by LLVM's default PassManagerBuilder.
455         // Each manager has a different set of passes, but they also share
456         // some common passes.
457         let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
458         let mpm = llvm::LLVMCreatePassManager();
459
460         // If we're verifying or linting, add them to the function pass
461         // manager.
462         let addpass = |pass_name: &str| {
463             let pass_name = CString::new(pass_name).unwrap();
464             let pass = llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr());
465             if pass.is_null() {
466                 return false;
467             }
468             let pass_manager = match llvm::LLVMRustPassKind(pass) {
469                 llvm::SupportedPassKind::Function => fpm,
470                 llvm::SupportedPassKind::Module => mpm,
471                 llvm::SupportedPassKind::Unsupported => {
472                     cgcx.handler.err("Encountered LLVM pass kind we can't handle");
473                     return true
474                 },
475             };
476             llvm::LLVMRustAddPass(pass_manager, pass);
477             true
478         };
479
480         if !config.no_verify { assert!(addpass("verify")); }
481         if !config.no_prepopulate_passes {
482             llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
483             llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
484             with_llvm_pmb(llmod, &config, &mut |b| {
485                 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
486                 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
487             })
488         }
489
490         for pass in &config.passes {
491             if !addpass(pass) {
492                 cgcx.handler.warn(&format!("unknown pass `{}`, ignoring",
493                                            pass));
494             }
495         }
496
497         for pass in &cgcx.plugin_passes {
498             if !addpass(pass) {
499                 cgcx.handler.err(&format!("a plugin asked for LLVM pass \
500                                            `{}` but LLVM does not \
501                                            recognize it", pass));
502             }
503         }
504
505         cgcx.handler.abort_if_errors();
506
507         // Finally, run the actual optimization passes
508         time(config.time_passes, &format!("llvm function passes [{}]", cgcx.worker), ||
509              llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
510         time(config.time_passes, &format!("llvm module passes [{}]", cgcx.worker), ||
511              llvm::LLVMRunPassManager(mpm, llmod));
512
513         // Deallocate managers that we're now done with
514         llvm::LLVMDisposePassManager(fpm);
515         llvm::LLVMDisposePassManager(mpm);
516
517         match cgcx.lto_ctxt {
518             Some((sess, reachable)) if sess.lto() =>  {
519                 time(sess.time_passes(), "all lto passes", || {
520                     let temp_no_opt_bc_filename =
521                         output_names.temp_path_ext("no-opt.lto.bc", module_name);
522                     lto::run(sess,
523                              llmod,
524                              tm,
525                              reachable,
526                              &config,
527                              &temp_no_opt_bc_filename);
528                 });
529                 if config.emit_lto_bc {
530                     let out = output_names.temp_path_ext("lto.bc", module_name);
531                     let out = path2cstr(&out);
532                     llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
533                 }
534             },
535             _ => {},
536         }
537     }
538
539     // A codegen-specific pass manager is used to generate object
540     // files for an LLVM module.
541     //
542     // Apparently each of these pass managers is a one-shot kind of
543     // thing, so we create a new one for each type of output. The
544     // pass manager passed to the closure should be ensured to not
545     // escape the closure itself, and the manager should only be
546     // used once.
547     unsafe fn with_codegen<F>(tm: TargetMachineRef,
548                               llmod: ModuleRef,
549                               no_builtins: bool,
550                               f: F) where
551         F: FnOnce(PassManagerRef),
552     {
553         let cpm = llvm::LLVMCreatePassManager();
554         llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
555         llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
556         f(cpm);
557     }
558
559     // Change what we write and cleanup based on whether obj files are
560     // just llvm bitcode. In that case write bitcode, and possibly
561     // delete the bitcode if it wasn't requested. Don't generate the
562     // machine code, instead copy the .o file from the .bc
563     let write_bc = config.emit_bc || config.obj_is_bitcode;
564     let rm_bc = !config.emit_bc && config.obj_is_bitcode;
565     let write_obj = config.emit_obj && !config.obj_is_bitcode;
566     let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
567
568     let bc_out = output_names.temp_path(OutputType::Bitcode, module_name);
569     let obj_out = output_names.temp_path(OutputType::Object, module_name);
570
571     if write_bc {
572         let bc_out_c = path2cstr(&bc_out);
573         llvm::LLVMWriteBitcodeToFile(llmod, bc_out_c.as_ptr());
574     }
575
576     time(config.time_passes, &format!("codegen passes [{}]", cgcx.worker), || {
577         if config.emit_ir {
578             let out = output_names.temp_path(OutputType::LlvmAssembly, module_name);
579             let out = path2cstr(&out);
580             with_codegen(tm, llmod, config.no_builtins, |cpm| {
581                 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr());
582                 llvm::LLVMDisposePassManager(cpm);
583             })
584         }
585
586         if config.emit_asm {
587             let path = output_names.temp_path(OutputType::Assembly, module_name);
588
589             // We can't use the same module for asm and binary output, because that triggers
590             // various errors like invalid IR or broken binaries, so we might have to clone the
591             // module to produce the asm output
592             let llmod = if config.emit_obj {
593                 llvm::LLVMCloneModule(llmod)
594             } else {
595                 llmod
596             };
597             with_codegen(tm, llmod, config.no_builtins, |cpm| {
598                 write_output_file(cgcx.handler, tm, cpm, llmod, &path,
599                                   llvm::AssemblyFileType);
600             });
601             if config.emit_obj {
602                 llvm::LLVMDisposeModule(llmod);
603             }
604         }
605
606         if write_obj {
607             with_codegen(tm, llmod, config.no_builtins, |cpm| {
608                 write_output_file(cgcx.handler, tm, cpm, llmod, &obj_out, llvm::ObjectFileType);
609             });
610         }
611     });
612
613     if copy_bc_to_obj {
614         debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
615         if let Err(e) = fs::copy(&bc_out, &obj_out) {
616             cgcx.handler.err(&format!("failed to copy bitcode to object file: {}", e));
617         }
618     }
619
620     if rm_bc {
621         debug!("removing_bitcode {:?}", bc_out);
622         if let Err(e) = fs::remove_file(&bc_out) {
623             cgcx.handler.err(&format!("failed to remove bitcode: {}", e));
624         }
625     }
626
627     llvm::LLVMRustDisposeTargetMachine(tm);
628 }
629
630
631 pub fn cleanup_llvm(trans: &CrateTranslation) {
632     for module in trans.modules.iter() {
633         unsafe {
634             match module.source {
635                 ModuleSource::Translated(llvm) => {
636                     llvm::LLVMDisposeModule(llvm.llmod);
637                     llvm::LLVMContextDispose(llvm.llcx);
638                 }
639                 ModuleSource::Preexisting(_) => {
640                 }
641             }
642         }
643     }
644 }
645
646 pub fn run_passes(sess: &Session,
647                   trans: &CrateTranslation,
648                   output_types: &HashMap<OutputType, Option<PathBuf>>,
649                   crate_output: &OutputFilenames) {
650     // It's possible that we have `codegen_units > 1` but only one item in
651     // `trans.modules`.  We could theoretically proceed and do LTO in that
652     // case, but it would be confusing to have the validity of
653     // `-Z lto -C codegen-units=2` depend on details of the crate being
654     // compiled, so we complain regardless.
655     if sess.lto() && sess.opts.cg.codegen_units > 1 {
656         // This case is impossible to handle because LTO expects to be able
657         // to combine the entire crate and all its dependencies into a
658         // single compilation unit, but each codegen unit is in a separate
659         // LLVM context, so they can't easily be combined.
660         sess.fatal("can't perform LTO when using multiple codegen units");
661     }
662
663     // Sanity check
664     assert!(trans.modules.len() == sess.opts.cg.codegen_units ||
665             sess.opts.debugging_opts.incremental.is_some());
666
667     let tm = create_target_machine(sess);
668
669     // Figure out what we actually need to build.
670
671     let mut modules_config = ModuleConfig::new(tm, sess.opts.cg.passes.clone());
672     let mut metadata_config = ModuleConfig::new(tm, vec!());
673
674     modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
675     modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
676
677     // Save all versions of the bytecode if we're saving our temporaries.
678     if sess.opts.cg.save_temps {
679         modules_config.emit_no_opt_bc = true;
680         modules_config.emit_bc = true;
681         modules_config.emit_lto_bc = true;
682         metadata_config.emit_bc = true;
683     }
684
685     // Emit bitcode files for the crate if we're emitting an rlib.
686     // Whenever an rlib is created, the bitcode is inserted into the
687     // archive in order to allow LTO against it.
688     let needs_crate_bitcode =
689             sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
690             sess.opts.output_types.contains_key(&OutputType::Exe);
691     let needs_crate_object =
692             sess.opts.output_types.contains_key(&OutputType::Exe);
693     if needs_crate_bitcode {
694         modules_config.emit_bc = true;
695     }
696
697     for output_type in output_types.keys() {
698         match *output_type {
699             OutputType::Bitcode => { modules_config.emit_bc = true; },
700             OutputType::LlvmAssembly => { modules_config.emit_ir = true; },
701             OutputType::Assembly => {
702                 modules_config.emit_asm = true;
703                 // If we're not using the LLVM assembler, this function
704                 // could be invoked specially with output_type_assembly, so
705                 // in this case we still want the metadata object file.
706                 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
707                     metadata_config.emit_obj = true;
708                 }
709             },
710             OutputType::Object => { modules_config.emit_obj = true; },
711             OutputType::Exe => {
712                 modules_config.emit_obj = true;
713                 metadata_config.emit_obj = true;
714             },
715             OutputType::DepInfo => {}
716         }
717     }
718
719     modules_config.set_flags(sess, trans);
720     metadata_config.set_flags(sess, trans);
721
722
723     // Populate a buffer with a list of codegen threads.  Items are processed in
724     // LIFO order, just because it's a tiny bit simpler that way.  (The order
725     // doesn't actually matter.)
726     let mut work_items = Vec::with_capacity(1 + trans.modules.len());
727
728     {
729         let work = build_work_item(sess,
730                                    trans.metadata_module.clone(),
731                                    metadata_config.clone(),
732                                    crate_output.clone());
733         work_items.push(work);
734     }
735
736     for mtrans in trans.modules.iter() {
737         let work = build_work_item(sess,
738                                    mtrans.clone(),
739                                    modules_config.clone(),
740                                    crate_output.clone());
741         work_items.push(work);
742     }
743
744     // Process the work items, optionally using worker threads.
745     // NOTE: This code is not really adapted to incremental compilation where
746     //       the compiler decides the number of codegen units (and will
747     //       potentially create hundreds of them).
748     let num_workers = work_items.len() - 1;
749     if num_workers == 1 {
750         run_work_singlethreaded(sess, &trans.reachable, work_items);
751     } else {
752         run_work_multithreaded(sess, work_items, num_workers);
753     }
754
755     // If in incr. comp. mode, preserve the `.o` files for potential re-use
756     for mtrans in trans.modules.iter() {
757         let path_to_obj = crate_output.temp_path(OutputType::Object, Some(&mtrans.name));
758         debug!("wrote module {:?} to {:?}", mtrans.name, path_to_obj);
759         save_trans_partition(sess, &mtrans.name, mtrans.symbol_name_hash, &path_to_obj);
760     }
761
762     // All codegen is finished.
763     unsafe {
764         llvm::LLVMRustDisposeTargetMachine(tm);
765     }
766
767     // Produce final compile outputs.
768     let copy_gracefully = |from: &Path, to: &Path| {
769         if let Err(e) = fs::copy(from, to) {
770             sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
771         }
772     };
773
774     let copy_if_one_unit = |output_type: OutputType,
775                             keep_numbered: bool| {
776         if trans.modules.len() == 1 {
777             // 1) Only one codegen unit.  In this case it's no difficulty
778             //    to copy `foo.0.x` to `foo.x`.
779             let module_name = Some(&(trans.modules[0].name)[..]);
780             let path = crate_output.temp_path(output_type, module_name);
781             copy_gracefully(&path,
782                             &crate_output.path(output_type));
783             if !sess.opts.cg.save_temps && !keep_numbered {
784                 // The user just wants `foo.x`, not `foo.#module-name#.x`.
785                 remove(sess, &path);
786             }
787         } else {
788             let ext = crate_output.temp_path(output_type, None)
789                                   .extension()
790                                   .unwrap()
791                                   .to_str()
792                                   .unwrap()
793                                   .to_owned();
794
795             if crate_output.outputs.contains_key(&output_type) {
796                 // 2) Multiple codegen units, with `--emit foo=some_name`.  We have
797                 //    no good solution for this case, so warn the user.
798                 sess.warn(&format!("ignoring emit path because multiple .{} files \
799                                     were produced", ext));
800             } else if crate_output.single_output_file.is_some() {
801                 // 3) Multiple codegen units, with `-o some_name`.  We have
802                 //    no good solution for this case, so warn the user.
803                 sess.warn(&format!("ignoring -o because multiple .{} files \
804                                     were produced", ext));
805             } else {
806                 // 4) Multiple codegen units, but no explicit name.  We
807                 //    just leave the `foo.0.x` files in place.
808                 // (We don't have to do any work in this case.)
809             }
810         }
811     };
812
813     // Flag to indicate whether the user explicitly requested bitcode.
814     // Otherwise, we produced it only as a temporary output, and will need
815     // to get rid of it.
816     let mut user_wants_bitcode = false;
817     let mut user_wants_objects = false;
818     for output_type in output_types.keys() {
819         match *output_type {
820             OutputType::Bitcode => {
821                 user_wants_bitcode = true;
822                 // Copy to .bc, but always keep the .0.bc.  There is a later
823                 // check to figure out if we should delete .0.bc files, or keep
824                 // them for making an rlib.
825                 copy_if_one_unit(OutputType::Bitcode, true);
826             }
827             OutputType::LlvmAssembly => {
828                 copy_if_one_unit(OutputType::LlvmAssembly, false);
829             }
830             OutputType::Assembly => {
831                 copy_if_one_unit(OutputType::Assembly, false);
832             }
833             OutputType::Object => {
834                 user_wants_objects = true;
835                 copy_if_one_unit(OutputType::Object, true);
836             }
837             OutputType::Exe |
838             OutputType::DepInfo => {}
839         }
840     }
841     let user_wants_bitcode = user_wants_bitcode;
842
843     // Clean up unwanted temporary files.
844
845     // We create the following files by default:
846     //  - crate.#module-name#.bc
847     //  - crate.#module-name#.o
848     //  - crate.metadata.bc
849     //  - crate.metadata.o
850     //  - crate.o (linked from crate.##.o)
851     //  - crate.bc (copied from crate.##.bc)
852     // We may create additional files if requested by the user (through
853     // `-C save-temps` or `--emit=` flags).
854
855     if !sess.opts.cg.save_temps {
856         // Remove the temporary .#module-name#.o objects.  If the user didn't
857         // explicitly request bitcode (with --emit=bc), and the bitcode is not
858         // needed for building an rlib, then we must remove .#module-name#.bc as
859         // well.
860
861         // Specific rules for keeping .#module-name#.bc:
862         //  - If we're building an rlib (`needs_crate_bitcode`), then keep
863         //    it.
864         //  - If the user requested bitcode (`user_wants_bitcode`), and
865         //    codegen_units > 1, then keep it.
866         //  - If the user requested bitcode but codegen_units == 1, then we
867         //    can toss .#module-name#.bc because we copied it to .bc earlier.
868         //  - If we're not building an rlib and the user didn't request
869         //    bitcode, then delete .#module-name#.bc.
870         // If you change how this works, also update back::link::link_rlib,
871         // where .#module-name#.bc files are (maybe) deleted after making an
872         // rlib.
873         let keep_numbered_bitcode = needs_crate_bitcode ||
874                 (user_wants_bitcode && sess.opts.cg.codegen_units > 1);
875
876         let keep_numbered_objects = needs_crate_object ||
877                 (user_wants_objects && sess.opts.cg.codegen_units > 1);
878
879         for module_name in trans.modules.iter().map(|m| Some(&m.name[..])) {
880             if modules_config.emit_obj && !keep_numbered_objects {
881                 let path = crate_output.temp_path(OutputType::Object, module_name);
882                 remove(sess, &path);
883             }
884
885             if modules_config.emit_bc && !keep_numbered_bitcode {
886                 let path = crate_output.temp_path(OutputType::Bitcode, module_name);
887                 remove(sess, &path);
888             }
889         }
890
891         if metadata_config.emit_bc && !user_wants_bitcode {
892             let path = crate_output.temp_path(OutputType::Bitcode,
893                                               Some(&trans.metadata_module.name[..]));
894             remove(sess, &path);
895         }
896     }
897
898     // We leave the following files around by default:
899     //  - crate.o
900     //  - crate.metadata.o
901     //  - crate.bc
902     // These are used in linking steps and will be cleaned up afterward.
903
904     // FIXME: time_llvm_passes support - does this use a global context or
905     // something?
906     if sess.opts.cg.codegen_units == 1 && sess.time_llvm_passes() {
907         unsafe { llvm::LLVMRustPrintPassTimings(); }
908     }
909 }
910
911 struct WorkItem {
912     mtrans: ModuleTranslation,
913     config: ModuleConfig,
914     output_names: OutputFilenames
915 }
916
917 fn build_work_item(sess: &Session,
918                    mtrans: ModuleTranslation,
919                    config: ModuleConfig,
920                    output_names: OutputFilenames)
921                    -> WorkItem
922 {
923     let mut config = config;
924     config.tm = create_target_machine(sess);
925     WorkItem {
926         mtrans: mtrans,
927         config: config,
928         output_names: output_names
929     }
930 }
931
932 fn execute_work_item(cgcx: &CodegenContext,
933                      work_item: WorkItem) {
934     unsafe {
935         match work_item.mtrans.source {
936             ModuleSource::Translated(mllvm) => {
937                 debug!("llvm-optimizing {:?}", work_item.mtrans.name);
938                 optimize_and_codegen(cgcx,
939                                      work_item.mtrans,
940                                      mllvm,
941                                      work_item.config,
942                                      work_item.output_names);
943             }
944             ModuleSource::Preexisting(ref buf) => {
945                 let obj_out = work_item.output_names.temp_path(OutputType::Object,
946                                                                Some(&work_item.mtrans.name));
947                 debug!("copying pre-existing module `{}` from {} to {}",
948                        work_item.mtrans.name,
949                        buf.display(),
950                        obj_out.display());
951                 match link_or_copy(buf, &obj_out) {
952                     Ok(()) => { }
953                     Err(err) => {
954                         cgcx.handler.err(&format!("unable to copy {} to {}: {}",
955                                                   buf.display(),
956                                                   obj_out.display(),
957                                                   err));
958                     }
959                 }
960             }
961         }
962     }
963 }
964
965 fn run_work_singlethreaded(sess: &Session,
966                            reachable: &[String],
967                            work_items: Vec<WorkItem>) {
968     let cgcx = CodegenContext::new_with_session(sess, reachable);
969
970     // Since we're running single-threaded, we can pass the session to
971     // the proc, allowing `optimize_and_codegen` to perform LTO.
972     for work in work_items.into_iter().rev() {
973         execute_work_item(&cgcx, work);
974     }
975 }
976
977 fn run_work_multithreaded(sess: &Session,
978                           work_items: Vec<WorkItem>,
979                           num_workers: usize) {
980     assert!(num_workers > 0);
981
982     // Run some workers to process the work items.
983     let work_items_arc = Arc::new(Mutex::new(work_items));
984     let mut diag_emitter = SharedEmitter::new();
985     let mut futures = Vec::with_capacity(num_workers);
986
987     for i in 0..num_workers {
988         let work_items_arc = work_items_arc.clone();
989         let diag_emitter = diag_emitter.clone();
990         let plugin_passes = sess.plugin_llvm_passes.borrow().clone();
991         let remark = sess.opts.cg.remark.clone();
992
993         let (tx, rx) = channel();
994         let mut tx = Some(tx);
995         futures.push(rx);
996
997         thread::Builder::new().name(format!("codegen-{}", i)).spawn(move || {
998             let diag_handler = Handler::with_emitter(true, false, box diag_emitter);
999
1000             // Must construct cgcx inside the proc because it has non-Send
1001             // fields.
1002             let cgcx = CodegenContext {
1003                 lto_ctxt: None,
1004                 handler: &diag_handler,
1005                 plugin_passes: plugin_passes,
1006                 remark: remark,
1007                 worker: i,
1008             };
1009
1010             loop {
1011                 // Avoid holding the lock for the entire duration of the match.
1012                 let maybe_work = work_items_arc.lock().unwrap().pop();
1013                 match maybe_work {
1014                     Some(work) => {
1015                         execute_work_item(&cgcx, work);
1016
1017                         // Make sure to fail the worker so the main thread can
1018                         // tell that there were errors.
1019                         cgcx.handler.abort_if_errors();
1020                     }
1021                     None => break,
1022                 }
1023             }
1024
1025             tx.take().unwrap().send(()).unwrap();
1026         }).unwrap();
1027     }
1028
1029     let mut panicked = false;
1030     for rx in futures {
1031         match rx.recv() {
1032             Ok(()) => {},
1033             Err(_) => {
1034                 panicked = true;
1035             },
1036         }
1037         // Display any new diagnostics.
1038         diag_emitter.dump(sess.diagnostic());
1039     }
1040     if panicked {
1041         sess.fatal("aborting due to worker thread panic");
1042     }
1043 }
1044
1045 pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
1046     let (pname, mut cmd, _) = get_linker(sess);
1047
1048     cmd.arg("-c").arg("-o").arg(&outputs.path(OutputType::Object))
1049                            .arg(&outputs.temp_path(OutputType::Assembly, None));
1050     debug!("{:?}", cmd);
1051
1052     match cmd.output() {
1053         Ok(prog) => {
1054             if !prog.status.success() {
1055                 let mut note = prog.stderr.clone();
1056                 note.extend_from_slice(&prog.stdout);
1057
1058                 sess.struct_err(&format!("linking with `{}` failed: {}",
1059                                          pname,
1060                                          prog.status))
1061                     .note(&format!("{:?}", &cmd))
1062                     .note(str::from_utf8(&note[..]).unwrap())
1063                     .emit();
1064                 sess.abort_if_errors();
1065             }
1066         },
1067         Err(e) => {
1068             sess.err(&format!("could not exec the linker `{}`: {}", pname, e));
1069             sess.abort_if_errors();
1070         }
1071     }
1072 }
1073
1074 pub unsafe fn with_llvm_pmb(llmod: ModuleRef,
1075                             config: &ModuleConfig,
1076                             f: &mut FnMut(llvm::PassManagerBuilderRef)) {
1077     // Create the PassManagerBuilder for LLVM. We configure it with
1078     // reasonable defaults and prepare it to actually populate the pass
1079     // manager.
1080     let builder = llvm::LLVMPassManagerBuilderCreate();
1081     let opt_level = config.opt_level.unwrap_or(llvm::CodeGenLevelNone);
1082     let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
1083     let inline_threshold = config.inline_threshold;
1084
1085     llvm::LLVMRustConfigurePassManagerBuilder(builder, opt_level,
1086                                               config.merge_functions,
1087                                               config.vectorize_slp,
1088                                               config.vectorize_loop);
1089     llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
1090
1091     if opt_size != llvm::CodeGenOptSizeNone {
1092         llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
1093     }
1094
1095     llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
1096
1097     // Here we match what clang does (kinda). For O0 we only inline
1098     // always-inline functions (but don't add lifetime intrinsics), at O1 we
1099     // inline with lifetime intrinsics, and O2+ we add an inliner with a
1100     // thresholds copied from clang.
1101     match (opt_level, opt_size, inline_threshold) {
1102         (_, _, Some(t)) => {
1103             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
1104         }
1105         (llvm::CodeGenLevelAggressive, _, _) => {
1106             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
1107         }
1108         (_, llvm::CodeGenOptSizeDefault, _) => {
1109             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
1110         }
1111         (_, llvm::CodeGenOptSizeAggressive, _) => {
1112             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
1113         }
1114         (llvm::CodeGenLevelNone, _, _) => {
1115             llvm::LLVMRustAddAlwaysInlinePass(builder, false);
1116         }
1117         (llvm::CodeGenLevelLess, _, _) => {
1118             llvm::LLVMRustAddAlwaysInlinePass(builder, true);
1119         }
1120         (llvm::CodeGenLevelDefault, _, _) => {
1121             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1122         }
1123     }
1124
1125     f(builder);
1126     llvm::LLVMPassManagerBuilderDispose(builder);
1127 }