blob: 9d40ff3d383f92083e4245bffd5ef75653208d13 [file] [log] [blame]
Stuart Pernsteinere29aa142014-08-11 17:33:581// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
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
25use std::c_str::{ToCStr, CString};
26use 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};
33use std::task::TaskBuilder;
Keegan McAllisterad9a1da2014-09-12 15:17:5834use libc::{c_uint, c_int, c_void};
Stuart Pernsteinere29aa142014-08-11 17:33:5835
Niko Matsakis096a2862014-12-06 01:01:3336#[deriving(Clone, PartialEq, PartialOrd, Ord, Eq)]
37pub enum OutputType {
38 OutputTypeBitcode,
39 OutputTypeAssembly,
40 OutputTypeLlvmAssembly,
41 OutputTypeObject,
42 OutputTypeExe,
43}
44
45impl Copy for OutputType {}
46
Stuart Pernsteinercf672852014-07-17 17:52:5247pub fn llvm_err(handler: &diagnostic::Handler, msg: String) -> ! {
Stuart Pernsteinere29aa142014-08-11 17:33:5848 unsafe {
49 let cstr = llvm::LLVMRustGetLastError();
50 if cstr == ptr::null() {
Stuart Pernsteinercf672852014-07-17 17:52:5251 handler.fatal(msg.as_slice());
Stuart Pernsteinere29aa142014-08-11 17:33:5852 } else {
53 let err = CString::new(cstr, true);
54 let err = String::from_utf8_lossy(err.as_bytes());
Stuart Pernsteinercf672852014-07-17 17:52:5255 handler.fatal(format!("{}: {}",
56 msg.as_slice(),
57 err.as_slice()).as_slice());
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 {
70 output.with_c_str(|output| {
71 let result = llvm::LLVMRustWriteOutputFile(
72 target, pm, m, output, file_type);
73 if !result {
Stuart Pernsteinercf672852014-07-17 17:52:5274 llvm_err(handler, "could not write output".to_string());
Stuart Pernsteinere29aa142014-08-11 17:33:5875 }
76 })
77 }
78}
79
80
Stuart Pernsteinercf672852014-07-17 17:52:5281struct Diagnostic {
82 msg: String,
83 code: Option<String>,
84 lvl: Level,
85}
86
87// We use an Arc instead of just returning a list of diagnostics from the
88// child task because we need to make sure that the messages are seen even
Steve Klabnik7828c3d2014-10-09 19:17:2289// if the child task panics (for example, when `fatal` is called).
Stuart Pernsteinercf672852014-07-17 17:52:5290#[deriving(Clone)]
91struct SharedEmitter {
92 buffer: Arc<Mutex<Vec<Diagnostic>>>,
93}
94
95impl SharedEmitter {
96 fn new() -> SharedEmitter {
97 SharedEmitter {
98 buffer: Arc::new(Mutex::new(Vec::new())),
99 }
100 }
101
102 fn dump(&mut self, handler: &Handler) {
103 let mut buffer = self.buffer.lock();
104 for diag in buffer.iter() {
105 match diag.code {
106 Some(ref code) => {
107 handler.emit_with_code(None,
108 diag.msg.as_slice(),
109 code.as_slice(),
110 diag.lvl);
111 },
112 None => {
113 handler.emit(None,
114 diag.msg.as_slice(),
115 diag.lvl);
116 },
117 }
118 }
119 buffer.clear();
120 }
121}
122
123impl Emitter for SharedEmitter {
124 fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, codemap::Span)>,
125 msg: &str, code: Option<&str>, lvl: Level) {
126 assert!(cmsp.is_none(), "SharedEmitter doesn't support spans");
127
128 self.buffer.lock().push(Diagnostic {
129 msg: msg.to_string(),
130 code: code.map(|s| s.to_string()),
131 lvl: lvl,
132 });
133 }
134
135 fn custom_emit(&mut self, _cm: &codemap::CodeMap,
136 _sp: diagnostic::RenderSpan, _msg: &str, _lvl: Level) {
Steve Klabnik7828c3d2014-10-09 19:17:22137 panic!("SharedEmitter doesn't support custom_emit");
Stuart Pernsteinercf672852014-07-17 17:52:52138 }
139}
140
141
Stuart Pernsteinere29aa142014-08-11 17:33:58142// On android, we by default compile for armv7 processors. This enables
143// things like double word CAS instructions (rather than emulating them)
144// which are *far* more efficient. This is obviously undesirable in some
145// cases, so if any sort of target feature is specified we don't append v7
146// to the feature list.
147//
148// On iOS only armv7 and newer are supported. So it is useful to
149// get all hardware potential via VFP3 (hardware floating point)
150// and NEON (SIMD) instructions supported by LLVM.
151// Note that without those flags various linking errors might
152// arise as some of intrinsics are converted into function calls
153// and nobody provides implementations those functions
Corey Richardson6b130e32014-07-23 18:56:36154fn target_feature(sess: &Session) -> String {
155 format!("{},{}", sess.target.target.options.features, sess.opts.cg.target_feature)
Stuart Pernsteinere29aa142014-08-11 17:33:58156}
157
Stuart Pernsteinercf672852014-07-17 17:52:52158fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
159 match optimize {
160 config::No => llvm::CodeGenLevelNone,
161 config::Less => llvm::CodeGenLevelLess,
162 config::Default => llvm::CodeGenLevelDefault,
163 config::Aggressive => llvm::CodeGenLevelAggressive,
164 }
165}
Stuart Pernsteinere29aa142014-08-11 17:33:58166
Stuart Pernsteinercf672852014-07-17 17:52:52167fn create_target_machine(sess: &Session) -> TargetMachineRef {
Corey Richardson6b130e32014-07-23 18:56:36168 let reloc_model_arg = match sess.opts.cg.relocation_model {
169 Some(ref s) => s.as_slice(),
170 None => sess.target.target.options.relocation_model.as_slice()
171 };
172 let reloc_model = match reloc_model_arg {
Stuart Pernsteinercf672852014-07-17 17:52:52173 "pic" => llvm::RelocPIC,
174 "static" => llvm::RelocStatic,
175 "default" => llvm::RelocDefault,
176 "dynamic-no-pic" => llvm::RelocDynamicNoPic,
177 _ => {
178 sess.err(format!("{} is not a valid relocation mode",
179 sess.opts
180 .cg
181 .relocation_model).as_slice());
182 sess.abort_if_errors();
183 unreachable!();
Stuart Pernsteinere29aa142014-08-11 17:33:58184 }
Stuart Pernsteinercf672852014-07-17 17:52:52185 };
Stuart Pernsteinere29aa142014-08-11 17:33:58186
Stuart Pernsteinercf672852014-07-17 17:52:52187 let opt_level = get_llvm_opt_level(sess.opts.optimize);
188 let use_softfp = sess.opts.cg.soft_float;
Stuart Pernsteinere29aa142014-08-11 17:33:58189
Stuart Pernsteinercf672852014-07-17 17:52:52190 // FIXME: #11906: Omitting frame pointers breaks retrieving the value of a parameter.
Stuart Pernsteinercf672852014-07-17 17:52:52191 let no_fp_elim = (sess.opts.debuginfo != NoDebugInfo) ||
Corey Richardson6b130e32014-07-23 18:56:36192 !sess.target.target.options.eliminate_frame_pointer;
Stuart Pernsteinere29aa142014-08-11 17:33:58193
Daniel Micay4deb4bc2014-08-09 16:43:45194 let any_library = sess.crate_types.borrow().iter().any(|ty| {
195 *ty != config::CrateTypeExecutable
196 });
197
Corey Richardson6b130e32014-07-23 18:56:36198 let ffunction_sections = sess.target.target.options.function_sections;
Stuart Pernsteinercf672852014-07-17 17:52:52199 let fdata_sections = ffunction_sections;
Stuart Pernsteinere29aa142014-08-11 17:33:58200
Corey Richardson6b130e32014-07-23 18:56:36201 let code_model_arg = match sess.opts.cg.code_model {
202 Some(ref s) => s.as_slice(),
203 None => sess.target.target.options.code_model.as_slice()
204 };
205
206 let code_model = match code_model_arg {
Stuart Pernsteinercf672852014-07-17 17:52:52207 "default" => llvm::CodeModelDefault,
208 "small" => llvm::CodeModelSmall,
209 "kernel" => llvm::CodeModelKernel,
210 "medium" => llvm::CodeModelMedium,
211 "large" => llvm::CodeModelLarge,
212 _ => {
213 sess.err(format!("{} is not a valid code model",
214 sess.opts
215 .cg
216 .code_model).as_slice());
217 sess.abort_if_errors();
218 unreachable!();
219 }
220 };
Stuart Pernsteinere29aa142014-08-11 17:33:58221
Corey Richardson6b130e32014-07-23 18:56:36222 let triple = sess.target.target.llvm_target.as_slice();
Richo Healey89e8caa2014-10-29 01:58:46223
224 let tm = unsafe {
Corey Richardson6b130e32014-07-23 18:56:36225 triple.with_c_str(|t| {
226 let cpu = match sess.opts.cg.target_cpu {
227 Some(ref s) => s.as_slice(),
228 None => sess.target.target.options.cpu.as_slice()
229 };
230 cpu.with_c_str(|cpu| {
Stuart Pernsteinere29aa142014-08-11 17:33:58231 target_feature(sess).with_c_str(|features| {
232 llvm::LLVMRustCreateTargetMachine(
233 t, cpu, features,
234 code_model,
235 reloc_model,
236 opt_level,
237 true /* EnableSegstk */,
238 use_softfp,
239 no_fp_elim,
Daniel Micay4deb4bc2014-08-09 16:43:45240 !any_library && reloc_model == llvm::RelocPIC,
Stuart Pernsteinere29aa142014-08-11 17:33:58241 ffunction_sections,
242 fdata_sections,
243 )
244 })
245 })
Stuart Pernsteinercf672852014-07-17 17:52:52246 })
Richo Healey89e8caa2014-10-29 01:58:46247 };
248
249 if tm.is_null() {
250 llvm_err(sess.diagnostic().handler(),
251 format!("Could not create LLVM TargetMachine for triple: {}",
252 triple).to_string());
253 } else {
254 return tm;
255 };
Stuart Pernsteinercf672852014-07-17 17:52:52256}
Stuart Pernsteinere29aa142014-08-11 17:33:58257
Stuart Pernsteinere29aa142014-08-11 17:33:58258
Stuart Pernsteinercf672852014-07-17 17:52:52259/// Module-specific configuration for `optimize_and_codegen`.
260#[deriving(Clone)]
261struct ModuleConfig {
262 /// LLVM TargetMachine to use for codegen.
263 tm: TargetMachineRef,
264 /// Names of additional optimization passes to run.
265 passes: Vec<String>,
266 /// Some(level) to optimize at a certain level, or None to run
267 /// absolutely no optimizations (used for the metadata module).
268 opt_level: Option<llvm::CodeGenOptLevel>,
Stuart Pernsteinere29aa142014-08-11 17:33:58269
Stuart Pernsteinercf672852014-07-17 17:52:52270 // Flags indicating which outputs to produce.
271 emit_no_opt_bc: bool,
272 emit_bc: bool,
273 emit_lto_bc: bool,
274 emit_ir: bool,
275 emit_asm: bool,
276 emit_obj: bool,
277
278 // Miscellaneous flags. These are mostly copied from command-line
279 // options.
280 no_verify: bool,
281 no_prepopulate_passes: bool,
282 no_builtins: bool,
283 time_passes: bool,
284}
285
286impl ModuleConfig {
287 fn new(tm: TargetMachineRef, passes: Vec<String>) -> ModuleConfig {
288 ModuleConfig {
289 tm: tm,
290 passes: passes,
291 opt_level: None,
292
293 emit_no_opt_bc: false,
294 emit_bc: false,
295 emit_lto_bc: false,
296 emit_ir: false,
297 emit_asm: false,
298 emit_obj: false,
299
300 no_verify: false,
301 no_prepopulate_passes: false,
302 no_builtins: false,
303 time_passes: false,
Stuart Pernsteinere29aa142014-08-11 17:33:58304 }
Stuart Pernsteinercf672852014-07-17 17:52:52305 }
Stuart Pernsteinere29aa142014-08-11 17:33:58306
Stuart Pernsteinercf672852014-07-17 17:52:52307 fn set_flags(&mut self, sess: &Session, trans: &CrateTranslation) {
308 self.no_verify = sess.no_verify();
309 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
310 self.no_builtins = trans.no_builtins;
311 self.time_passes = sess.time_passes();
312 }
313}
314
315/// Additional resources used by optimize_and_codegen (not module specific)
316struct CodegenContext<'a> {
317 // Extra resources used for LTO: (sess, reachable). This will be `None`
318 // when running in a worker thread.
319 lto_ctxt: Option<(&'a Session, &'a [String])>,
320 // Handler to use for diagnostics produced during codegen.
321 handler: &'a Handler,
Keegan McAllisterad9a1da2014-09-12 15:17:58322 // LLVM optimizations for which we want to print remarks.
323 remark: Passes,
Stuart Pernsteinercf672852014-07-17 17:52:52324}
325
326impl<'a> CodegenContext<'a> {
Stuart Pernsteinercf672852014-07-17 17:52:52327 fn new_with_session(sess: &'a Session, reachable: &'a [String]) -> CodegenContext<'a> {
328 CodegenContext {
329 lto_ctxt: Some((sess, reachable)),
330 handler: sess.diagnostic().handler(),
Keegan McAllisterad9a1da2014-09-12 15:17:58331 remark: sess.opts.cg.remark.clone(),
Stuart Pernsteinere29aa142014-08-11 17:33:58332 }
Stuart Pernsteinercf672852014-07-17 17:52:52333 }
334}
Stuart Pernsteinere29aa142014-08-11 17:33:58335
Keegan McAllister9d60de92014-09-27 08:33:36336struct HandlerFreeVars<'a> {
Keegan McAllisterad9a1da2014-09-12 15:17:58337 llcx: ContextRef,
338 cgcx: &'a CodegenContext<'a>,
339}
340
Keegan McAllister9d60de92014-09-27 08:33:36341unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
342 user: *const c_void,
343 cookie: c_uint) {
344 use syntax::codemap::ExpnId;
345
346 let HandlerFreeVars { cgcx, .. }
347 = *mem::transmute::<_, *const HandlerFreeVars>(user);
348
349 let msg = llvm::build_string(|s| llvm::LLVMWriteSMDiagnosticToString(diag, s))
350 .expect("non-UTF8 SMDiagnostic");
351
352 match cgcx.lto_ctxt {
353 Some((sess, _)) => {
Keegan McAllister8826fdf2014-09-28 16:25:48354 sess.codemap().with_expn_info(ExpnId::from_llvm_cookie(cookie), |info| match info {
Keegan McAllister9d60de92014-09-27 08:33:36355 Some(ei) => sess.span_err(ei.call_site, msg.as_slice()),
356 None => sess.err(msg.as_slice()),
357 });
358 }
359
360 None => {
361 cgcx.handler.err(msg.as_slice());
362 cgcx.handler.note("build without -C codegen-units for more exact errors");
363 }
364 }
365}
366
Keegan McAllisterad9a1da2014-09-12 15:17:58367unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
Keegan McAllister9d60de92014-09-27 08:33:36368 let HandlerFreeVars { llcx, cgcx }
369 = *mem::transmute::<_, *const HandlerFreeVars>(user);
Keegan McAllisterad9a1da2014-09-12 15:17:58370
371 match llvm::diagnostic::Diagnostic::unpack(info) {
372 llvm::diagnostic::Optimization(opt) => {
373 let pass_name = CString::new(opt.pass_name, false);
374 let pass_name = pass_name.as_str().expect("got a non-UTF8 pass name from LLVM");
375 let enabled = match cgcx.remark {
376 AllPasses => true,
Jorge Aparicio8bb5ef92014-11-27 19:10:25377 SomePasses(ref v) => v.iter().any(|s| *s == pass_name),
Keegan McAllisterad9a1da2014-09-12 15:17:58378 };
379
380 if enabled {
381 let loc = llvm::debug_loc_to_string(llcx, opt.debug_loc);
Alex Crichton4af34942014-11-17 19:29:38382 cgcx.handler.note(format!("optimization {} for {} at {}: {}",
Keegan McAllisterad9a1da2014-09-12 15:17:58383 opt.kind.describe(),
384 pass_name,
385 if loc.is_empty() { "[unknown]" } else { loc.as_slice() },
386 llvm::twine_to_string(opt.message)).as_slice());
387 }
388 }
389
390 _ => (),
391 }
392}
393
Stuart Pernsteinercf672852014-07-17 17:52:52394// Unsafe due to LLVM calls.
395unsafe fn optimize_and_codegen(cgcx: &CodegenContext,
396 mtrans: ModuleTranslation,
397 config: ModuleConfig,
398 name_extra: String,
399 output_names: OutputFilenames) {
400 let ModuleTranslation { llmod, llcx } = mtrans;
401 let tm = config.tm;
Stuart Pernsteinere29aa142014-08-11 17:33:58402
Keegan McAllisterad9a1da2014-09-12 15:17:58403 // llcx doesn't outlive this function, so we can put this on the stack.
Keegan McAllister9d60de92014-09-27 08:33:36404 let fv = HandlerFreeVars {
Keegan McAllisterad9a1da2014-09-12 15:17:58405 llcx: llcx,
406 cgcx: cgcx,
407 };
Keegan McAllister9d60de92014-09-27 08:33:36408 let fv = &fv as *const HandlerFreeVars as *mut c_void;
409
410 llvm::LLVMSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, fv);
411
Keegan McAllisterad9a1da2014-09-12 15:17:58412 if !cgcx.remark.is_empty() {
Keegan McAllister9d60de92014-09-27 08:33:36413 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, fv);
Keegan McAllisterad9a1da2014-09-12 15:17:58414 }
415
Stuart Pernsteinercf672852014-07-17 17:52:52416 if config.emit_no_opt_bc {
417 let ext = format!("{}.no-opt.bc", name_extra);
418 output_names.with_extension(ext.as_slice()).with_c_str(|buf| {
419 llvm::LLVMWriteBitcodeToFile(llmod, buf);
420 })
421 }
422
423 match config.opt_level {
424 Some(opt_level) => {
425 // Create the two optimizing pass managers. These mirror what clang
426 // does, and are by populated by LLVM's default PassManagerBuilder.
427 // Each manager has a different set of passes, but they also share
428 // some common passes.
429 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
430 let mpm = llvm::LLVMCreatePassManager();
431
432 // If we're verifying or linting, add them to the function pass
433 // manager.
434 let addpass = |pass: &str| {
Jorge Aparicio8bb5ef92014-11-27 19:10:25435 pass.with_c_str(|s| llvm::LLVMRustAddPass(fpm, s))
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() {
Jorge Aparicio8bb5ef92014-11-27 19:10:25447 pass.with_c_str(|s| {
Stuart Pernsteinercf672852014-07-17 17:52:52448 if !llvm::LLVMRustAddPass(mpm, s) {
449 cgcx.handler.warn(format!("unknown pass {}, ignoring",
450 *pass).as_slice());
451 }
Stuart Pernsteinere29aa142014-08-11 17:33:58452 })
453 }
Stuart Pernsteinere29aa142014-08-11 17:33:58454
Stuart Pernsteinercf672852014-07-17 17:52:52455 // Finally, run the actual optimization passes
456 time(config.time_passes, "llvm function passes", (), |()|
457 llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
458 time(config.time_passes, "llvm module passes", (), |()|
459 llvm::LLVMRunPassManager(mpm, llmod));
Stuart Pernsteinere29aa142014-08-11 17:33:58460
Stuart Pernsteinercf672852014-07-17 17:52:52461 // Deallocate managers that we're now done with
462 llvm::LLVMDisposePassManager(fpm);
463 llvm::LLVMDisposePassManager(mpm);
464
465 match cgcx.lto_ctxt {
466 Some((sess, reachable)) if sess.lto() => {
467 time(sess.time_passes(), "all lto passes", (), |()|
468 lto::run(sess, llmod, tm, reachable));
469
470 if config.emit_lto_bc {
471 let name = format!("{}.lto.bc", name_extra);
472 output_names.with_extension(name.as_slice()).with_c_str(|buf| {
473 llvm::LLVMWriteBitcodeToFile(llmod, buf);
Stuart Pernsteinere29aa142014-08-11 17:33:58474 })
Stuart Pernsteinercf672852014-07-17 17:52:52475 }
476 },
477 _ => {},
478 }
479 },
480 None => {},
481 }
482
483 // A codegen-specific pass manager is used to generate object
484 // files for an LLVM module.
485 //
486 // Apparently each of these pass managers is a one-shot kind of
487 // thing, so we create a new one for each type of output. The
488 // pass manager passed to the closure should be ensured to not
489 // escape the closure itself, and the manager should only be
490 // used once.
Jorge Aparicio0676c3b2014-12-09 18:44:51491 unsafe fn with_codegen<F>(tm: TargetMachineRef,
492 llmod: ModuleRef,
493 no_builtins: bool,
494 f: F) where
495 F: FnOnce(PassManagerRef),
496 {
Stuart Pernsteinercf672852014-07-17 17:52:52497 let cpm = llvm::LLVMCreatePassManager();
498 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
499 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
500 f(cpm);
501 llvm::LLVMDisposePassManager(cpm);
502 }
503
504 if config.emit_bc {
505 let ext = format!("{}.bc", name_extra);
506 output_names.with_extension(ext.as_slice()).with_c_str(|buf| {
507 llvm::LLVMWriteBitcodeToFile(llmod, buf);
508 })
509 }
510
511 time(config.time_passes, "codegen passes", (), |()| {
512 if config.emit_ir {
513 let ext = format!("{}.ll", name_extra);
514 output_names.with_extension(ext.as_slice()).with_c_str(|output| {
515 with_codegen(tm, llmod, config.no_builtins, |cpm| {
516 llvm::LLVMRustPrintModule(cpm, llmod, output);
517 })
518 })
519 }
520
521 if config.emit_asm {
522 let path = output_names.with_extension(format!("{}.s", name_extra).as_slice());
523 with_codegen(tm, llmod, config.no_builtins, |cpm| {
Nick Cameronce0907e2014-09-11 05:07:49524 write_output_file(cgcx.handler, tm, cpm, llmod, &path, llvm::AssemblyFileType);
Stuart Pernsteinercf672852014-07-17 17:52:52525 });
526 }
527
528 if config.emit_obj {
529 let path = output_names.with_extension(format!("{}.o", name_extra).as_slice());
530 with_codegen(tm, llmod, config.no_builtins, |cpm| {
Nick Cameronce0907e2014-09-11 05:07:49531 write_output_file(cgcx.handler, tm, cpm, llmod, &path, llvm::ObjectFileType);
Stuart Pernsteinercf672852014-07-17 17:52:52532 });
533 }
534 });
535
536 llvm::LLVMDisposeModule(llmod);
537 llvm::LLVMContextDispose(llcx);
538 llvm::LLVMRustDisposeTargetMachine(tm);
539}
540
541pub fn run_passes(sess: &Session,
542 trans: &CrateTranslation,
Niko Matsakisdc6e4142014-11-16 01:30:33543 output_types: &[config::OutputType],
Stuart Pernsteinercf672852014-07-17 17:52:52544 crate_output: &OutputFilenames) {
545 // It's possible that we have `codegen_units > 1` but only one item in
546 // `trans.modules`. We could theoretically proceed and do LTO in that
547 // case, but it would be confusing to have the validity of
548 // `-Z lto -C codegen-units=2` depend on details of the crate being
549 // compiled, so we complain regardless.
550 if sess.lto() && sess.opts.cg.codegen_units > 1 {
551 // This case is impossible to handle because LTO expects to be able
552 // to combine the entire crate and all its dependencies into a
553 // single compilation unit, but each codegen unit is in a separate
554 // LLVM context, so they can't easily be combined.
555 sess.fatal("can't perform LTO when using multiple codegen units");
556 }
557
Stuart Pernsteiner6d2d47b2014-09-05 21:30:36558 // Sanity check
559 assert!(trans.modules.len() == sess.opts.cg.codegen_units);
560
Stuart Pernsteinercf672852014-07-17 17:52:52561 unsafe {
562 configure_llvm(sess);
563 }
564
565 let tm = create_target_machine(sess);
566
567 // Figure out what we actually need to build.
568
569 let mut modules_config = ModuleConfig::new(tm, sess.opts.cg.passes.clone());
570 let mut metadata_config = ModuleConfig::new(tm, vec!());
571
572 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
573
574 // Save all versions of the bytecode if we're saving our temporaries.
575 if sess.opts.cg.save_temps {
576 modules_config.emit_no_opt_bc = true;
577 modules_config.emit_bc = true;
578 modules_config.emit_lto_bc = true;
579 metadata_config.emit_bc = true;
580 }
581
Stuart Pernsteinered476b02014-09-17 23:18:12582 // Emit bitcode files for the crate if we're emitting an rlib.
Stuart Pernsteinercf672852014-07-17 17:52:52583 // Whenever an rlib is created, the bitcode is inserted into the
584 // archive in order to allow LTO against it.
585 let needs_crate_bitcode =
586 sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
Niko Matsakisdc6e4142014-11-16 01:30:33587 sess.opts.output_types.contains(&config::OutputTypeExe);
Stuart Pernsteinercf672852014-07-17 17:52:52588 if needs_crate_bitcode {
589 modules_config.emit_bc = true;
590 }
591
592 for output_type in output_types.iter() {
593 match *output_type {
Niko Matsakisdc6e4142014-11-16 01:30:33594 config::OutputTypeBitcode => { modules_config.emit_bc = true; },
595 config::OutputTypeLlvmAssembly => { modules_config.emit_ir = true; },
596 config::OutputTypeAssembly => {
Stuart Pernsteinercf672852014-07-17 17:52:52597 modules_config.emit_asm = true;
598 // If we're not using the LLVM assembler, this function
599 // could be invoked specially with output_type_assembly, so
600 // in this case we still want the metadata object file.
Niko Matsakisdc6e4142014-11-16 01:30:33601 if !sess.opts.output_types.contains(&config::OutputTypeAssembly) {
Stuart Pernsteinercf672852014-07-17 17:52:52602 metadata_config.emit_obj = true;
Stuart Pernsteinere29aa142014-08-11 17:33:58603 }
Stuart Pernsteinercf672852014-07-17 17:52:52604 },
Niko Matsakisdc6e4142014-11-16 01:30:33605 config::OutputTypeObject => { modules_config.emit_obj = true; },
606 config::OutputTypeExe => {
Stuart Pernsteinercf672852014-07-17 17:52:52607 modules_config.emit_obj = true;
608 metadata_config.emit_obj = true;
609 },
Alex Crichton117984b2014-12-16 00:03:39610 config::OutputTypeDepInfo => {}
Stuart Pernsteinercf672852014-07-17 17:52:52611 }
612 }
613
614 modules_config.set_flags(sess, trans);
615 metadata_config.set_flags(sess, trans);
616
617
618 // Populate a buffer with a list of codegen tasks. Items are processed in
619 // LIFO order, just because it's a tiny bit simpler that way. (The order
620 // doesn't actually matter.)
621 let mut work_items = Vec::with_capacity(1 + trans.modules.len());
622
623 {
624 let work = build_work_item(sess,
625 trans.metadata_module,
626 metadata_config.clone(),
627 crate_output.clone(),
628 "metadata".to_string());
629 work_items.push(work);
630 }
631
632 for (index, mtrans) in trans.modules.iter().enumerate() {
633 let work = build_work_item(sess,
634 *mtrans,
635 modules_config.clone(),
636 crate_output.clone(),
637 format!("{}", index));
638 work_items.push(work);
639 }
640
641 // Process the work items, optionally using worker threads.
642 if sess.opts.cg.codegen_units == 1 {
643 run_work_singlethreaded(sess, trans.reachable.as_slice(), work_items);
Stuart Pernsteinercf672852014-07-17 17:52:52644 } else {
645 run_work_multithreaded(sess, work_items, sess.opts.cg.codegen_units);
Stuart Pernsteinercf672852014-07-17 17:52:52646 }
647
648 // All codegen is finished.
649 unsafe {
650 llvm::LLVMRustDisposeTargetMachine(tm);
651 }
652
653 // Produce final compile outputs.
654
Niko Matsakisdc6e4142014-11-16 01:30:33655 let copy_if_one_unit = |ext: &str, output_type: config::OutputType, keep_numbered: bool| {
Stuart Pernsteinercf672852014-07-17 17:52:52656 // Three cases:
657 if sess.opts.cg.codegen_units == 1 {
658 // 1) Only one codegen unit. In this case it's no difficulty
659 // to copy `foo.0.x` to `foo.x`.
660 fs::copy(&crate_output.with_extension(ext),
661 &crate_output.path(output_type)).unwrap();
Stuart Pernsteinered476b02014-09-17 23:18:12662 if !sess.opts.cg.save_temps && !keep_numbered {
Stuart Pernsteiner1b676fb2014-08-27 21:49:17663 // The user just wants `foo.x`, not `foo.0.x`.
664 remove(sess, &crate_output.with_extension(ext));
665 }
Stuart Pernsteinercf672852014-07-17 17:52:52666 } else {
667 if crate_output.single_output_file.is_some() {
668 // 2) Multiple codegen units, with `-o some_name`. We have
669 // no good solution for this case, so warn the user.
Stuart Pernsteiner1b676fb2014-08-27 21:49:17670 sess.warn(format!("ignoring -o because multiple .{} files were produced",
Stuart Pernsteinercf672852014-07-17 17:52:52671 ext).as_slice());
672 } else {
673 // 3) Multiple codegen units, but no `-o some_name`. We
674 // just leave the `foo.0.x` files in place.
675 // (We don't have to do any work in this case.)
676 }
677 }
678 };
679
680 let link_obj = |output_path: &Path| {
Stuart Pernsteiner6d2d47b2014-09-05 21:30:36681 // Running `ld -r` on a single input is kind of pointless.
682 if sess.opts.cg.codegen_units == 1 {
683 fs::copy(&crate_output.with_extension("0.o"),
684 output_path).unwrap();
685 // Leave the .0.o file around, to mimic the behavior of the normal
686 // code path.
687 return;
688 }
689
Stuart Pernsteiner4d9a4782014-08-29 19:46:04690 // Some builds of MinGW GCC will pass --force-exe-suffix to ld, which
691 // will automatically add a .exe extension if the extension is not
692 // already .exe or .dll. To ensure consistent behavior on Windows, we
693 // add the .exe suffix explicitly and then rename the output file to
694 // the desired path. This will give the correct behavior whether or
695 // not GCC adds --force-exe-suffix.
696 let windows_output_path =
Corey Richardson6b130e32014-07-23 18:56:36697 if sess.target.target.options.is_like_windows {
Stuart Pernsteiner4d9a4782014-08-29 19:46:04698 Some(output_path.with_extension("o.exe"))
699 } else {
700 None
701 };
702
Stuart Pernsteinerb5a0b702014-08-26 22:53:56703 let pname = get_cc_prog(sess);
704 let mut cmd = Command::new(pname.as_slice());
705
Corey Richardson6b130e32014-07-23 18:56:36706 cmd.args(sess.target.target.options.pre_link_args.as_slice());
Stuart Pernsteinerb5a0b702014-08-26 22:53:56707 cmd.arg("-nostdlib");
Stuart Pernsteinercf672852014-07-17 17:52:52708
709 for index in range(0, trans.modules.len()) {
710 cmd.arg(crate_output.with_extension(format!("{}.o", index).as_slice()));
711 }
712
Stuart Pernsteiner4d9a4782014-08-29 19:46:04713 cmd.arg("-r")
714 .arg("-o")
715 .arg(windows_output_path.as_ref().unwrap_or(output_path));
Stuart Pernsteinerb5a0b702014-08-26 22:53:56716
Corey Richardson6b130e32014-07-23 18:56:36717 cmd.args(sess.target.target.options.post_link_args.as_slice());
718
Stuart Pernsteinerb5a0b702014-08-26 22:53:56719 if (sess.opts.debugging_opts & config::PRINT_LINK_ARGS) != 0 {
720 println!("{}", &cmd);
721 }
722
Stuart Pernsteinercf672852014-07-17 17:52:52723 cmd.stdin(::std::io::process::Ignored)
724 .stdout(::std::io::process::InheritFd(1))
725 .stderr(::std::io::process::InheritFd(2));
Stuart Pernsteinerb5a0b702014-08-26 22:53:56726 match cmd.status() {
Markus Siemens53ac8522014-10-22 20:23:22727 Ok(status) => {
728 if !status.success() {
729 sess.err(format!("linking of {} with `{}` failed",
730 output_path.display(), cmd).as_slice());
731 sess.abort_if_errors();
732 }
733 },
Stuart Pernsteinerb5a0b702014-08-26 22:53:56734 Err(e) => {
735 sess.err(format!("could not exec the linker `{}`: {}",
736 pname,
737 e).as_slice());
738 sess.abort_if_errors();
739 },
740 }
Stuart Pernsteiner4d9a4782014-08-29 19:46:04741
742 match windows_output_path {
743 Some(ref windows_path) => {
744 fs::rename(windows_path, output_path).unwrap();
745 },
746 None => {
747 // The file is already named according to `output_path`.
748 }
749 }
Stuart Pernsteinercf672852014-07-17 17:52:52750 };
751
752 // Flag to indicate whether the user explicitly requested bitcode.
753 // Otherwise, we produced it only as a temporary output, and will need
754 // to get rid of it.
Stuart Pernsteinered476b02014-09-17 23:18:12755 let mut user_wants_bitcode = false;
Stuart Pernsteinercf672852014-07-17 17:52:52756 for output_type in output_types.iter() {
757 match *output_type {
Niko Matsakisdc6e4142014-11-16 01:30:33758 config::OutputTypeBitcode => {
Stuart Pernsteinered476b02014-09-17 23:18:12759 user_wants_bitcode = true;
760 // Copy to .bc, but always keep the .0.bc. There is a later
761 // check to figure out if we should delete .0.bc files, or keep
762 // them for making an rlib.
Niko Matsakisdc6e4142014-11-16 01:30:33763 copy_if_one_unit("0.bc", config::OutputTypeBitcode, true);
764 }
765 config::OutputTypeLlvmAssembly => {
766 copy_if_one_unit("0.ll", config::OutputTypeLlvmAssembly, false);
767 }
768 config::OutputTypeAssembly => {
769 copy_if_one_unit("0.s", config::OutputTypeAssembly, false);
770 }
771 config::OutputTypeObject => {
772 link_obj(&crate_output.path(config::OutputTypeObject));
773 }
774 config::OutputTypeExe => {
775 // If config::OutputTypeObject is already in the list, then
776 // `crate.o` will be handled by the config::OutputTypeObject case.
Stuart Pernsteinercf672852014-07-17 17:52:52777 // Otherwise, we need to create the temporary object so we
778 // can run the linker.
Niko Matsakisdc6e4142014-11-16 01:30:33779 if !sess.opts.output_types.contains(&config::OutputTypeObject) {
780 link_obj(&crate_output.temp_path(config::OutputTypeObject));
Stuart Pernsteinere29aa142014-08-11 17:33:58781 }
Niko Matsakisdc6e4142014-11-16 01:30:33782 }
Alex Crichton117984b2014-12-16 00:03:39783 config::OutputTypeDepInfo => {}
Stuart Pernsteinercf672852014-07-17 17:52:52784 }
785 }
Stuart Pernsteinered476b02014-09-17 23:18:12786 let user_wants_bitcode = user_wants_bitcode;
Stuart Pernsteinercf672852014-07-17 17:52:52787
788 // Clean up unwanted temporary files.
789
790 // We create the following files by default:
791 // - crate.0.bc
792 // - crate.0.o
793 // - crate.metadata.bc
794 // - crate.metadata.o
795 // - crate.o (linked from crate.##.o)
Stuart Pernsteiner1b676fb2014-08-27 21:49:17796 // - crate.bc (copied from crate.0.bc)
Stuart Pernsteinercf672852014-07-17 17:52:52797 // We may create additional files if requested by the user (through
798 // `-C save-temps` or `--emit=` flags).
799
800 if !sess.opts.cg.save_temps {
801 // Remove the temporary .0.o objects. If the user didn't
Stuart Pernsteinered476b02014-09-17 23:18:12802 // explicitly request bitcode (with --emit=bc), and the bitcode is not
803 // needed for building an rlib, then we must remove .0.bc as well.
804
805 // Specific rules for keeping .0.bc:
806 // - If we're building an rlib (`needs_crate_bitcode`), then keep
807 // it.
808 // - If the user requested bitcode (`user_wants_bitcode`), and
809 // codegen_units > 1, then keep it.
810 // - If the user requested bitcode but codegen_units == 1, then we
811 // can toss .0.bc because we copied it to .bc earlier.
812 // - If we're not building an rlib and the user didn't request
813 // bitcode, then delete .0.bc.
814 // If you change how this works, also update back::link::link_rlib,
815 // where .0.bc files are (maybe) deleted after making an rlib.
816 let keep_numbered_bitcode = needs_crate_bitcode ||
817 (user_wants_bitcode && sess.opts.cg.codegen_units > 1);
818
Stuart Pernsteinercf672852014-07-17 17:52:52819 for i in range(0, trans.modules.len()) {
820 if modules_config.emit_obj {
821 let ext = format!("{}.o", i);
822 remove(sess, &crate_output.with_extension(ext.as_slice()));
823 }
824
Stuart Pernsteinered476b02014-09-17 23:18:12825 if modules_config.emit_bc && !keep_numbered_bitcode {
Stuart Pernsteinercf672852014-07-17 17:52:52826 let ext = format!("{}.bc", i);
827 remove(sess, &crate_output.with_extension(ext.as_slice()));
Stuart Pernsteinere29aa142014-08-11 17:33:58828 }
829 }
830
Stuart Pernsteinered476b02014-09-17 23:18:12831 if metadata_config.emit_bc && !user_wants_bitcode {
Stuart Pernsteinercf672852014-07-17 17:52:52832 remove(sess, &crate_output.with_extension("metadata.bc"));
833 }
834 }
835
836 // We leave the following files around by default:
837 // - crate.o
838 // - crate.metadata.o
839 // - crate.bc
840 // These are used in linking steps and will be cleaned up afterward.
841
842 // FIXME: time_llvm_passes support - does this use a global context or
843 // something?
844 //if sess.time_llvm_passes() { llvm::LLVMRustPrintPassTimings(); }
845}
846
Niko Matsakis394f6842014-11-26 15:07:58847struct WorkItem {
848 mtrans: ModuleTranslation,
849 config: ModuleConfig,
850 output_names: OutputFilenames,
851 name_extra: String
852}
Stuart Pernsteinercf672852014-07-17 17:52:52853
854fn build_work_item(sess: &Session,
855 mtrans: ModuleTranslation,
856 config: ModuleConfig,
857 output_names: OutputFilenames,
Niko Matsakis394f6842014-11-26 15:07:58858 name_extra: String)
859 -> WorkItem
860{
Stuart Pernsteinercf672852014-07-17 17:52:52861 let mut config = config;
862 config.tm = create_target_machine(sess);
Niko Matsakis394f6842014-11-26 15:07:58863 WorkItem { mtrans: mtrans, config: config, output_names: output_names,
864 name_extra: name_extra }
865}
Stuart Pernsteinercf672852014-07-17 17:52:52866
Niko Matsakis394f6842014-11-26 15:07:58867fn execute_work_item(cgcx: &CodegenContext,
868 work_item: WorkItem) {
869 unsafe {
870 optimize_and_codegen(cgcx, work_item.mtrans, work_item.config,
871 work_item.name_extra, work_item.output_names);
Stuart Pernsteinercf672852014-07-17 17:52:52872 }
873}
874
875fn run_work_singlethreaded(sess: &Session,
876 reachable: &[String],
877 work_items: Vec<WorkItem>) {
878 let cgcx = CodegenContext::new_with_session(sess, reachable);
879 let mut work_items = work_items;
880
881 // Since we're running single-threaded, we can pass the session to
882 // the proc, allowing `optimize_and_codegen` to perform LTO.
883 for work in Unfold::new((), |_| work_items.pop()) {
Niko Matsakis394f6842014-11-26 15:07:58884 execute_work_item(&cgcx, work);
Stuart Pernsteinercf672852014-07-17 17:52:52885 }
886}
887
888fn run_work_multithreaded(sess: &Session,
889 work_items: Vec<WorkItem>,
890 num_workers: uint) {
891 // Run some workers to process the work items.
892 let work_items_arc = Arc::new(Mutex::new(work_items));
893 let mut diag_emitter = SharedEmitter::new();
894 let mut futures = Vec::with_capacity(num_workers);
895
896 for i in range(0, num_workers) {
897 let work_items_arc = work_items_arc.clone();
898 let diag_emitter = diag_emitter.clone();
Keegan McAllisterad9a1da2014-09-12 15:17:58899 let remark = sess.opts.cg.remark.clone();
Stuart Pernsteinercf672852014-07-17 17:52:52900
Niko Matsakis394f6842014-11-26 15:07:58901 let future = TaskBuilder::new().named(format!("codegen-{}", i)).try_future(move |:| {
Stuart Pernsteinercf672852014-07-17 17:52:52902 let diag_handler = mk_handler(box diag_emitter);
903
904 // Must construct cgcx inside the proc because it has non-Send
905 // fields.
Keegan McAllisterad9a1da2014-09-12 15:17:58906 let cgcx = CodegenContext {
907 lto_ctxt: None,
908 handler: &diag_handler,
909 remark: remark,
910 };
Stuart Pernsteinercf672852014-07-17 17:52:52911
912 loop {
913 // Avoid holding the lock for the entire duration of the match.
914 let maybe_work = work_items_arc.lock().pop();
915 match maybe_work {
916 Some(work) => {
Niko Matsakis394f6842014-11-26 15:07:58917 execute_work_item(&cgcx, work);
Stuart Pernsteinercf672852014-07-17 17:52:52918
919 // Make sure to fail the worker so the main thread can
920 // tell that there were errors.
921 cgcx.handler.abort_if_errors();
922 }
923 None => break,
Stuart Pernsteinere29aa142014-08-11 17:33:58924 }
Stuart Pernsteinere29aa142014-08-11 17:33:58925 }
926 });
Stuart Pernsteinercf672852014-07-17 17:52:52927 futures.push(future);
928 }
Stuart Pernsteinere29aa142014-08-11 17:33:58929
Steve Klabnik7828c3d2014-10-09 19:17:22930 let mut panicked = false;
Aaron Turonfc525ee2014-09-15 03:27:36931 for future in futures.into_iter() {
Alex Crichtonf1f6c122014-11-20 17:23:43932 match future.into_inner() {
Stuart Pernsteinercf672852014-07-17 17:52:52933 Ok(()) => {},
934 Err(_) => {
Steve Klabnik7828c3d2014-10-09 19:17:22935 panicked = true;
Stuart Pernsteinercf672852014-07-17 17:52:52936 },
937 }
938 // Display any new diagnostics.
939 diag_emitter.dump(sess.diagnostic().handler());
940 }
Steve Klabnik7828c3d2014-10-09 19:17:22941 if panicked {
942 sess.fatal("aborting due to worker thread panic");
Stuart Pernsteinere29aa142014-08-11 17:33:58943 }
944}
945
946pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
947 let pname = get_cc_prog(sess);
948 let mut cmd = Command::new(pname.as_slice());
949
Niko Matsakisdc6e4142014-11-16 01:30:33950 cmd.arg("-c").arg("-o").arg(outputs.path(config::OutputTypeObject))
951 .arg(outputs.temp_path(config::OutputTypeAssembly));
Stuart Pernsteinere29aa142014-08-11 17:33:58952 debug!("{}", &cmd);
953
954 match cmd.output() {
955 Ok(prog) => {
956 if !prog.status.success() {
957 sess.err(format!("linking with `{}` failed: {}",
958 pname,
959 prog.status).as_slice());
960 sess.note(format!("{}", &cmd).as_slice());
961 let mut note = prog.error.clone();
962 note.push_all(prog.output.as_slice());
963 sess.note(str::from_utf8(note.as_slice()).unwrap());
964 sess.abort_if_errors();
965 }
966 },
967 Err(e) => {
968 sess.err(format!("could not exec the linker `{}`: {}",
969 pname,
970 e).as_slice());
971 sess.abort_if_errors();
972 }
973 }
974}
975
976unsafe fn configure_llvm(sess: &Session) {
977 use std::sync::{Once, ONCE_INIT};
Alex Crichtondae48a02014-10-11 04:59:10978 static INIT: Once = ONCE_INIT;
Stuart Pernsteinere29aa142014-08-11 17:33:58979
980 // Copy what clang does by turning on loop vectorization at O2 and
981 // slp vectorization at O3
982 let vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
983 (sess.opts.optimize == config::Default ||
984 sess.opts.optimize == config::Aggressive);
985 let vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
986 sess.opts.optimize == config::Aggressive;
987
988 let mut llvm_c_strs = Vec::new();
989 let mut llvm_args = Vec::new();
990 {
991 let add = |arg: &str| {
992 let s = arg.to_c_str();
993 llvm_args.push(s.as_ptr());
994 llvm_c_strs.push(s);
995 };
996 add("rustc"); // fake program name
997 if vectorize_loop { add("-vectorize-loops"); }
998 if vectorize_slp { add("-vectorize-slp"); }
999 if sess.time_llvm_passes() { add("-time-passes"); }
1000 if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
1001
1002 for arg in sess.opts.cg.llvm_args.iter() {
1003 add((*arg).as_slice());
1004 }
1005 }
1006
1007 INIT.doit(|| {
1008 llvm::LLVMInitializePasses();
1009
1010 // Only initialize the platforms supported by Rust here, because
1011 // using --llvm-root will have multiple platforms that rustllvm
1012 // doesn't actually link to and it's pointless to put target info
1013 // into the registry that Rust cannot generate machine code for.
1014 llvm::LLVMInitializeX86TargetInfo();
1015 llvm::LLVMInitializeX86Target();
1016 llvm::LLVMInitializeX86TargetMC();
1017 llvm::LLVMInitializeX86AsmPrinter();
1018 llvm::LLVMInitializeX86AsmParser();
1019
1020 llvm::LLVMInitializeARMTargetInfo();
1021 llvm::LLVMInitializeARMTarget();
1022 llvm::LLVMInitializeARMTargetMC();
1023 llvm::LLVMInitializeARMAsmPrinter();
1024 llvm::LLVMInitializeARMAsmParser();
1025
1026 llvm::LLVMInitializeMipsTargetInfo();
1027 llvm::LLVMInitializeMipsTarget();
1028 llvm::LLVMInitializeMipsTargetMC();
1029 llvm::LLVMInitializeMipsAsmPrinter();
1030 llvm::LLVMInitializeMipsAsmParser();
1031
1032 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
1033 llvm_args.as_ptr());
1034 });
1035}
1036
1037unsafe fn populate_llvm_passes(fpm: llvm::PassManagerRef,
1038 mpm: llvm::PassManagerRef,
1039 llmod: ModuleRef,
1040 opt: llvm::CodeGenOptLevel,
1041 no_builtins: bool) {
1042 // Create the PassManagerBuilder for LLVM. We configure it with
1043 // reasonable defaults and prepare it to actually populate the pass
1044 // manager.
1045 let builder = llvm::LLVMPassManagerBuilderCreate();
1046 match opt {
1047 llvm::CodeGenLevelNone => {
1048 // Don't add lifetime intrinsics at O0
1049 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
1050 }
1051 llvm::CodeGenLevelLess => {
1052 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
1053 }
1054 // numeric values copied from clang
1055 llvm::CodeGenLevelDefault => {
1056 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
1057 225);
1058 }
1059 llvm::CodeGenLevelAggressive => {
1060 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
1061 275);
1062 }
1063 }
1064 llvm::LLVMPassManagerBuilderSetOptLevel(builder, opt as c_uint);
1065 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, no_builtins);
1066
1067 // Use the builder to populate the function/module pass managers.
1068 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(builder, fpm);
1069 llvm::LLVMPassManagerBuilderPopulateModulePassManager(builder, mpm);
1070 llvm::LLVMPassManagerBuilderDispose(builder);
1071
1072 match opt {
1073 llvm::CodeGenLevelDefault | llvm::CodeGenLevelAggressive => {
1074 "mergefunc".with_c_str(|s| llvm::LLVMRustAddPass(mpm, s));
1075 }
1076 _ => {}
1077 };
1078}