blob: e0ba6d569cc031cf7cabc5e82f85c3876635d1de [file] [log] [blame]
Akos Kiss6e5fb8b2014-12-12 23:39:271// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
Stuart Pernsteinere29aa142014-08-11 17:33:582// 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
11use back::lto;
Stuart Pernsteinercf672852014-07-17 17:52:5212use back::link::{get_cc_prog, remove};
Niko Matsakise135fa52014-11-27 12:21:2613use session::config::{OutputFilenames, NoDebugInfo, Passes, SomePasses, AllPasses};
Niko Matsakisdc6e4142014-11-16 01:30:3314use session::Session;
15use session::config;
Stuart Pernsteinere29aa142014-08-11 17:33:5816use llvm;
Keegan McAllisterad9a1da2014-09-12 15:17:5817use llvm::{ModuleRef, TargetMachineRef, PassManagerRef, DiagnosticInfoRef, ContextRef};
Keegan McAllister9d60de92014-09-27 08:33:3618use llvm::SMDiagnosticRef;
Niko Matsakise135fa52014-11-27 12:21:2619use trans::{CrateTranslation, ModuleTranslation};
Stuart Pernsteinere29aa142014-08-11 17:33:5820use util::common::time;
Stuart Pernsteinercf672852014-07-17 17:52:5221use syntax::codemap;
22use syntax::diagnostic;
23use syntax::diagnostic::{Emitter, Handler, Level, mk_handler};
Stuart Pernsteinere29aa142014-08-11 17:33:5824
Alex Crichton4b359e32015-01-06 03:13:3825use std::ffi::{self, CString};
Stuart Pernsteinere29aa142014-08-11 17:33:5826use std::io::Command;
Stuart Pernsteinercf672852014-07-17 17:52:5227use std::io::fs;
28use std::iter::Unfold;
Stuart Pernsteinere29aa142014-08-11 17:33:5829use std::ptr;
30use std::str;
Keegan McAllisterad9a1da2014-09-12 15:17:5831use std::mem;
Stuart Pernsteinercf672852014-07-17 17:52:5232use std::sync::{Arc, Mutex};
Alex Crichtonbc83a002014-12-23 19:53:3533use std::sync::mpsc::channel;
Aaron Turon43ae4b32014-12-07 02:34:3734use std::thread;
Alex Crichton4b359e32015-01-06 03:13:3835use libc::{self, c_uint, c_int, c_void};
Stuart Pernsteinere29aa142014-08-11 17:33:5836
Jorge Aparicio351409a2015-01-04 03:54:1837#[derive(Clone, Copy, PartialEq, PartialOrd, Ord, Eq)]
Niko Matsakis096a2862014-12-06 01:01:3338pub enum OutputType {
39 OutputTypeBitcode,
40 OutputTypeAssembly,
41 OutputTypeLlvmAssembly,
42 OutputTypeObject,
43 OutputTypeExe,
44}
45
Stuart Pernsteinercf672852014-07-17 17:52:5246pub fn llvm_err(handler: &diagnostic::Handler, msg: String) -> ! {
Stuart Pernsteinere29aa142014-08-11 17:33:5847 unsafe {
48 let cstr = llvm::LLVMRustGetLastError();
49 if cstr == ptr::null() {
Jorge Aparicio517f1cc2015-01-07 16:58:3150 handler.fatal(&msg[]);
Stuart Pernsteinere29aa142014-08-11 17:33:5851 } else {
Alex Crichtonec7a50d2014-11-25 21:28:3552 let err = ffi::c_str_to_bytes(&cstr);
53 let err = String::from_utf8_lossy(err.as_slice()).to_string();
54 libc::free(cstr as *mut _);
Jorge Aparicio517f1cc2015-01-07 16:58:3155 handler.fatal(&format!("{}: {}",
56 &msg[],
57 &err[])[]);
Stuart Pernsteinere29aa142014-08-11 17:33:5858 }
59 }
60}
61
62pub fn write_output_file(
Stuart Pernsteinercf672852014-07-17 17:52:5263 handler: &diagnostic::Handler,
Stuart Pernsteinere29aa142014-08-11 17:33:5864 target: llvm::TargetMachineRef,
65 pm: llvm::PassManagerRef,
66 m: ModuleRef,
67 output: &Path,
68 file_type: llvm::FileType) {
69 unsafe {
Alex Crichtonec7a50d2014-11-25 21:28:3570 let output = CString::from_slice(output.as_vec());
71 let result = llvm::LLVMRustWriteOutputFile(
72 target, pm, m, output.as_ptr(), file_type);
73 if !result {
74 llvm_err(handler, "could not write output".to_string());
75 }
Stuart Pernsteinere29aa142014-08-11 17:33:5876 }
77}
78
79
Stuart Pernsteinercf672852014-07-17 17:52:5280struct 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
Steve Klabnik7828c3d2014-10-09 19:17:2288// if the child task panics (for example, when `fatal` is called).
Jorge Aparicio351409a2015-01-04 03:54:1889#[derive(Clone)]
Stuart Pernsteinercf672852014-07-17 17:52:5290struct SharedEmitter {
91 buffer: Arc<Mutex<Vec<Diagnostic>>>,
92}
93
94impl 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) {
Alex Crichton76e5ed62014-12-09 04:20:03102 let mut buffer = self.buffer.lock().unwrap();
Stuart Pernsteinercf672852014-07-17 17:52:52103 for diag in buffer.iter() {
104 match diag.code {
105 Some(ref code) => {
106 handler.emit_with_code(None,
Jorge Aparicio517f1cc2015-01-07 16:58:31107 &diag.msg[],
108 &code[],
Stuart Pernsteinercf672852014-07-17 17:52:52109 diag.lvl);
110 },
111 None => {
112 handler.emit(None,
Jorge Aparicio517f1cc2015-01-07 16:58:31113 &diag.msg[],
Stuart Pernsteinercf672852014-07-17 17:52:52114 diag.lvl);
115 },
116 }
117 }
118 buffer.clear();
119 }
120}
121
122impl 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
Alex Crichton76e5ed62014-12-09 04:20:03127 self.buffer.lock().unwrap().push(Diagnostic {
Stuart Pernsteinercf672852014-07-17 17:52:52128 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) {
Steve Klabnik7828c3d2014-10-09 19:17:22136 panic!("SharedEmitter doesn't support custom_emit");
Stuart Pernsteinercf672852014-07-17 17:52:52137 }
138}
139
140
Stuart Pernsteinere29aa142014-08-11 17:33:58141// 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
Corey Richardson6b130e32014-07-23 18:56:36153fn target_feature(sess: &Session) -> String {
154 format!("{},{}", sess.target.target.options.features, sess.opts.cg.target_feature)
Stuart Pernsteinere29aa142014-08-11 17:33:58155}
156
Stuart Pernsteinercf672852014-07-17 17:52:52157fn 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}
Stuart Pernsteinere29aa142014-08-11 17:33:58165
Stuart Pernsteinercf672852014-07-17 17:52:52166fn create_target_machine(sess: &Session) -> TargetMachineRef {
Corey Richardson6b130e32014-07-23 18:56:36167 let reloc_model_arg = match sess.opts.cg.relocation_model {
Jorge Aparicio517f1cc2015-01-07 16:58:31168 Some(ref s) => &s[],
169 None => &sess.target.target.options.relocation_model[]
Corey Richardson6b130e32014-07-23 18:56:36170 };
171 let reloc_model = match reloc_model_arg {
Stuart Pernsteinercf672852014-07-17 17:52:52172 "pic" => llvm::RelocPIC,
173 "static" => llvm::RelocStatic,
174 "default" => llvm::RelocDefault,
175 "dynamic-no-pic" => llvm::RelocDynamicNoPic,
176 _ => {
Jorge Aparicio517f1cc2015-01-07 16:58:31177 sess.err(&format!("{:?} is not a valid relocation mode",
Stuart Pernsteinercf672852014-07-17 17:52:52178 sess.opts
179 .cg
Jorge Aparicio517f1cc2015-01-07 16:58:31180 .relocation_model)[]);
Stuart Pernsteinercf672852014-07-17 17:52:52181 sess.abort_if_errors();
182 unreachable!();
Stuart Pernsteinere29aa142014-08-11 17:33:58183 }
Stuart Pernsteinercf672852014-07-17 17:52:52184 };
Stuart Pernsteinere29aa142014-08-11 17:33:58185
Stuart Pernsteinercf672852014-07-17 17:52:52186 let opt_level = get_llvm_opt_level(sess.opts.optimize);
187 let use_softfp = sess.opts.cg.soft_float;
Stuart Pernsteinere29aa142014-08-11 17:33:58188
Stuart Pernsteinercf672852014-07-17 17:52:52189 // FIXME: #11906: Omitting frame pointers breaks retrieving the value of a parameter.
Stuart Pernsteinercf672852014-07-17 17:52:52190 let no_fp_elim = (sess.opts.debuginfo != NoDebugInfo) ||
Corey Richardson6b130e32014-07-23 18:56:36191 !sess.target.target.options.eliminate_frame_pointer;
Stuart Pernsteinere29aa142014-08-11 17:33:58192
Daniel Micay4deb4bc2014-08-09 16:43:45193 let any_library = sess.crate_types.borrow().iter().any(|ty| {
194 *ty != config::CrateTypeExecutable
195 });
196
Corey Richardson6b130e32014-07-23 18:56:36197 let ffunction_sections = sess.target.target.options.function_sections;
Stuart Pernsteinercf672852014-07-17 17:52:52198 let fdata_sections = ffunction_sections;
Stuart Pernsteinere29aa142014-08-11 17:33:58199
Corey Richardson6b130e32014-07-23 18:56:36200 let code_model_arg = match sess.opts.cg.code_model {
Jorge Aparicio517f1cc2015-01-07 16:58:31201 Some(ref s) => &s[],
202 None => &sess.target.target.options.code_model[]
Corey Richardson6b130e32014-07-23 18:56:36203 };
204
205 let code_model = match code_model_arg {
Stuart Pernsteinercf672852014-07-17 17:52:52206 "default" => llvm::CodeModelDefault,
207 "small" => llvm::CodeModelSmall,
208 "kernel" => llvm::CodeModelKernel,
209 "medium" => llvm::CodeModelMedium,
210 "large" => llvm::CodeModelLarge,
211 _ => {
Jorge Aparicio517f1cc2015-01-07 16:58:31212 sess.err(&format!("{:?} is not a valid code model",
Stuart Pernsteinercf672852014-07-17 17:52:52213 sess.opts
214 .cg
Jorge Aparicio517f1cc2015-01-07 16:58:31215 .code_model)[]);
Stuart Pernsteinercf672852014-07-17 17:52:52216 sess.abort_if_errors();
217 unreachable!();
218 }
219 };
Stuart Pernsteinere29aa142014-08-11 17:33:58220
Jorge Aparicio517f1cc2015-01-07 16:58:31221 let triple = &sess.target.target.llvm_target[];
Richo Healey89e8caa2014-10-29 01:58:46222
223 let tm = unsafe {
Alex Crichtonec7a50d2014-11-25 21:28:35224 let triple = CString::from_slice(triple.as_bytes());
225 let cpu = match sess.opts.cg.target_cpu {
226 Some(ref s) => s.as_slice(),
227 None => sess.target.target.options.cpu.as_slice()
228 };
229 let cpu = CString::from_slice(cpu.as_bytes());
230 let features = CString::from_slice(target_feature(sess).as_bytes());
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 )
Richo Healey89e8caa2014-10-29 01:58:46243 };
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 };
Stuart Pernsteinercf672852014-07-17 17:52:52252}
Stuart Pernsteinere29aa142014-08-11 17:33:58253
Stuart Pernsteinere29aa142014-08-11 17:33:58254
Stuart Pernsteinercf672852014-07-17 17:52:52255/// Module-specific configuration for `optimize_and_codegen`.
Jorge Aparicio351409a2015-01-04 03:54:18256#[derive(Clone)]
Stuart Pernsteinercf672852014-07-17 17:52:52257struct 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>,
Stuart Pernsteinere29aa142014-08-11 17:33:58265
Stuart Pernsteinercf672852014-07-17 17:52:52266 // 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
Flavio Percocof436f9c2014-12-21 23:49:42282unsafe impl Send for ModuleConfig { }
Flavio Percocofb803a82014-12-06 16:39:25283
Stuart Pernsteinercf672852014-07-17 17:52:52284impl 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,
Stuart Pernsteinere29aa142014-08-11 17:33:58302 }
Stuart Pernsteinercf672852014-07-17 17:52:52303 }
Stuart Pernsteinere29aa142014-08-11 17:33:58304
Stuart Pernsteinercf672852014-07-17 17:52:52305 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)
314struct 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,
Keegan McAllisterad9a1da2014-09-12 15:17:58320 // LLVM optimizations for which we want to print remarks.
321 remark: Passes,
Stuart Pernsteinercf672852014-07-17 17:52:52322}
323
324impl<'a> CodegenContext<'a> {
Stuart Pernsteinercf672852014-07-17 17:52:52325 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(),
Keegan McAllisterad9a1da2014-09-12 15:17:58329 remark: sess.opts.cg.remark.clone(),
Stuart Pernsteinere29aa142014-08-11 17:33:58330 }
Stuart Pernsteinercf672852014-07-17 17:52:52331 }
332}
Stuart Pernsteinere29aa142014-08-11 17:33:58333
Keegan McAllister9d60de92014-09-27 08:33:36334struct HandlerFreeVars<'a> {
Keegan McAllisterad9a1da2014-09-12 15:17:58335 llcx: ContextRef,
336 cgcx: &'a CodegenContext<'a>,
337}
338
Keegan McAllister9d60de92014-09-27 08:33:36339unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
340 user: *const c_void,
341 cookie: c_uint) {
342 use syntax::codemap::ExpnId;
343
344 let HandlerFreeVars { cgcx, .. }
345 = *mem::transmute::<_, *const HandlerFreeVars>(user);
346
347 let msg = llvm::build_string(|s| llvm::LLVMWriteSMDiagnosticToString(diag, s))
348 .expect("non-UTF8 SMDiagnostic");
349
350 match cgcx.lto_ctxt {
351 Some((sess, _)) => {
Keegan McAllister8826fdf2014-09-28 16:25:48352 sess.codemap().with_expn_info(ExpnId::from_llvm_cookie(cookie), |info| match info {
Jorge Aparicio517f1cc2015-01-07 16:58:31353 Some(ei) => sess.span_err(ei.call_site, &msg[]),
354 None => sess.err(&msg[]),
Keegan McAllister9d60de92014-09-27 08:33:36355 });
356 }
357
358 None => {
Jorge Aparicio517f1cc2015-01-07 16:58:31359 cgcx.handler.err(&msg[]);
Keegan McAllister9d60de92014-09-27 08:33:36360 cgcx.handler.note("build without -C codegen-units for more exact errors");
361 }
362 }
363}
364
Keegan McAllisterad9a1da2014-09-12 15:17:58365unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
Keegan McAllister9d60de92014-09-27 08:33:36366 let HandlerFreeVars { llcx, cgcx }
367 = *mem::transmute::<_, *const HandlerFreeVars>(user);
Keegan McAllisterad9a1da2014-09-12 15:17:58368
369 match llvm::diagnostic::Diagnostic::unpack(info) {
370 llvm::diagnostic::Optimization(opt) => {
Alex Crichtonec7a50d2014-11-25 21:28:35371 let pass_name = str::from_utf8(ffi::c_str_to_bytes(&opt.pass_name))
372 .ok()
373 .expect("got a non-UTF8 pass name from LLVM");
Keegan McAllisterad9a1da2014-09-12 15:17:58374 let enabled = match cgcx.remark {
375 AllPasses => true,
Jorge Aparicio8bb5ef92014-11-27 19:10:25376 SomePasses(ref v) => v.iter().any(|s| *s == pass_name),
Keegan McAllisterad9a1da2014-09-12 15:17:58377 };
378
379 if enabled {
380 let loc = llvm::debug_loc_to_string(llcx, opt.debug_loc);
Alex Crichton4af34942014-11-17 19:29:38381 cgcx.handler.note(format!("optimization {} for {} at {}: {}",
Keegan McAllisterad9a1da2014-09-12 15:17:58382 opt.kind.describe(),
383 pass_name,
Nick Cameron0c7f7a52015-01-04 04:43:24384 if loc.is_empty() { "[unknown]" } else { loc.as_slice() },
385 llvm::twine_to_string(opt.message)).as_slice());
Keegan McAllisterad9a1da2014-09-12 15:17:58386 }
387 }
388
389 _ => (),
390 }
391}
392
Stuart Pernsteinercf672852014-07-17 17:52:52393// Unsafe due to LLVM calls.
394unsafe fn optimize_and_codegen(cgcx: &CodegenContext,
395 mtrans: ModuleTranslation,
396 config: ModuleConfig,
397 name_extra: String,
398 output_names: OutputFilenames) {
399 let ModuleTranslation { llmod, llcx } = mtrans;
400 let tm = config.tm;
Stuart Pernsteinere29aa142014-08-11 17:33:58401
Keegan McAllisterad9a1da2014-09-12 15:17:58402 // llcx doesn't outlive this function, so we can put this on the stack.
Keegan McAllister9d60de92014-09-27 08:33:36403 let fv = HandlerFreeVars {
Keegan McAllisterad9a1da2014-09-12 15:17:58404 llcx: llcx,
405 cgcx: cgcx,
406 };
Keegan McAllister9d60de92014-09-27 08:33:36407 let fv = &fv as *const HandlerFreeVars as *mut c_void;
408
409 llvm::LLVMSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, fv);
410
Keegan McAllisterad9a1da2014-09-12 15:17:58411 if !cgcx.remark.is_empty() {
Keegan McAllister9d60de92014-09-27 08:33:36412 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, fv);
Keegan McAllisterad9a1da2014-09-12 15:17:58413 }
414
Stuart Pernsteinercf672852014-07-17 17:52:52415 if config.emit_no_opt_bc {
416 let ext = format!("{}.no-opt.bc", name_extra);
Alex Crichtonec7a50d2014-11-25 21:28:35417 let out = output_names.with_extension(ext.as_slice());
418 let out = CString::from_slice(out.as_vec());
419 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
Stuart Pernsteinercf672852014-07-17 17:52:52420 }
421
422 match config.opt_level {
423 Some(opt_level) => {
424 // Create the two optimizing pass managers. These mirror what clang
425 // does, and are by populated by LLVM's default PassManagerBuilder.
426 // Each manager has a different set of passes, but they also share
427 // some common passes.
428 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
429 let mpm = llvm::LLVMCreatePassManager();
430
431 // If we're verifying or linting, add them to the function pass
432 // manager.
Jorge Aparicioe47035b2014-12-31 01:58:47433 let addpass = |&: pass: &str| {
Alex Crichtonec7a50d2014-11-25 21:28:35434 let pass = CString::from_slice(pass.as_bytes());
435 llvm::LLVMRustAddPass(fpm, pass.as_ptr())
Stuart Pernsteinercf672852014-07-17 17:52:52436 };
437 if !config.no_verify { assert!(addpass("verify")); }
438
439 if !config.no_prepopulate_passes {
440 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
441 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
442 populate_llvm_passes(fpm, mpm, llmod, opt_level,
443 config.no_builtins);
444 }
445
446 for pass in config.passes.iter() {
Alex Crichtonec7a50d2014-11-25 21:28:35447 let pass = CString::from_slice(pass.as_bytes());
448 if !llvm::LLVMRustAddPass(mpm, pass.as_ptr()) {
Alex Crichtona6400082015-01-07 00:16:35449 cgcx.handler.warn(format!("unknown pass {:?}, ignoring",
Alex Crichtonec7a50d2014-11-25 21:28:35450 pass).as_slice());
451 }
Stuart Pernsteinere29aa142014-08-11 17:33:58452 }
Stuart Pernsteinere29aa142014-08-11 17:33:58453
Stuart Pernsteinercf672852014-07-17 17:52:52454 // Finally, run the actual optimization passes
455 time(config.time_passes, "llvm function passes", (), |()|
456 llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
457 time(config.time_passes, "llvm module passes", (), |()|
458 llvm::LLVMRunPassManager(mpm, llmod));
Stuart Pernsteinere29aa142014-08-11 17:33:58459
Stuart Pernsteinercf672852014-07-17 17:52:52460 // Deallocate managers that we're now done with
461 llvm::LLVMDisposePassManager(fpm);
462 llvm::LLVMDisposePassManager(mpm);
463
464 match cgcx.lto_ctxt {
465 Some((sess, reachable)) if sess.lto() => {
466 time(sess.time_passes(), "all lto passes", (), |()|
467 lto::run(sess, llmod, tm, reachable));
468
469 if config.emit_lto_bc {
470 let name = format!("{}.lto.bc", name_extra);
Alex Crichtonec7a50d2014-11-25 21:28:35471 let out = output_names.with_extension(name.as_slice());
472 let out = CString::from_slice(out.as_vec());
473 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
Stuart Pernsteinercf672852014-07-17 17:52:52474 }
475 },
476 _ => {},
477 }
478 },
479 None => {},
480 }
481
482 // A codegen-specific pass manager is used to generate object
483 // files for an LLVM module.
484 //
485 // Apparently each of these pass managers is a one-shot kind of
486 // thing, so we create a new one for each type of output. The
487 // pass manager passed to the closure should be ensured to not
488 // escape the closure itself, and the manager should only be
489 // used once.
Jorge Aparicio0676c3b2014-12-09 18:44:51490 unsafe fn with_codegen<F>(tm: TargetMachineRef,
491 llmod: ModuleRef,
492 no_builtins: bool,
493 f: F) where
494 F: FnOnce(PassManagerRef),
495 {
Stuart Pernsteinercf672852014-07-17 17:52:52496 let cpm = llvm::LLVMCreatePassManager();
497 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
498 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
499 f(cpm);
500 llvm::LLVMDisposePassManager(cpm);
501 }
502
503 if config.emit_bc {
504 let ext = format!("{}.bc", name_extra);
Alex Crichtonec7a50d2014-11-25 21:28:35505 let out = output_names.with_extension(ext.as_slice());
506 let out = CString::from_slice(out.as_vec());
507 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
Stuart Pernsteinercf672852014-07-17 17:52:52508 }
509
510 time(config.time_passes, "codegen passes", (), |()| {
511 if config.emit_ir {
512 let ext = format!("{}.ll", name_extra);
Alex Crichtonec7a50d2014-11-25 21:28:35513 let out = output_names.with_extension(ext.as_slice());
514 let out = CString::from_slice(out.as_vec());
515 with_codegen(tm, llmod, config.no_builtins, |cpm| {
516 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr());
Stuart Pernsteinercf672852014-07-17 17:52:52517 })
518 }
519
520 if config.emit_asm {
Jorge Aparicio517f1cc2015-01-07 16:58:31521 let path = output_names.with_extension(&format!("{}.s", name_extra)[]);
Stuart Pernsteinercf672852014-07-17 17:52:52522 with_codegen(tm, llmod, config.no_builtins, |cpm| {
Nick Cameronce0907e2014-09-11 05:07:49523 write_output_file(cgcx.handler, tm, cpm, llmod, &path, llvm::AssemblyFileType);
Stuart Pernsteinercf672852014-07-17 17:52:52524 });
525 }
526
527 if config.emit_obj {
Jorge Aparicio517f1cc2015-01-07 16:58:31528 let path = output_names.with_extension(&format!("{}.o", name_extra)[]);
Stuart Pernsteinercf672852014-07-17 17:52:52529 with_codegen(tm, llmod, config.no_builtins, |cpm| {
Nick Cameronce0907e2014-09-11 05:07:49530 write_output_file(cgcx.handler, tm, cpm, llmod, &path, llvm::ObjectFileType);
Stuart Pernsteinercf672852014-07-17 17:52:52531 });
532 }
533 });
534
535 llvm::LLVMDisposeModule(llmod);
536 llvm::LLVMContextDispose(llcx);
537 llvm::LLVMRustDisposeTargetMachine(tm);
538}
539
540pub fn run_passes(sess: &Session,
541 trans: &CrateTranslation,
Niko Matsakisdc6e4142014-11-16 01:30:33542 output_types: &[config::OutputType],
Stuart Pernsteinercf672852014-07-17 17:52:52543 crate_output: &OutputFilenames) {
544 // It's possible that we have `codegen_units > 1` but only one item in
545 // `trans.modules`. We could theoretically proceed and do LTO in that
546 // case, but it would be confusing to have the validity of
547 // `-Z lto -C codegen-units=2` depend on details of the crate being
548 // compiled, so we complain regardless.
549 if sess.lto() && sess.opts.cg.codegen_units > 1 {
550 // This case is impossible to handle because LTO expects to be able
551 // to combine the entire crate and all its dependencies into a
552 // single compilation unit, but each codegen unit is in a separate
553 // LLVM context, so they can't easily be combined.
554 sess.fatal("can't perform LTO when using multiple codegen units");
555 }
556
Stuart Pernsteiner6d2d47b2014-09-05 21:30:36557 // Sanity check
558 assert!(trans.modules.len() == sess.opts.cg.codegen_units);
559
Stuart Pernsteinercf672852014-07-17 17:52:52560 unsafe {
561 configure_llvm(sess);
562 }
563
564 let tm = create_target_machine(sess);
565
566 // Figure out what we actually need to build.
567
568 let mut modules_config = ModuleConfig::new(tm, sess.opts.cg.passes.clone());
569 let mut metadata_config = ModuleConfig::new(tm, vec!());
570
571 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
572
573 // Save all versions of the bytecode if we're saving our temporaries.
574 if sess.opts.cg.save_temps {
575 modules_config.emit_no_opt_bc = true;
576 modules_config.emit_bc = true;
577 modules_config.emit_lto_bc = true;
578 metadata_config.emit_bc = true;
579 }
580
Stuart Pernsteinered476b02014-09-17 23:18:12581 // Emit bitcode files for the crate if we're emitting an rlib.
Stuart Pernsteinercf672852014-07-17 17:52:52582 // Whenever an rlib is created, the bitcode is inserted into the
583 // archive in order to allow LTO against it.
584 let needs_crate_bitcode =
585 sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
Niko Matsakisdc6e4142014-11-16 01:30:33586 sess.opts.output_types.contains(&config::OutputTypeExe);
Stuart Pernsteinercf672852014-07-17 17:52:52587 if needs_crate_bitcode {
588 modules_config.emit_bc = true;
589 }
590
591 for output_type in output_types.iter() {
592 match *output_type {
Niko Matsakisdc6e4142014-11-16 01:30:33593 config::OutputTypeBitcode => { modules_config.emit_bc = true; },
594 config::OutputTypeLlvmAssembly => { modules_config.emit_ir = true; },
595 config::OutputTypeAssembly => {
Stuart Pernsteinercf672852014-07-17 17:52:52596 modules_config.emit_asm = true;
597 // If we're not using the LLVM assembler, this function
598 // could be invoked specially with output_type_assembly, so
599 // in this case we still want the metadata object file.
Niko Matsakisdc6e4142014-11-16 01:30:33600 if !sess.opts.output_types.contains(&config::OutputTypeAssembly) {
Stuart Pernsteinercf672852014-07-17 17:52:52601 metadata_config.emit_obj = true;
Stuart Pernsteinere29aa142014-08-11 17:33:58602 }
Stuart Pernsteinercf672852014-07-17 17:52:52603 },
Niko Matsakisdc6e4142014-11-16 01:30:33604 config::OutputTypeObject => { modules_config.emit_obj = true; },
605 config::OutputTypeExe => {
Stuart Pernsteinercf672852014-07-17 17:52:52606 modules_config.emit_obj = true;
607 metadata_config.emit_obj = true;
608 },
Alex Crichton117984b2014-12-16 00:03:39609 config::OutputTypeDepInfo => {}
Stuart Pernsteinercf672852014-07-17 17:52:52610 }
611 }
612
613 modules_config.set_flags(sess, trans);
614 metadata_config.set_flags(sess, trans);
615
616
617 // Populate a buffer with a list of codegen tasks. Items are processed in
618 // LIFO order, just because it's a tiny bit simpler that way. (The order
619 // doesn't actually matter.)
620 let mut work_items = Vec::with_capacity(1 + trans.modules.len());
621
622 {
623 let work = build_work_item(sess,
624 trans.metadata_module,
625 metadata_config.clone(),
626 crate_output.clone(),
627 "metadata".to_string());
628 work_items.push(work);
629 }
630
631 for (index, mtrans) in trans.modules.iter().enumerate() {
632 let work = build_work_item(sess,
633 *mtrans,
634 modules_config.clone(),
635 crate_output.clone(),
636 format!("{}", index));
637 work_items.push(work);
638 }
639
640 // Process the work items, optionally using worker threads.
641 if sess.opts.cg.codegen_units == 1 {
Jorge Aparicio517f1cc2015-01-07 16:58:31642 run_work_singlethreaded(sess, &trans.reachable[], work_items);
Stuart Pernsteinercf672852014-07-17 17:52:52643 } else {
644 run_work_multithreaded(sess, work_items, sess.opts.cg.codegen_units);
Stuart Pernsteinercf672852014-07-17 17:52:52645 }
646
647 // All codegen is finished.
648 unsafe {
649 llvm::LLVMRustDisposeTargetMachine(tm);
650 }
651
652 // Produce final compile outputs.
653
Jorge Aparicioe47035b2014-12-31 01:58:47654 let copy_if_one_unit = |&: ext: &str, output_type: config::OutputType, keep_numbered: bool| {
Stuart Pernsteinercf672852014-07-17 17:52:52655 // Three cases:
656 if sess.opts.cg.codegen_units == 1 {
657 // 1) Only one codegen unit. In this case it's no difficulty
658 // to copy `foo.0.x` to `foo.x`.
659 fs::copy(&crate_output.with_extension(ext),
660 &crate_output.path(output_type)).unwrap();
Stuart Pernsteinered476b02014-09-17 23:18:12661 if !sess.opts.cg.save_temps && !keep_numbered {
Stuart Pernsteiner1b676fb2014-08-27 21:49:17662 // The user just wants `foo.x`, not `foo.0.x`.
663 remove(sess, &crate_output.with_extension(ext));
664 }
Stuart Pernsteinercf672852014-07-17 17:52:52665 } else {
666 if crate_output.single_output_file.is_some() {
667 // 2) Multiple codegen units, with `-o some_name`. We have
668 // no good solution for this case, so warn the user.
Jorge Aparicio517f1cc2015-01-07 16:58:31669 sess.warn(&format!("ignoring -o because multiple .{} files were produced",
670 ext)[]);
Stuart Pernsteinercf672852014-07-17 17:52:52671 } else {
672 // 3) Multiple codegen units, but no `-o some_name`. We
673 // just leave the `foo.0.x` files in place.
674 // (We don't have to do any work in this case.)
675 }
676 }
677 };
678
Jorge Aparicioe47035b2014-12-31 01:58:47679 let link_obj = |&: output_path: &Path| {
Stuart Pernsteiner6d2d47b2014-09-05 21:30:36680 // Running `ld -r` on a single input is kind of pointless.
681 if sess.opts.cg.codegen_units == 1 {
682 fs::copy(&crate_output.with_extension("0.o"),
683 output_path).unwrap();
684 // Leave the .0.o file around, to mimic the behavior of the normal
685 // code path.
686 return;
687 }
688
Stuart Pernsteiner4d9a4782014-08-29 19:46:04689 // Some builds of MinGW GCC will pass --force-exe-suffix to ld, which
690 // will automatically add a .exe extension if the extension is not
691 // already .exe or .dll. To ensure consistent behavior on Windows, we
692 // add the .exe suffix explicitly and then rename the output file to
693 // the desired path. This will give the correct behavior whether or
694 // not GCC adds --force-exe-suffix.
695 let windows_output_path =
Corey Richardson6b130e32014-07-23 18:56:36696 if sess.target.target.options.is_like_windows {
Stuart Pernsteiner4d9a4782014-08-29 19:46:04697 Some(output_path.with_extension("o.exe"))
698 } else {
699 None
700 };
701
Stuart Pernsteinerb5a0b702014-08-26 22:53:56702 let pname = get_cc_prog(sess);
Jorge Aparicio517f1cc2015-01-07 16:58:31703 let mut cmd = Command::new(&pname[]);
Stuart Pernsteinerb5a0b702014-08-26 22:53:56704
Jorge Aparicio517f1cc2015-01-07 16:58:31705 cmd.args(&sess.target.target.options.pre_link_args[]);
Stuart Pernsteinerb5a0b702014-08-26 22:53:56706 cmd.arg("-nostdlib");
Stuart Pernsteinercf672852014-07-17 17:52:52707
708 for index in range(0, trans.modules.len()) {
Jorge Aparicio517f1cc2015-01-07 16:58:31709 cmd.arg(crate_output.with_extension(&format!("{}.o", index)[]));
Stuart Pernsteinercf672852014-07-17 17:52:52710 }
711
Stuart Pernsteiner4d9a4782014-08-29 19:46:04712 cmd.arg("-r")
713 .arg("-o")
714 .arg(windows_output_path.as_ref().unwrap_or(output_path));
Stuart Pernsteinerb5a0b702014-08-26 22:53:56715
Jorge Aparicio517f1cc2015-01-07 16:58:31716 cmd.args(&sess.target.target.options.post_link_args[]);
Corey Richardson6b130e32014-07-23 18:56:36717
Stuart Pernsteinerb5a0b702014-08-26 22:53:56718 if (sess.opts.debugging_opts & config::PRINT_LINK_ARGS) != 0 {
719 println!("{}", &cmd);
720 }
721
Stuart Pernsteinercf672852014-07-17 17:52:52722 cmd.stdin(::std::io::process::Ignored)
723 .stdout(::std::io::process::InheritFd(1))
724 .stderr(::std::io::process::InheritFd(2));
Stuart Pernsteinerb5a0b702014-08-26 22:53:56725 match cmd.status() {
Markus Siemens53ac8522014-10-22 20:23:22726 Ok(status) => {
727 if !status.success() {
Jorge Aparicio517f1cc2015-01-07 16:58:31728 sess.err(&format!("linking of {} with `{}` failed",
729 output_path.display(), cmd)[]);
Markus Siemens53ac8522014-10-22 20:23:22730 sess.abort_if_errors();
731 }
732 },
Stuart Pernsteinerb5a0b702014-08-26 22:53:56733 Err(e) => {
Jorge Aparicio517f1cc2015-01-07 16:58:31734 sess.err(&format!("could not exec the linker `{}`: {}",
Stuart Pernsteinerb5a0b702014-08-26 22:53:56735 pname,
Jorge Aparicio517f1cc2015-01-07 16:58:31736 e)[]);
Stuart Pernsteinerb5a0b702014-08-26 22:53:56737 sess.abort_if_errors();
738 },
739 }
Stuart Pernsteiner4d9a4782014-08-29 19:46:04740
741 match windows_output_path {
742 Some(ref windows_path) => {
743 fs::rename(windows_path, output_path).unwrap();
744 },
745 None => {
746 // The file is already named according to `output_path`.
747 }
748 }
Stuart Pernsteinercf672852014-07-17 17:52:52749 };
750
751 // Flag to indicate whether the user explicitly requested bitcode.
752 // Otherwise, we produced it only as a temporary output, and will need
753 // to get rid of it.
Stuart Pernsteinered476b02014-09-17 23:18:12754 let mut user_wants_bitcode = false;
Stuart Pernsteinercf672852014-07-17 17:52:52755 for output_type in output_types.iter() {
756 match *output_type {
Niko Matsakisdc6e4142014-11-16 01:30:33757 config::OutputTypeBitcode => {
Stuart Pernsteinered476b02014-09-17 23:18:12758 user_wants_bitcode = true;
759 // Copy to .bc, but always keep the .0.bc. There is a later
760 // check to figure out if we should delete .0.bc files, or keep
761 // them for making an rlib.
Niko Matsakisdc6e4142014-11-16 01:30:33762 copy_if_one_unit("0.bc", config::OutputTypeBitcode, true);
763 }
764 config::OutputTypeLlvmAssembly => {
765 copy_if_one_unit("0.ll", config::OutputTypeLlvmAssembly, false);
766 }
767 config::OutputTypeAssembly => {
768 copy_if_one_unit("0.s", config::OutputTypeAssembly, false);
769 }
770 config::OutputTypeObject => {
771 link_obj(&crate_output.path(config::OutputTypeObject));
772 }
773 config::OutputTypeExe => {
774 // If config::OutputTypeObject is already in the list, then
775 // `crate.o` will be handled by the config::OutputTypeObject case.
Stuart Pernsteinercf672852014-07-17 17:52:52776 // Otherwise, we need to create the temporary object so we
777 // can run the linker.
Niko Matsakisdc6e4142014-11-16 01:30:33778 if !sess.opts.output_types.contains(&config::OutputTypeObject) {
779 link_obj(&crate_output.temp_path(config::OutputTypeObject));
Stuart Pernsteinere29aa142014-08-11 17:33:58780 }
Niko Matsakisdc6e4142014-11-16 01:30:33781 }
Alex Crichton117984b2014-12-16 00:03:39782 config::OutputTypeDepInfo => {}
Stuart Pernsteinercf672852014-07-17 17:52:52783 }
784 }
Stuart Pernsteinered476b02014-09-17 23:18:12785 let user_wants_bitcode = user_wants_bitcode;
Stuart Pernsteinercf672852014-07-17 17:52:52786
787 // Clean up unwanted temporary files.
788
789 // We create the following files by default:
790 // - crate.0.bc
791 // - crate.0.o
792 // - crate.metadata.bc
793 // - crate.metadata.o
794 // - crate.o (linked from crate.##.o)
Stuart Pernsteiner1b676fb2014-08-27 21:49:17795 // - crate.bc (copied from crate.0.bc)
Stuart Pernsteinercf672852014-07-17 17:52:52796 // We may create additional files if requested by the user (through
797 // `-C save-temps` or `--emit=` flags).
798
799 if !sess.opts.cg.save_temps {
800 // Remove the temporary .0.o objects. If the user didn't
Stuart Pernsteinered476b02014-09-17 23:18:12801 // explicitly request bitcode (with --emit=bc), and the bitcode is not
802 // needed for building an rlib, then we must remove .0.bc as well.
803
804 // Specific rules for keeping .0.bc:
805 // - If we're building an rlib (`needs_crate_bitcode`), then keep
806 // it.
807 // - If the user requested bitcode (`user_wants_bitcode`), and
808 // codegen_units > 1, then keep it.
809 // - If the user requested bitcode but codegen_units == 1, then we
810 // can toss .0.bc because we copied it to .bc earlier.
811 // - If we're not building an rlib and the user didn't request
812 // bitcode, then delete .0.bc.
813 // If you change how this works, also update back::link::link_rlib,
814 // where .0.bc files are (maybe) deleted after making an rlib.
815 let keep_numbered_bitcode = needs_crate_bitcode ||
816 (user_wants_bitcode && sess.opts.cg.codegen_units > 1);
817
Stuart Pernsteinercf672852014-07-17 17:52:52818 for i in range(0, trans.modules.len()) {
819 if modules_config.emit_obj {
820 let ext = format!("{}.o", i);
Jorge Aparicio517f1cc2015-01-07 16:58:31821 remove(sess, &crate_output.with_extension(&ext[]));
Stuart Pernsteinercf672852014-07-17 17:52:52822 }
823
Stuart Pernsteinered476b02014-09-17 23:18:12824 if modules_config.emit_bc && !keep_numbered_bitcode {
Stuart Pernsteinercf672852014-07-17 17:52:52825 let ext = format!("{}.bc", i);
Jorge Aparicio517f1cc2015-01-07 16:58:31826 remove(sess, &crate_output.with_extension(&ext[]));
Stuart Pernsteinere29aa142014-08-11 17:33:58827 }
828 }
829
Stuart Pernsteinered476b02014-09-17 23:18:12830 if metadata_config.emit_bc && !user_wants_bitcode {
Stuart Pernsteinercf672852014-07-17 17:52:52831 remove(sess, &crate_output.with_extension("metadata.bc"));
832 }
833 }
834
835 // We leave the following files around by default:
836 // - crate.o
837 // - crate.metadata.o
838 // - crate.bc
839 // These are used in linking steps and will be cleaned up afterward.
840
841 // FIXME: time_llvm_passes support - does this use a global context or
842 // something?
843 //if sess.time_llvm_passes() { llvm::LLVMRustPrintPassTimings(); }
844}
845
Niko Matsakis394f6842014-11-26 15:07:58846struct WorkItem {
847 mtrans: ModuleTranslation,
848 config: ModuleConfig,
849 output_names: OutputFilenames,
850 name_extra: String
851}
Stuart Pernsteinercf672852014-07-17 17:52:52852
853fn build_work_item(sess: &Session,
854 mtrans: ModuleTranslation,
855 config: ModuleConfig,
856 output_names: OutputFilenames,
Niko Matsakis394f6842014-11-26 15:07:58857 name_extra: String)
858 -> WorkItem
859{
Stuart Pernsteinercf672852014-07-17 17:52:52860 let mut config = config;
861 config.tm = create_target_machine(sess);
Niko Matsakis394f6842014-11-26 15:07:58862 WorkItem { mtrans: mtrans, config: config, output_names: output_names,
863 name_extra: name_extra }
864}
Stuart Pernsteinercf672852014-07-17 17:52:52865
Niko Matsakis394f6842014-11-26 15:07:58866fn execute_work_item(cgcx: &CodegenContext,
867 work_item: WorkItem) {
868 unsafe {
869 optimize_and_codegen(cgcx, work_item.mtrans, work_item.config,
870 work_item.name_extra, work_item.output_names);
Stuart Pernsteinercf672852014-07-17 17:52:52871 }
872}
873
874fn run_work_singlethreaded(sess: &Session,
875 reachable: &[String],
876 work_items: Vec<WorkItem>) {
877 let cgcx = CodegenContext::new_with_session(sess, reachable);
878 let mut work_items = work_items;
879
880 // Since we're running single-threaded, we can pass the session to
881 // the proc, allowing `optimize_and_codegen` to perform LTO.
882 for work in Unfold::new((), |_| work_items.pop()) {
Niko Matsakis394f6842014-11-26 15:07:58883 execute_work_item(&cgcx, work);
Stuart Pernsteinercf672852014-07-17 17:52:52884 }
885}
886
887fn run_work_multithreaded(sess: &Session,
888 work_items: Vec<WorkItem>,
889 num_workers: uint) {
890 // Run some workers to process the work items.
891 let work_items_arc = Arc::new(Mutex::new(work_items));
892 let mut diag_emitter = SharedEmitter::new();
893 let mut futures = Vec::with_capacity(num_workers);
894
895 for i in range(0, num_workers) {
896 let work_items_arc = work_items_arc.clone();
897 let diag_emitter = diag_emitter.clone();
Keegan McAllisterad9a1da2014-09-12 15:17:58898 let remark = sess.opts.cg.remark.clone();
Stuart Pernsteinercf672852014-07-17 17:52:52899
Aaron Turon43ae4b32014-12-07 02:34:37900 let (tx, rx) = channel();
901 let mut tx = Some(tx);
902 futures.push(rx);
903
Aaron Turona27fbac2014-12-14 08:05:32904 thread::Builder::new().name(format!("codegen-{}", i)).spawn(move |:| {
Stuart Pernsteinercf672852014-07-17 17:52:52905 let diag_handler = mk_handler(box diag_emitter);
906
907 // Must construct cgcx inside the proc because it has non-Send
908 // fields.
Keegan McAllisterad9a1da2014-09-12 15:17:58909 let cgcx = CodegenContext {
910 lto_ctxt: None,
911 handler: &diag_handler,
912 remark: remark,
913 };
Stuart Pernsteinercf672852014-07-17 17:52:52914
915 loop {
916 // Avoid holding the lock for the entire duration of the match.
Alex Crichton76e5ed62014-12-09 04:20:03917 let maybe_work = work_items_arc.lock().unwrap().pop();
Stuart Pernsteinercf672852014-07-17 17:52:52918 match maybe_work {
919 Some(work) => {
Niko Matsakis394f6842014-11-26 15:07:58920 execute_work_item(&cgcx, work);
Stuart Pernsteinercf672852014-07-17 17:52:52921
922 // Make sure to fail the worker so the main thread can
923 // tell that there were errors.
924 cgcx.handler.abort_if_errors();
925 }
926 None => break,
Stuart Pernsteinere29aa142014-08-11 17:33:58927 }
Stuart Pernsteinere29aa142014-08-11 17:33:58928 }
Aaron Turon43ae4b32014-12-07 02:34:37929
Alex Crichtonbc83a002014-12-23 19:53:35930 tx.take().unwrap().send(()).unwrap();
Aaron Turoncaca9b22015-01-06 05:59:45931 });
Stuart Pernsteinercf672852014-07-17 17:52:52932 }
Stuart Pernsteinere29aa142014-08-11 17:33:58933
Steve Klabnik7828c3d2014-10-09 19:17:22934 let mut panicked = false;
Aaron Turon43ae4b32014-12-07 02:34:37935 for rx in futures.into_iter() {
Alex Crichtonbc83a002014-12-23 19:53:35936 match rx.recv() {
Stuart Pernsteinercf672852014-07-17 17:52:52937 Ok(()) => {},
938 Err(_) => {
Steve Klabnik7828c3d2014-10-09 19:17:22939 panicked = true;
Stuart Pernsteinercf672852014-07-17 17:52:52940 },
941 }
942 // Display any new diagnostics.
943 diag_emitter.dump(sess.diagnostic().handler());
944 }
Steve Klabnik7828c3d2014-10-09 19:17:22945 if panicked {
946 sess.fatal("aborting due to worker thread panic");
Stuart Pernsteinere29aa142014-08-11 17:33:58947 }
948}
949
950pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
951 let pname = get_cc_prog(sess);
Jorge Aparicio517f1cc2015-01-07 16:58:31952 let mut cmd = Command::new(&pname[]);
Stuart Pernsteinere29aa142014-08-11 17:33:58953
Niko Matsakisdc6e4142014-11-16 01:30:33954 cmd.arg("-c").arg("-o").arg(outputs.path(config::OutputTypeObject))
955 .arg(outputs.temp_path(config::OutputTypeAssembly));
Stuart Pernsteinere29aa142014-08-11 17:33:58956 debug!("{}", &cmd);
957
958 match cmd.output() {
959 Ok(prog) => {
960 if !prog.status.success() {
Jorge Aparicio517f1cc2015-01-07 16:58:31961 sess.err(&format!("linking with `{}` failed: {}",
Stuart Pernsteinere29aa142014-08-11 17:33:58962 pname,
Jorge Aparicio517f1cc2015-01-07 16:58:31963 prog.status)[]);
964 sess.note(&format!("{}", &cmd)[]);
Stuart Pernsteinere29aa142014-08-11 17:33:58965 let mut note = prog.error.clone();
Jorge Aparicio517f1cc2015-01-07 16:58:31966 note.push_all(&prog.output[]);
967 sess.note(str::from_utf8(&note[]).unwrap());
Stuart Pernsteinere29aa142014-08-11 17:33:58968 sess.abort_if_errors();
969 }
970 },
971 Err(e) => {
Jorge Aparicio517f1cc2015-01-07 16:58:31972 sess.err(&format!("could not exec the linker `{}`: {}",
Stuart Pernsteinere29aa142014-08-11 17:33:58973 pname,
Jorge Aparicio517f1cc2015-01-07 16:58:31974 e)[]);
Stuart Pernsteinere29aa142014-08-11 17:33:58975 sess.abort_if_errors();
976 }
977 }
978}
979
980unsafe fn configure_llvm(sess: &Session) {
981 use std::sync::{Once, ONCE_INIT};
Alex Crichtondae48a02014-10-11 04:59:10982 static INIT: Once = ONCE_INIT;
Stuart Pernsteinere29aa142014-08-11 17:33:58983
984 // Copy what clang does by turning on loop vectorization at O2 and
985 // slp vectorization at O3
986 let vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
987 (sess.opts.optimize == config::Default ||
988 sess.opts.optimize == config::Aggressive);
989 let vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
990 sess.opts.optimize == config::Aggressive;
991
992 let mut llvm_c_strs = Vec::new();
993 let mut llvm_args = Vec::new();
994 {
Jorge Aparicioe47035b2014-12-31 01:58:47995 let mut add = |&mut : arg: &str| {
Alex Crichtonec7a50d2014-11-25 21:28:35996 let s = CString::from_slice(arg.as_bytes());
Stuart Pernsteinere29aa142014-08-11 17:33:58997 llvm_args.push(s.as_ptr());
998 llvm_c_strs.push(s);
999 };
1000 add("rustc"); // fake program name
1001 if vectorize_loop { add("-vectorize-loops"); }
1002 if vectorize_slp { add("-vectorize-slp"); }
1003 if sess.time_llvm_passes() { add("-time-passes"); }
1004 if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
1005
1006 for arg in sess.opts.cg.llvm_args.iter() {
Jorge Aparicio517f1cc2015-01-07 16:58:311007 add(&(*arg)[]);
Stuart Pernsteinere29aa142014-08-11 17:33:581008 }
1009 }
1010
Alex Crichtonf3a7ec72014-12-29 23:03:011011 INIT.call_once(|| {
Stuart Pernsteinere29aa142014-08-11 17:33:581012 llvm::LLVMInitializePasses();
1013
1014 // Only initialize the platforms supported by Rust here, because
1015 // using --llvm-root will have multiple platforms that rustllvm
1016 // doesn't actually link to and it's pointless to put target info
1017 // into the registry that Rust cannot generate machine code for.
1018 llvm::LLVMInitializeX86TargetInfo();
1019 llvm::LLVMInitializeX86Target();
1020 llvm::LLVMInitializeX86TargetMC();
1021 llvm::LLVMInitializeX86AsmPrinter();
1022 llvm::LLVMInitializeX86AsmParser();
1023
1024 llvm::LLVMInitializeARMTargetInfo();
1025 llvm::LLVMInitializeARMTarget();
1026 llvm::LLVMInitializeARMTargetMC();
1027 llvm::LLVMInitializeARMAsmPrinter();
1028 llvm::LLVMInitializeARMAsmParser();
1029
Akos Kiss6e5fb8b2014-12-12 23:39:271030 llvm::LLVMInitializeAArch64TargetInfo();
1031 llvm::LLVMInitializeAArch64Target();
1032 llvm::LLVMInitializeAArch64TargetMC();
1033 llvm::LLVMInitializeAArch64AsmPrinter();
1034 llvm::LLVMInitializeAArch64AsmParser();
1035
Stuart Pernsteinere29aa142014-08-11 17:33:581036 llvm::LLVMInitializeMipsTargetInfo();
1037 llvm::LLVMInitializeMipsTarget();
1038 llvm::LLVMInitializeMipsTargetMC();
1039 llvm::LLVMInitializeMipsAsmPrinter();
1040 llvm::LLVMInitializeMipsAsmParser();
1041
1042 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
1043 llvm_args.as_ptr());
1044 });
1045}
1046
1047unsafe fn populate_llvm_passes(fpm: llvm::PassManagerRef,
1048 mpm: llvm::PassManagerRef,
1049 llmod: ModuleRef,
1050 opt: llvm::CodeGenOptLevel,
1051 no_builtins: bool) {
1052 // Create the PassManagerBuilder for LLVM. We configure it with
1053 // reasonable defaults and prepare it to actually populate the pass
1054 // manager.
1055 let builder = llvm::LLVMPassManagerBuilderCreate();
1056 match opt {
1057 llvm::CodeGenLevelNone => {
1058 // Don't add lifetime intrinsics at O0
1059 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
1060 }
1061 llvm::CodeGenLevelLess => {
1062 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
1063 }
1064 // numeric values copied from clang
1065 llvm::CodeGenLevelDefault => {
1066 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
1067 225);
1068 }
1069 llvm::CodeGenLevelAggressive => {
1070 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
1071 275);
1072 }
1073 }
1074 llvm::LLVMPassManagerBuilderSetOptLevel(builder, opt as c_uint);
1075 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, no_builtins);
1076
1077 // Use the builder to populate the function/module pass managers.
1078 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(builder, fpm);
1079 llvm::LLVMPassManagerBuilderPopulateModulePassManager(builder, mpm);
1080 llvm::LLVMPassManagerBuilderDispose(builder);
1081
1082 match opt {
1083 llvm::CodeGenLevelDefault | llvm::CodeGenLevelAggressive => {
Alex Crichtonec7a50d2014-11-25 21:28:351084 llvm::LLVMRustAddPass(mpm, "mergefunc\0".as_ptr() as *const _);
Stuart Pernsteinere29aa142014-08-11 17:33:581085 }
1086 _ => {}
1087 };
1088}