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