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