blob: 9b195486d5d68162aeec64708bdf67abf736eb7d [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};
Alex Crichton3a07f852015-01-23 00:31:0026use std::old_io::Command;
27use std::old_io::fs;
Stuart Pernsteinercf672852014-07-17 17:52:5228use 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 {
Stepan Koltsovfa012512015-01-18 00:32:1170 let output_c = CString::from_slice(output.as_vec());
Alex Crichtonec7a50d2014-11-25 21:28:3571 let result = llvm::LLVMRustWriteOutputFile(
Stepan Koltsovfa012512015-01-18 00:32:1172 target, pm, m, output_c.as_ptr(), file_type);
Alex Crichtonec7a50d2014-11-25 21:28:3573 if !result {
Stepan Koltsovfa012512015-01-18 00:32:1174 llvm_err(handler, format!("could not write output to {}", output.display()));
Alex Crichtonec7a50d2014-11-25 21:28:3575 }
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
John KÃ¥re Alsaker4cfb7002015-01-22 18:43:39339unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext<'a>,
340 msg: &'b str,
341 cookie: c_uint) {
342 use syntax::codemap::ExpnId;
343
344 match cgcx.lto_ctxt {
345 Some((sess, _)) => {
346 sess.codemap().with_expn_info(ExpnId::from_llvm_cookie(cookie), |info| match info {
347 Some(ei) => sess.span_err(ei.call_site, msg),
348 None => sess.err(msg),
349 });
350 }
351
352 None => {
353 cgcx.handler.err(msg);
354 cgcx.handler.note("build without -C codegen-units for more exact errors");
355 }
356 }
357}
358
Keegan McAllister9d60de92014-09-27 08:33:36359unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
360 user: *const c_void,
361 cookie: c_uint) {
Keegan McAllister9d60de92014-09-27 08:33:36362 let HandlerFreeVars { cgcx, .. }
363 = *mem::transmute::<_, *const HandlerFreeVars>(user);
364
365 let msg = llvm::build_string(|s| llvm::LLVMWriteSMDiagnosticToString(diag, s))
366 .expect("non-UTF8 SMDiagnostic");
367
John KÃ¥re Alsaker4cfb7002015-01-22 18:43:39368 report_inline_asm(cgcx, &msg[], cookie);
Keegan McAllister9d60de92014-09-27 08:33:36369}
370
Keegan McAllisterad9a1da2014-09-12 15:17:58371unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
Keegan McAllister9d60de92014-09-27 08:33:36372 let HandlerFreeVars { llcx, cgcx }
373 = *mem::transmute::<_, *const HandlerFreeVars>(user);
Keegan McAllisterad9a1da2014-09-12 15:17:58374
375 match llvm::diagnostic::Diagnostic::unpack(info) {
John KÃ¥re Alsaker4cfb7002015-01-22 18:43:39376 llvm::diagnostic::InlineAsm(inline) => {
377 report_inline_asm(cgcx,
378 llvm::twine_to_string(inline.message).as_slice(),
379 inline.cookie);
380 }
381
Keegan McAllisterad9a1da2014-09-12 15:17:58382 llvm::diagnostic::Optimization(opt) => {
Alex Crichtonec7a50d2014-11-25 21:28:35383 let pass_name = str::from_utf8(ffi::c_str_to_bytes(&opt.pass_name))
384 .ok()
385 .expect("got a non-UTF8 pass name from LLVM");
Keegan McAllisterad9a1da2014-09-12 15:17:58386 let enabled = match cgcx.remark {
387 AllPasses => true,
Jorge Aparicio8bb5ef92014-11-27 19:10:25388 SomePasses(ref v) => v.iter().any(|s| *s == pass_name),
Keegan McAllisterad9a1da2014-09-12 15:17:58389 };
390
391 if enabled {
392 let loc = llvm::debug_loc_to_string(llcx, opt.debug_loc);
Alex Crichton4af34942014-11-17 19:29:38393 cgcx.handler.note(format!("optimization {} for {} at {}: {}",
Keegan McAllisterad9a1da2014-09-12 15:17:58394 opt.kind.describe(),
395 pass_name,
Nick Cameron0c7f7a52015-01-04 04:43:24396 if loc.is_empty() { "[unknown]" } else { loc.as_slice() },
397 llvm::twine_to_string(opt.message)).as_slice());
Keegan McAllisterad9a1da2014-09-12 15:17:58398 }
399 }
400
401 _ => (),
402 }
403}
404
Stuart Pernsteinercf672852014-07-17 17:52:52405// Unsafe due to LLVM calls.
406unsafe fn optimize_and_codegen(cgcx: &CodegenContext,
407 mtrans: ModuleTranslation,
408 config: ModuleConfig,
409 name_extra: String,
410 output_names: OutputFilenames) {
411 let ModuleTranslation { llmod, llcx } = mtrans;
412 let tm = config.tm;
Stuart Pernsteinere29aa142014-08-11 17:33:58413
Keegan McAllisterad9a1da2014-09-12 15:17:58414 // llcx doesn't outlive this function, so we can put this on the stack.
Keegan McAllister9d60de92014-09-27 08:33:36415 let fv = HandlerFreeVars {
Keegan McAllisterad9a1da2014-09-12 15:17:58416 llcx: llcx,
417 cgcx: cgcx,
418 };
Keegan McAllister9d60de92014-09-27 08:33:36419 let fv = &fv as *const HandlerFreeVars as *mut c_void;
420
421 llvm::LLVMSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, fv);
John KÃ¥re Alsaker4cfb7002015-01-22 18:43:39422 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, fv);
Keegan McAllisterad9a1da2014-09-12 15:17:58423
Stuart Pernsteinercf672852014-07-17 17:52:52424 if config.emit_no_opt_bc {
425 let ext = format!("{}.no-opt.bc", name_extra);
Alex Crichtonec7a50d2014-11-25 21:28:35426 let out = output_names.with_extension(ext.as_slice());
427 let out = CString::from_slice(out.as_vec());
428 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
Stuart Pernsteinercf672852014-07-17 17:52:52429 }
430
431 match config.opt_level {
432 Some(opt_level) => {
433 // Create the two optimizing pass managers. These mirror what clang
434 // does, and are by populated by LLVM's default PassManagerBuilder.
435 // Each manager has a different set of passes, but they also share
436 // some common passes.
437 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
438 let mpm = llvm::LLVMCreatePassManager();
439
440 // If we're verifying or linting, add them to the function pass
441 // manager.
Jorge Aparicioe47035b2014-12-31 01:58:47442 let addpass = |&: pass: &str| {
Alex Crichtonec7a50d2014-11-25 21:28:35443 let pass = CString::from_slice(pass.as_bytes());
444 llvm::LLVMRustAddPass(fpm, pass.as_ptr())
Stuart Pernsteinercf672852014-07-17 17:52:52445 };
446 if !config.no_verify { assert!(addpass("verify")); }
447
448 if !config.no_prepopulate_passes {
449 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
450 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
451 populate_llvm_passes(fpm, mpm, llmod, opt_level,
452 config.no_builtins);
453 }
454
455 for pass in config.passes.iter() {
Alex Crichtonec7a50d2014-11-25 21:28:35456 let pass = CString::from_slice(pass.as_bytes());
457 if !llvm::LLVMRustAddPass(mpm, pass.as_ptr()) {
Alex Crichtona6400082015-01-07 00:16:35458 cgcx.handler.warn(format!("unknown pass {:?}, ignoring",
Alex Crichtonec7a50d2014-11-25 21:28:35459 pass).as_slice());
460 }
Stuart Pernsteinere29aa142014-08-11 17:33:58461 }
Stuart Pernsteinere29aa142014-08-11 17:33:58462
Stuart Pernsteinercf672852014-07-17 17:52:52463 // Finally, run the actual optimization passes
464 time(config.time_passes, "llvm function passes", (), |()|
465 llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
466 time(config.time_passes, "llvm module passes", (), |()|
467 llvm::LLVMRunPassManager(mpm, llmod));
Stuart Pernsteinere29aa142014-08-11 17:33:58468
Stuart Pernsteinercf672852014-07-17 17:52:52469 // Deallocate managers that we're now done with
470 llvm::LLVMDisposePassManager(fpm);
471 llvm::LLVMDisposePassManager(mpm);
472
473 match cgcx.lto_ctxt {
474 Some((sess, reachable)) if sess.lto() => {
475 time(sess.time_passes(), "all lto passes", (), |()|
476 lto::run(sess, llmod, tm, reachable));
477
478 if config.emit_lto_bc {
479 let name = format!("{}.lto.bc", name_extra);
Alex Crichtonec7a50d2014-11-25 21:28:35480 let out = output_names.with_extension(name.as_slice());
481 let out = CString::from_slice(out.as_vec());
482 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
Stuart Pernsteinercf672852014-07-17 17:52:52483 }
484 },
485 _ => {},
486 }
487 },
488 None => {},
489 }
490
491 // A codegen-specific pass manager is used to generate object
492 // files for an LLVM module.
493 //
494 // Apparently each of these pass managers is a one-shot kind of
495 // thing, so we create a new one for each type of output. The
496 // pass manager passed to the closure should be ensured to not
497 // escape the closure itself, and the manager should only be
498 // used once.
Jorge Aparicio0676c3b2014-12-09 18:44:51499 unsafe fn with_codegen<F>(tm: TargetMachineRef,
500 llmod: ModuleRef,
501 no_builtins: bool,
502 f: F) where
503 F: FnOnce(PassManagerRef),
504 {
Stuart Pernsteinercf672852014-07-17 17:52:52505 let cpm = llvm::LLVMCreatePassManager();
506 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
507 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
508 f(cpm);
509 llvm::LLVMDisposePassManager(cpm);
510 }
511
512 if config.emit_bc {
513 let ext = format!("{}.bc", name_extra);
Alex Crichtonec7a50d2014-11-25 21:28:35514 let out = output_names.with_extension(ext.as_slice());
515 let out = CString::from_slice(out.as_vec());
516 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
Stuart Pernsteinercf672852014-07-17 17:52:52517 }
518
519 time(config.time_passes, "codegen passes", (), |()| {
520 if config.emit_ir {
521 let ext = format!("{}.ll", name_extra);
Alex Crichtonec7a50d2014-11-25 21:28:35522 let out = output_names.with_extension(ext.as_slice());
523 let out = CString::from_slice(out.as_vec());
524 with_codegen(tm, llmod, config.no_builtins, |cpm| {
525 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr());
Stuart Pernsteinercf672852014-07-17 17:52:52526 })
527 }
528
529 if config.emit_asm {
Jorge Aparicio517f1cc2015-01-07 16:58:31530 let path = output_names.with_extension(&format!("{}.s", name_extra)[]);
Stuart Pernsteinercf672852014-07-17 17:52:52531 with_codegen(tm, llmod, config.no_builtins, |cpm| {
Nick Cameronce0907e2014-09-11 05:07:49532 write_output_file(cgcx.handler, tm, cpm, llmod, &path, llvm::AssemblyFileType);
Stuart Pernsteinercf672852014-07-17 17:52:52533 });
534 }
535
536 if config.emit_obj {
Jorge Aparicio517f1cc2015-01-07 16:58:31537 let path = output_names.with_extension(&format!("{}.o", name_extra)[]);
Stuart Pernsteinercf672852014-07-17 17:52:52538 with_codegen(tm, llmod, config.no_builtins, |cpm| {
Nick Cameronce0907e2014-09-11 05:07:49539 write_output_file(cgcx.handler, tm, cpm, llmod, &path, llvm::ObjectFileType);
Stuart Pernsteinercf672852014-07-17 17:52:52540 });
541 }
542 });
543
544 llvm::LLVMDisposeModule(llmod);
545 llvm::LLVMContextDispose(llcx);
546 llvm::LLVMRustDisposeTargetMachine(tm);
547}
548
549pub fn run_passes(sess: &Session,
550 trans: &CrateTranslation,
Niko Matsakisdc6e4142014-11-16 01:30:33551 output_types: &[config::OutputType],
Stuart Pernsteinercf672852014-07-17 17:52:52552 crate_output: &OutputFilenames) {
553 // It's possible that we have `codegen_units > 1` but only one item in
554 // `trans.modules`. We could theoretically proceed and do LTO in that
555 // case, but it would be confusing to have the validity of
556 // `-Z lto -C codegen-units=2` depend on details of the crate being
557 // compiled, so we complain regardless.
558 if sess.lto() && sess.opts.cg.codegen_units > 1 {
559 // This case is impossible to handle because LTO expects to be able
560 // to combine the entire crate and all its dependencies into a
561 // single compilation unit, but each codegen unit is in a separate
562 // LLVM context, so they can't easily be combined.
563 sess.fatal("can't perform LTO when using multiple codegen units");
564 }
565
Stuart Pernsteiner6d2d47b2014-09-05 21:30:36566 // Sanity check
567 assert!(trans.modules.len() == sess.opts.cg.codegen_units);
568
Stuart Pernsteinercf672852014-07-17 17:52:52569 unsafe {
570 configure_llvm(sess);
571 }
572
573 let tm = create_target_machine(sess);
574
575 // Figure out what we actually need to build.
576
577 let mut modules_config = ModuleConfig::new(tm, sess.opts.cg.passes.clone());
578 let mut metadata_config = ModuleConfig::new(tm, vec!());
579
580 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
581
582 // Save all versions of the bytecode if we're saving our temporaries.
583 if sess.opts.cg.save_temps {
584 modules_config.emit_no_opt_bc = true;
585 modules_config.emit_bc = true;
586 modules_config.emit_lto_bc = true;
587 metadata_config.emit_bc = true;
588 }
589
Stuart Pernsteinered476b02014-09-17 23:18:12590 // Emit bitcode files for the crate if we're emitting an rlib.
Stuart Pernsteinercf672852014-07-17 17:52:52591 // Whenever an rlib is created, the bitcode is inserted into the
592 // archive in order to allow LTO against it.
593 let needs_crate_bitcode =
594 sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
Niko Matsakisdc6e4142014-11-16 01:30:33595 sess.opts.output_types.contains(&config::OutputTypeExe);
Stuart Pernsteinercf672852014-07-17 17:52:52596 if needs_crate_bitcode {
597 modules_config.emit_bc = true;
598 }
599
600 for output_type in output_types.iter() {
601 match *output_type {
Niko Matsakisdc6e4142014-11-16 01:30:33602 config::OutputTypeBitcode => { modules_config.emit_bc = true; },
603 config::OutputTypeLlvmAssembly => { modules_config.emit_ir = true; },
604 config::OutputTypeAssembly => {
Stuart Pernsteinercf672852014-07-17 17:52:52605 modules_config.emit_asm = true;
606 // If we're not using the LLVM assembler, this function
607 // could be invoked specially with output_type_assembly, so
608 // in this case we still want the metadata object file.
Niko Matsakisdc6e4142014-11-16 01:30:33609 if !sess.opts.output_types.contains(&config::OutputTypeAssembly) {
Stuart Pernsteinercf672852014-07-17 17:52:52610 metadata_config.emit_obj = true;
Stuart Pernsteinere29aa142014-08-11 17:33:58611 }
Stuart Pernsteinercf672852014-07-17 17:52:52612 },
Niko Matsakisdc6e4142014-11-16 01:30:33613 config::OutputTypeObject => { modules_config.emit_obj = true; },
614 config::OutputTypeExe => {
Stuart Pernsteinercf672852014-07-17 17:52:52615 modules_config.emit_obj = true;
616 metadata_config.emit_obj = true;
617 },
Alex Crichton117984b2014-12-16 00:03:39618 config::OutputTypeDepInfo => {}
Stuart Pernsteinercf672852014-07-17 17:52:52619 }
620 }
621
622 modules_config.set_flags(sess, trans);
623 metadata_config.set_flags(sess, trans);
624
625
626 // Populate a buffer with a list of codegen tasks. Items are processed in
627 // LIFO order, just because it's a tiny bit simpler that way. (The order
628 // doesn't actually matter.)
629 let mut work_items = Vec::with_capacity(1 + trans.modules.len());
630
631 {
632 let work = build_work_item(sess,
633 trans.metadata_module,
634 metadata_config.clone(),
635 crate_output.clone(),
636 "metadata".to_string());
637 work_items.push(work);
638 }
639
640 for (index, mtrans) in trans.modules.iter().enumerate() {
641 let work = build_work_item(sess,
642 *mtrans,
643 modules_config.clone(),
644 crate_output.clone(),
645 format!("{}", index));
646 work_items.push(work);
647 }
648
649 // Process the work items, optionally using worker threads.
650 if sess.opts.cg.codegen_units == 1 {
Jorge Aparicio517f1cc2015-01-07 16:58:31651 run_work_singlethreaded(sess, &trans.reachable[], work_items);
Stuart Pernsteinercf672852014-07-17 17:52:52652 } else {
653 run_work_multithreaded(sess, work_items, sess.opts.cg.codegen_units);
Stuart Pernsteinercf672852014-07-17 17:52:52654 }
655
656 // All codegen is finished.
657 unsafe {
658 llvm::LLVMRustDisposeTargetMachine(tm);
659 }
660
661 // Produce final compile outputs.
662
Jorge Aparicioe47035b2014-12-31 01:58:47663 let copy_if_one_unit = |&: ext: &str, output_type: config::OutputType, keep_numbered: bool| {
Stuart Pernsteinercf672852014-07-17 17:52:52664 // Three cases:
665 if sess.opts.cg.codegen_units == 1 {
666 // 1) Only one codegen unit. In this case it's no difficulty
667 // to copy `foo.0.x` to `foo.x`.
668 fs::copy(&crate_output.with_extension(ext),
669 &crate_output.path(output_type)).unwrap();
Stuart Pernsteinered476b02014-09-17 23:18:12670 if !sess.opts.cg.save_temps && !keep_numbered {
Stuart Pernsteiner1b676fb2014-08-27 21:49:17671 // The user just wants `foo.x`, not `foo.0.x`.
672 remove(sess, &crate_output.with_extension(ext));
673 }
Stuart Pernsteinercf672852014-07-17 17:52:52674 } else {
675 if crate_output.single_output_file.is_some() {
676 // 2) Multiple codegen units, with `-o some_name`. We have
677 // no good solution for this case, so warn the user.
Jorge Aparicio517f1cc2015-01-07 16:58:31678 sess.warn(&format!("ignoring -o because multiple .{} files were produced",
679 ext)[]);
Stuart Pernsteinercf672852014-07-17 17:52:52680 } else {
681 // 3) Multiple codegen units, but no `-o some_name`. We
682 // just leave the `foo.0.x` files in place.
683 // (We don't have to do any work in this case.)
684 }
685 }
686 };
687
Jorge Aparicioe47035b2014-12-31 01:58:47688 let link_obj = |&: output_path: &Path| {
Stuart Pernsteiner6d2d47b2014-09-05 21:30:36689 // Running `ld -r` on a single input is kind of pointless.
690 if sess.opts.cg.codegen_units == 1 {
691 fs::copy(&crate_output.with_extension("0.o"),
692 output_path).unwrap();
693 // Leave the .0.o file around, to mimic the behavior of the normal
694 // code path.
695 return;
696 }
697
Stuart Pernsteiner4d9a4782014-08-29 19:46:04698 // Some builds of MinGW GCC will pass --force-exe-suffix to ld, which
699 // will automatically add a .exe extension if the extension is not
700 // already .exe or .dll. To ensure consistent behavior on Windows, we
701 // add the .exe suffix explicitly and then rename the output file to
702 // the desired path. This will give the correct behavior whether or
703 // not GCC adds --force-exe-suffix.
704 let windows_output_path =
Corey Richardson6b130e32014-07-23 18:56:36705 if sess.target.target.options.is_like_windows {
Stuart Pernsteiner4d9a4782014-08-29 19:46:04706 Some(output_path.with_extension("o.exe"))
707 } else {
708 None
709 };
710
Stuart Pernsteinerb5a0b702014-08-26 22:53:56711 let pname = get_cc_prog(sess);
Jorge Aparicio517f1cc2015-01-07 16:58:31712 let mut cmd = Command::new(&pname[]);
Stuart Pernsteinerb5a0b702014-08-26 22:53:56713
Jorge Aparicio517f1cc2015-01-07 16:58:31714 cmd.args(&sess.target.target.options.pre_link_args[]);
Stuart Pernsteinerb5a0b702014-08-26 22:53:56715 cmd.arg("-nostdlib");
Stuart Pernsteinercf672852014-07-17 17:52:52716
Jorge Aparicioefc97a52015-01-26 21:05:07717 for index in 0..trans.modules.len() {
Jorge Aparicio517f1cc2015-01-07 16:58:31718 cmd.arg(crate_output.with_extension(&format!("{}.o", index)[]));
Stuart Pernsteinercf672852014-07-17 17:52:52719 }
720
Stuart Pernsteiner4d9a4782014-08-29 19:46:04721 cmd.arg("-r")
722 .arg("-o")
723 .arg(windows_output_path.as_ref().unwrap_or(output_path));
Stuart Pernsteinerb5a0b702014-08-26 22:53:56724
Jorge Aparicio517f1cc2015-01-07 16:58:31725 cmd.args(&sess.target.target.options.post_link_args[]);
Corey Richardson6b130e32014-07-23 18:56:36726
Manish Goregaokar7e87ea92014-12-09 09:55:49727 if sess.opts.debugging_opts.print_link_args {
Alex Crichton3cb9fa22015-01-20 23:45:07728 println!("{:?}", &cmd);
Stuart Pernsteinerb5a0b702014-08-26 22:53:56729 }
730
Alex Crichton3a07f852015-01-23 00:31:00731 cmd.stdin(::std::old_io::process::Ignored)
732 .stdout(::std::old_io::process::InheritFd(1))
733 .stderr(::std::old_io::process::InheritFd(2));
Stuart Pernsteinerb5a0b702014-08-26 22:53:56734 match cmd.status() {
Markus Siemens53ac8522014-10-22 20:23:22735 Ok(status) => {
736 if !status.success() {
Alex Crichton3cb9fa22015-01-20 23:45:07737 sess.err(&format!("linking of {} with `{:?}` failed",
Jorge Aparicio517f1cc2015-01-07 16:58:31738 output_path.display(), cmd)[]);
Markus Siemens53ac8522014-10-22 20:23:22739 sess.abort_if_errors();
740 }
741 },
Stuart Pernsteinerb5a0b702014-08-26 22:53:56742 Err(e) => {
Jorge Aparicio517f1cc2015-01-07 16:58:31743 sess.err(&format!("could not exec the linker `{}`: {}",
Stuart Pernsteinerb5a0b702014-08-26 22:53:56744 pname,
Jorge Aparicio517f1cc2015-01-07 16:58:31745 e)[]);
Stuart Pernsteinerb5a0b702014-08-26 22:53:56746 sess.abort_if_errors();
747 },
748 }
Stuart Pernsteiner4d9a4782014-08-29 19:46:04749
750 match windows_output_path {
751 Some(ref windows_path) => {
752 fs::rename(windows_path, output_path).unwrap();
753 },
754 None => {
755 // The file is already named according to `output_path`.
756 }
757 }
Stuart Pernsteinercf672852014-07-17 17:52:52758 };
759
760 // Flag to indicate whether the user explicitly requested bitcode.
761 // Otherwise, we produced it only as a temporary output, and will need
762 // to get rid of it.
Stuart Pernsteinered476b02014-09-17 23:18:12763 let mut user_wants_bitcode = false;
Stuart Pernsteinercf672852014-07-17 17:52:52764 for output_type in output_types.iter() {
765 match *output_type {
Niko Matsakisdc6e4142014-11-16 01:30:33766 config::OutputTypeBitcode => {
Stuart Pernsteinered476b02014-09-17 23:18:12767 user_wants_bitcode = true;
768 // Copy to .bc, but always keep the .0.bc. There is a later
769 // check to figure out if we should delete .0.bc files, or keep
770 // them for making an rlib.
Niko Matsakisdc6e4142014-11-16 01:30:33771 copy_if_one_unit("0.bc", config::OutputTypeBitcode, true);
772 }
773 config::OutputTypeLlvmAssembly => {
774 copy_if_one_unit("0.ll", config::OutputTypeLlvmAssembly, false);
775 }
776 config::OutputTypeAssembly => {
777 copy_if_one_unit("0.s", config::OutputTypeAssembly, false);
778 }
779 config::OutputTypeObject => {
780 link_obj(&crate_output.path(config::OutputTypeObject));
781 }
782 config::OutputTypeExe => {
783 // If config::OutputTypeObject is already in the list, then
784 // `crate.o` will be handled by the config::OutputTypeObject case.
Stuart Pernsteinercf672852014-07-17 17:52:52785 // Otherwise, we need to create the temporary object so we
786 // can run the linker.
Niko Matsakisdc6e4142014-11-16 01:30:33787 if !sess.opts.output_types.contains(&config::OutputTypeObject) {
788 link_obj(&crate_output.temp_path(config::OutputTypeObject));
Stuart Pernsteinere29aa142014-08-11 17:33:58789 }
Niko Matsakisdc6e4142014-11-16 01:30:33790 }
Alex Crichton117984b2014-12-16 00:03:39791 config::OutputTypeDepInfo => {}
Stuart Pernsteinercf672852014-07-17 17:52:52792 }
793 }
Stuart Pernsteinered476b02014-09-17 23:18:12794 let user_wants_bitcode = user_wants_bitcode;
Stuart Pernsteinercf672852014-07-17 17:52:52795
796 // Clean up unwanted temporary files.
797
798 // We create the following files by default:
799 // - crate.0.bc
800 // - crate.0.o
801 // - crate.metadata.bc
802 // - crate.metadata.o
803 // - crate.o (linked from crate.##.o)
Stuart Pernsteiner1b676fb2014-08-27 21:49:17804 // - crate.bc (copied from crate.0.bc)
Stuart Pernsteinercf672852014-07-17 17:52:52805 // We may create additional files if requested by the user (through
806 // `-C save-temps` or `--emit=` flags).
807
808 if !sess.opts.cg.save_temps {
809 // Remove the temporary .0.o objects. If the user didn't
Stuart Pernsteinered476b02014-09-17 23:18:12810 // explicitly request bitcode (with --emit=bc), and the bitcode is not
811 // needed for building an rlib, then we must remove .0.bc as well.
812
813 // Specific rules for keeping .0.bc:
814 // - If we're building an rlib (`needs_crate_bitcode`), then keep
815 // it.
816 // - If the user requested bitcode (`user_wants_bitcode`), and
817 // codegen_units > 1, then keep it.
818 // - If the user requested bitcode but codegen_units == 1, then we
819 // can toss .0.bc because we copied it to .bc earlier.
820 // - If we're not building an rlib and the user didn't request
821 // bitcode, then delete .0.bc.
822 // If you change how this works, also update back::link::link_rlib,
823 // where .0.bc files are (maybe) deleted after making an rlib.
824 let keep_numbered_bitcode = needs_crate_bitcode ||
825 (user_wants_bitcode && sess.opts.cg.codegen_units > 1);
826
Jorge Aparicioefc97a52015-01-26 21:05:07827 for i in 0..trans.modules.len() {
Stuart Pernsteinercf672852014-07-17 17:52:52828 if modules_config.emit_obj {
829 let ext = format!("{}.o", i);
Jorge Aparicio517f1cc2015-01-07 16:58:31830 remove(sess, &crate_output.with_extension(&ext[]));
Stuart Pernsteinercf672852014-07-17 17:52:52831 }
832
Stuart Pernsteinered476b02014-09-17 23:18:12833 if modules_config.emit_bc && !keep_numbered_bitcode {
Stuart Pernsteinercf672852014-07-17 17:52:52834 let ext = format!("{}.bc", i);
Jorge Aparicio517f1cc2015-01-07 16:58:31835 remove(sess, &crate_output.with_extension(&ext[]));
Stuart Pernsteinere29aa142014-08-11 17:33:58836 }
837 }
838
Stuart Pernsteinered476b02014-09-17 23:18:12839 if metadata_config.emit_bc && !user_wants_bitcode {
Stuart Pernsteinercf672852014-07-17 17:52:52840 remove(sess, &crate_output.with_extension("metadata.bc"));
841 }
842 }
843
844 // We leave the following files around by default:
845 // - crate.o
846 // - crate.metadata.o
847 // - crate.bc
848 // These are used in linking steps and will be cleaned up afterward.
849
850 // FIXME: time_llvm_passes support - does this use a global context or
851 // something?
852 //if sess.time_llvm_passes() { llvm::LLVMRustPrintPassTimings(); }
853}
854
Niko Matsakis394f6842014-11-26 15:07:58855struct WorkItem {
856 mtrans: ModuleTranslation,
857 config: ModuleConfig,
858 output_names: OutputFilenames,
859 name_extra: String
860}
Stuart Pernsteinercf672852014-07-17 17:52:52861
862fn build_work_item(sess: &Session,
863 mtrans: ModuleTranslation,
864 config: ModuleConfig,
865 output_names: OutputFilenames,
Niko Matsakis394f6842014-11-26 15:07:58866 name_extra: String)
867 -> WorkItem
868{
Stuart Pernsteinercf672852014-07-17 17:52:52869 let mut config = config;
870 config.tm = create_target_machine(sess);
Niko Matsakis394f6842014-11-26 15:07:58871 WorkItem { mtrans: mtrans, config: config, output_names: output_names,
872 name_extra: name_extra }
873}
Stuart Pernsteinercf672852014-07-17 17:52:52874
Niko Matsakis394f6842014-11-26 15:07:58875fn execute_work_item(cgcx: &CodegenContext,
876 work_item: WorkItem) {
877 unsafe {
878 optimize_and_codegen(cgcx, work_item.mtrans, work_item.config,
879 work_item.name_extra, work_item.output_names);
Stuart Pernsteinercf672852014-07-17 17:52:52880 }
881}
882
883fn run_work_singlethreaded(sess: &Session,
884 reachable: &[String],
885 work_items: Vec<WorkItem>) {
886 let cgcx = CodegenContext::new_with_session(sess, reachable);
887 let mut work_items = work_items;
888
889 // Since we're running single-threaded, we can pass the session to
890 // the proc, allowing `optimize_and_codegen` to perform LTO.
891 for work in Unfold::new((), |_| work_items.pop()) {
Niko Matsakis394f6842014-11-26 15:07:58892 execute_work_item(&cgcx, work);
Stuart Pernsteinercf672852014-07-17 17:52:52893 }
894}
895
896fn run_work_multithreaded(sess: &Session,
897 work_items: Vec<WorkItem>,
898 num_workers: uint) {
899 // Run some workers to process the work items.
900 let work_items_arc = Arc::new(Mutex::new(work_items));
901 let mut diag_emitter = SharedEmitter::new();
902 let mut futures = Vec::with_capacity(num_workers);
903
Jorge Aparicio7d661af2015-01-26 20:46:12904 for i in 0..num_workers {
Stuart Pernsteinercf672852014-07-17 17:52:52905 let work_items_arc = work_items_arc.clone();
906 let diag_emitter = diag_emitter.clone();
Keegan McAllisterad9a1da2014-09-12 15:17:58907 let remark = sess.opts.cg.remark.clone();
Stuart Pernsteinercf672852014-07-17 17:52:52908
Aaron Turon43ae4b32014-12-07 02:34:37909 let (tx, rx) = channel();
910 let mut tx = Some(tx);
911 futures.push(rx);
912
Aaron Turona27fbac2014-12-14 08:05:32913 thread::Builder::new().name(format!("codegen-{}", i)).spawn(move |:| {
Brian Andersonabc56a02015-01-26 23:42:24914 let diag_handler = mk_handler(true, box diag_emitter);
Stuart Pernsteinercf672852014-07-17 17:52:52915
916 // Must construct cgcx inside the proc because it has non-Send
917 // fields.
Keegan McAllisterad9a1da2014-09-12 15:17:58918 let cgcx = CodegenContext {
919 lto_ctxt: None,
920 handler: &diag_handler,
921 remark: remark,
922 };
Stuart Pernsteinercf672852014-07-17 17:52:52923
924 loop {
925 // Avoid holding the lock for the entire duration of the match.
Alex Crichton76e5ed62014-12-09 04:20:03926 let maybe_work = work_items_arc.lock().unwrap().pop();
Stuart Pernsteinercf672852014-07-17 17:52:52927 match maybe_work {
928 Some(work) => {
Niko Matsakis394f6842014-11-26 15:07:58929 execute_work_item(&cgcx, work);
Stuart Pernsteinercf672852014-07-17 17:52:52930
931 // Make sure to fail the worker so the main thread can
932 // tell that there were errors.
933 cgcx.handler.abort_if_errors();
934 }
935 None => break,
Stuart Pernsteinere29aa142014-08-11 17:33:58936 }
Stuart Pernsteinere29aa142014-08-11 17:33:58937 }
Aaron Turon43ae4b32014-12-07 02:34:37938
Alex Crichtonbc83a002014-12-23 19:53:35939 tx.take().unwrap().send(()).unwrap();
Aaron Turoncaca9b22015-01-06 05:59:45940 });
Stuart Pernsteinercf672852014-07-17 17:52:52941 }
Stuart Pernsteinere29aa142014-08-11 17:33:58942
Steve Klabnik7828c3d2014-10-09 19:17:22943 let mut panicked = false;
Aaron Turon43ae4b32014-12-07 02:34:37944 for rx in futures.into_iter() {
Alex Crichtonbc83a002014-12-23 19:53:35945 match rx.recv() {
Stuart Pernsteinercf672852014-07-17 17:52:52946 Ok(()) => {},
947 Err(_) => {
Steve Klabnik7828c3d2014-10-09 19:17:22948 panicked = true;
Stuart Pernsteinercf672852014-07-17 17:52:52949 },
950 }
951 // Display any new diagnostics.
952 diag_emitter.dump(sess.diagnostic().handler());
953 }
Steve Klabnik7828c3d2014-10-09 19:17:22954 if panicked {
955 sess.fatal("aborting due to worker thread panic");
Stuart Pernsteinere29aa142014-08-11 17:33:58956 }
957}
958
959pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
960 let pname = get_cc_prog(sess);
Jorge Aparicio517f1cc2015-01-07 16:58:31961 let mut cmd = Command::new(&pname[]);
Stuart Pernsteinere29aa142014-08-11 17:33:58962
Niko Matsakisdc6e4142014-11-16 01:30:33963 cmd.arg("-c").arg("-o").arg(outputs.path(config::OutputTypeObject))
964 .arg(outputs.temp_path(config::OutputTypeAssembly));
Alex Crichton3cb9fa22015-01-20 23:45:07965 debug!("{:?}", &cmd);
Stuart Pernsteinere29aa142014-08-11 17:33:58966
967 match cmd.output() {
968 Ok(prog) => {
969 if !prog.status.success() {
Jorge Aparicio517f1cc2015-01-07 16:58:31970 sess.err(&format!("linking with `{}` failed: {}",
Stuart Pernsteinere29aa142014-08-11 17:33:58971 pname,
Jorge Aparicio517f1cc2015-01-07 16:58:31972 prog.status)[]);
Alex Crichton3cb9fa22015-01-20 23:45:07973 sess.note(&format!("{:?}", &cmd)[]);
Stuart Pernsteinere29aa142014-08-11 17:33:58974 let mut note = prog.error.clone();
Jorge Aparicio517f1cc2015-01-07 16:58:31975 note.push_all(&prog.output[]);
976 sess.note(str::from_utf8(&note[]).unwrap());
Stuart Pernsteinere29aa142014-08-11 17:33:58977 sess.abort_if_errors();
978 }
979 },
980 Err(e) => {
Jorge Aparicio517f1cc2015-01-07 16:58:31981 sess.err(&format!("could not exec the linker `{}`: {}",
Stuart Pernsteinere29aa142014-08-11 17:33:58982 pname,
Jorge Aparicio517f1cc2015-01-07 16:58:31983 e)[]);
Stuart Pernsteinere29aa142014-08-11 17:33:58984 sess.abort_if_errors();
985 }
986 }
987}
988
989unsafe fn configure_llvm(sess: &Session) {
990 use std::sync::{Once, ONCE_INIT};
Alex Crichtondae48a02014-10-11 04:59:10991 static INIT: Once = ONCE_INIT;
Stuart Pernsteinere29aa142014-08-11 17:33:58992
993 // Copy what clang does by turning on loop vectorization at O2 and
994 // slp vectorization at O3
995 let vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
996 (sess.opts.optimize == config::Default ||
997 sess.opts.optimize == config::Aggressive);
998 let vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
999 sess.opts.optimize == config::Aggressive;
1000
1001 let mut llvm_c_strs = Vec::new();
1002 let mut llvm_args = Vec::new();
1003 {
Jorge Aparicioe47035b2014-12-31 01:58:471004 let mut add = |&mut : arg: &str| {
Alex Crichtonec7a50d2014-11-25 21:28:351005 let s = CString::from_slice(arg.as_bytes());
Stuart Pernsteinere29aa142014-08-11 17:33:581006 llvm_args.push(s.as_ptr());
1007 llvm_c_strs.push(s);
1008 };
1009 add("rustc"); // fake program name
1010 if vectorize_loop { add("-vectorize-loops"); }
1011 if vectorize_slp { add("-vectorize-slp"); }
1012 if sess.time_llvm_passes() { add("-time-passes"); }
1013 if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
1014
Akos Kissea50bf82015-01-26 21:39:511015 // FIXME #21627 disable faulty FastISel on AArch64 (even for -O0)
1016 if sess.target.target.arch.as_slice() == "aarch64" { add("-fast-isel=0"); }
1017
Stuart Pernsteinere29aa142014-08-11 17:33:581018 for arg in sess.opts.cg.llvm_args.iter() {
Jorge Aparicio517f1cc2015-01-07 16:58:311019 add(&(*arg)[]);
Stuart Pernsteinere29aa142014-08-11 17:33:581020 }
1021 }
1022
Alex Crichtonf3a7ec72014-12-29 23:03:011023 INIT.call_once(|| {
Stuart Pernsteinere29aa142014-08-11 17:33:581024 llvm::LLVMInitializePasses();
1025
1026 // Only initialize the platforms supported by Rust here, because
1027 // using --llvm-root will have multiple platforms that rustllvm
1028 // doesn't actually link to and it's pointless to put target info
1029 // into the registry that Rust cannot generate machine code for.
1030 llvm::LLVMInitializeX86TargetInfo();
1031 llvm::LLVMInitializeX86Target();
1032 llvm::LLVMInitializeX86TargetMC();
1033 llvm::LLVMInitializeX86AsmPrinter();
1034 llvm::LLVMInitializeX86AsmParser();
1035
1036 llvm::LLVMInitializeARMTargetInfo();
1037 llvm::LLVMInitializeARMTarget();
1038 llvm::LLVMInitializeARMTargetMC();
1039 llvm::LLVMInitializeARMAsmPrinter();
1040 llvm::LLVMInitializeARMAsmParser();
1041
Akos Kiss6e5fb8b2014-12-12 23:39:271042 llvm::LLVMInitializeAArch64TargetInfo();
1043 llvm::LLVMInitializeAArch64Target();
1044 llvm::LLVMInitializeAArch64TargetMC();
1045 llvm::LLVMInitializeAArch64AsmPrinter();
1046 llvm::LLVMInitializeAArch64AsmParser();
1047
Stuart Pernsteinere29aa142014-08-11 17:33:581048 llvm::LLVMInitializeMipsTargetInfo();
1049 llvm::LLVMInitializeMipsTarget();
1050 llvm::LLVMInitializeMipsTargetMC();
1051 llvm::LLVMInitializeMipsAsmPrinter();
1052 llvm::LLVMInitializeMipsAsmParser();
1053
Richo Healey33cd9cf2015-01-10 04:03:371054 llvm::LLVMInitializePowerPCTargetInfo();
1055 llvm::LLVMInitializePowerPCTarget();
1056 llvm::LLVMInitializePowerPCTargetMC();
1057 llvm::LLVMInitializePowerPCAsmPrinter();
1058 llvm::LLVMInitializePowerPCAsmParser();
1059
Stuart Pernsteinere29aa142014-08-11 17:33:581060 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
1061 llvm_args.as_ptr());
1062 });
1063}
1064
1065unsafe fn populate_llvm_passes(fpm: llvm::PassManagerRef,
1066 mpm: llvm::PassManagerRef,
1067 llmod: ModuleRef,
1068 opt: llvm::CodeGenOptLevel,
1069 no_builtins: bool) {
1070 // Create the PassManagerBuilder for LLVM. We configure it with
1071 // reasonable defaults and prepare it to actually populate the pass
1072 // manager.
1073 let builder = llvm::LLVMPassManagerBuilderCreate();
1074 match opt {
1075 llvm::CodeGenLevelNone => {
1076 // Don't add lifetime intrinsics at O0
1077 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
1078 }
1079 llvm::CodeGenLevelLess => {
1080 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
1081 }
1082 // numeric values copied from clang
1083 llvm::CodeGenLevelDefault => {
1084 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
1085 225);
1086 }
1087 llvm::CodeGenLevelAggressive => {
1088 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
1089 275);
1090 }
1091 }
1092 llvm::LLVMPassManagerBuilderSetOptLevel(builder, opt as c_uint);
1093 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, no_builtins);
1094
1095 // Use the builder to populate the function/module pass managers.
1096 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(builder, fpm);
1097 llvm::LLVMPassManagerBuilderPopulateModulePassManager(builder, mpm);
1098 llvm::LLVMPassManagerBuilderDispose(builder);
1099
1100 match opt {
1101 llvm::CodeGenLevelDefault | llvm::CodeGenLevelAggressive => {
Alex Crichtonec7a50d2014-11-25 21:28:351102 llvm::LLVMRustAddPass(mpm, "mergefunc\0".as_ptr() as *const _);
Stuart Pernsteinere29aa142014-08-11 17:33:581103 }
1104 _ => {}
1105 };
1106}