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