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