1 // Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
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.
12 use back::link::{get_linker, remove};
13 use session::config::{OutputFilenames, Passes, SomePasses, AllPasses};
15 use session::config::{self, OutputType};
17 use llvm::{ModuleRef, TargetMachineRef, PassManagerRef, DiagnosticInfoRef, ContextRef};
18 use llvm::SMDiagnosticRef;
19 use trans::{CrateTranslation, ModuleTranslation};
20 use util::common::time;
21 use util::common::path2cstr;
23 use syntax::diagnostic;
24 use syntax::diagnostic::{Emitter, Handler, Level};
26 use std::collections::HashMap;
27 use std::ffi::{CStr, CString};
29 use std::path::{Path, PathBuf};
32 use std::sync::{Arc, Mutex};
33 use std::sync::mpsc::channel;
35 use libc::{self, c_uint, c_int, c_void};
37 pub fn llvm_err(handler: &diagnostic::Handler, msg: String) -> ! {
39 let cstr = llvm::LLVMRustGetLastError();
40 if cstr == ptr::null() {
41 panic!(handler.fatal(&msg[..]));
43 let err = CStr::from_ptr(cstr).to_bytes();
44 let err = String::from_utf8_lossy(err).to_string();
45 libc::free(cstr as *mut _);
46 panic!(handler.fatal(&format!("{}: {}", &msg[..], &err[..])));
51 pub fn write_output_file(
52 handler: &diagnostic::Handler,
53 target: llvm::TargetMachineRef,
54 pm: llvm::PassManagerRef,
57 file_type: llvm::FileType) {
59 let output_c = path2cstr(output);
60 let result = llvm::LLVMRustWriteOutputFile(
61 target, pm, m, output_c.as_ptr(), file_type);
63 llvm_err(handler, format!("could not write output to {}", output.display()));
75 // We use an Arc instead of just returning a list of diagnostics from the
76 // child thread because we need to make sure that the messages are seen even
77 // if the child thread panics (for example, when `fatal` is called).
79 struct SharedEmitter {
80 buffer: Arc<Mutex<Vec<Diagnostic>>>,
84 fn new() -> SharedEmitter {
86 buffer: Arc::new(Mutex::new(Vec::new())),
90 fn dump(&mut self, handler: &Handler) {
91 let mut buffer = self.buffer.lock().unwrap();
92 for diag in &*buffer {
95 handler.emit_with_code(None,
111 impl Emitter for SharedEmitter {
112 fn emit(&mut self, cmsp: Option<(&codemap::CodeMap, codemap::Span)>,
113 msg: &str, code: Option<&str>, lvl: Level) {
114 assert!(cmsp.is_none(), "SharedEmitter doesn't support spans");
116 self.buffer.lock().unwrap().push(Diagnostic {
117 msg: msg.to_string(),
118 code: code.map(|s| s.to_string()),
123 fn custom_emit(&mut self, _cm: &codemap::CodeMap,
124 _sp: diagnostic::RenderSpan, _msg: &str, _lvl: Level) {
125 panic!("SharedEmitter doesn't support custom_emit");
130 // On android, we by default compile for armv7 processors. This enables
131 // things like double word CAS instructions (rather than emulating them)
132 // which are *far* more efficient. This is obviously undesirable in some
133 // cases, so if any sort of target feature is specified we don't append v7
134 // to the feature list.
136 // On iOS only armv7 and newer are supported. So it is useful to
137 // get all hardware potential via VFP3 (hardware floating point)
138 // and NEON (SIMD) instructions supported by LLVM.
139 // Note that without those flags various linking errors might
140 // arise as some of intrinsics are converted into function calls
141 // and nobody provides implementations those functions
142 fn target_feature(sess: &Session) -> String {
143 format!("{},{}", sess.target.target.options.features, sess.opts.cg.target_feature)
146 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
148 config::No => llvm::CodeGenLevelNone,
149 config::Less => llvm::CodeGenLevelLess,
150 config::Default => llvm::CodeGenLevelDefault,
151 config::Aggressive => llvm::CodeGenLevelAggressive,
155 pub fn create_target_machine(sess: &Session) -> TargetMachineRef {
156 let reloc_model_arg = match sess.opts.cg.relocation_model {
157 Some(ref s) => &s[..],
158 None => &sess.target.target.options.relocation_model[..],
160 let reloc_model = match reloc_model_arg {
161 "pic" => llvm::RelocPIC,
162 "static" => llvm::RelocStatic,
163 "default" => llvm::RelocDefault,
164 "dynamic-no-pic" => llvm::RelocDynamicNoPic,
166 sess.err(&format!("{:?} is not a valid relocation mode",
170 sess.abort_if_errors();
175 let opt_level = get_llvm_opt_level(sess.opts.optimize);
176 let use_softfp = sess.opts.cg.soft_float;
178 let any_library = sess.crate_types.borrow().iter().any(|ty| {
179 *ty != config::CrateTypeExecutable
182 let ffunction_sections = sess.target.target.options.function_sections;
183 let fdata_sections = ffunction_sections;
185 let code_model_arg = match sess.opts.cg.code_model {
186 Some(ref s) => &s[..],
187 None => &sess.target.target.options.code_model[..],
190 let code_model = match code_model_arg {
191 "default" => llvm::CodeModelDefault,
192 "small" => llvm::CodeModelSmall,
193 "kernel" => llvm::CodeModelKernel,
194 "medium" => llvm::CodeModelMedium,
195 "large" => llvm::CodeModelLarge,
197 sess.err(&format!("{:?} is not a valid code model",
201 sess.abort_if_errors();
206 let triple = &sess.target.target.llvm_target;
209 let triple = CString::new(triple.as_bytes()).unwrap();
210 let cpu = match sess.opts.cg.target_cpu {
212 None => &*sess.target.target.options.cpu
214 let cpu = CString::new(cpu.as_bytes()).unwrap();
215 let features = CString::new(target_feature(sess).as_bytes()).unwrap();
216 llvm::LLVMRustCreateTargetMachine(
217 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
221 true /* EnableSegstk */,
223 !any_library && reloc_model == llvm::RelocPIC,
230 llvm_err(sess.diagnostic().handler(),
231 format!("Could not create LLVM TargetMachine for triple: {}",
232 triple).to_string());
239 /// Module-specific configuration for `optimize_and_codegen`.
241 pub struct ModuleConfig {
242 /// LLVM TargetMachine to use for codegen.
243 tm: TargetMachineRef,
244 /// Names of additional optimization passes to run.
246 /// Some(level) to optimize at a certain level, or None to run
247 /// absolutely no optimizations (used for the metadata module).
248 opt_level: Option<llvm::CodeGenOptLevel>,
250 // Flags indicating which outputs to produce.
251 emit_no_opt_bc: bool,
258 // Miscellaneous flags. These are mostly copied from command-line
261 no_prepopulate_passes: bool,
264 vectorize_loop: bool,
266 merge_functions: bool,
269 unsafe impl Send for ModuleConfig { }
272 fn new(tm: TargetMachineRef, passes: Vec<String>) -> ModuleConfig {
278 emit_no_opt_bc: false,
286 no_prepopulate_passes: false,
289 vectorize_loop: false,
290 vectorize_slp: false,
291 merge_functions: false,
295 fn set_flags(&mut self, sess: &Session, trans: &CrateTranslation) {
296 self.no_verify = sess.no_verify();
297 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
298 self.no_builtins = trans.no_builtins;
299 self.time_passes = sess.time_passes();
301 // Copy what clang does by turning on loop vectorization at O2 and
302 // slp vectorization at O3. Otherwise configure other optimization aspects
303 // of this pass manager builder.
304 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
305 (sess.opts.optimize == config::Default ||
306 sess.opts.optimize == config::Aggressive);
307 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
308 sess.opts.optimize == config::Aggressive;
310 self.merge_functions = sess.opts.optimize == config::Default ||
311 sess.opts.optimize == config::Aggressive;
315 /// Additional resources used by optimize_and_codegen (not module specific)
316 struct 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,
322 // LLVM passes added by plugins.
323 plugin_passes: Vec<String>,
324 // LLVM optimizations for which we want to print remarks.
326 // Worker thread number
330 impl<'a> CodegenContext<'a> {
331 fn new_with_session(sess: &'a Session, reachable: &'a [String]) -> CodegenContext<'a> {
333 lto_ctxt: Some((sess, reachable)),
334 handler: sess.diagnostic().handler(),
335 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
336 remark: sess.opts.cg.remark.clone(),
342 struct HandlerFreeVars<'a> {
344 cgcx: &'a CodegenContext<'a>,
347 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext<'a>,
350 use syntax::codemap::ExpnId;
352 match cgcx.lto_ctxt {
354 sess.codemap().with_expn_info(ExpnId::from_u32(cookie), |info| match info {
355 Some(ei) => sess.span_err(ei.call_site, msg),
356 None => sess.err(msg),
361 cgcx.handler.err(msg);
362 cgcx.handler.note("build without -C codegen-units for more exact errors");
367 unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
370 let HandlerFreeVars { cgcx, .. } = *(user as *const HandlerFreeVars);
372 let msg = llvm::build_string(|s| llvm::LLVMWriteSMDiagnosticToString(diag, s))
373 .expect("non-UTF8 SMDiagnostic");
375 report_inline_asm(cgcx, &msg[..], cookie);
378 unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
379 let HandlerFreeVars { llcx, cgcx } = *(user as *const HandlerFreeVars);
381 match llvm::diagnostic::Diagnostic::unpack(info) {
382 llvm::diagnostic::InlineAsm(inline) => {
383 report_inline_asm(cgcx,
384 &*llvm::twine_to_string(inline.message),
388 llvm::diagnostic::Optimization(opt) => {
389 let pass_name = str::from_utf8(CStr::from_ptr(opt.pass_name).to_bytes())
391 .expect("got a non-UTF8 pass name from LLVM");
392 let enabled = match cgcx.remark {
394 SomePasses(ref v) => v.iter().any(|s| *s == pass_name),
398 let loc = llvm::debug_loc_to_string(llcx, opt.debug_loc);
399 cgcx.handler.note(&format!("optimization {} for {} at {}: {}",
402 if loc.is_empty() { "[unknown]" } else { &*loc },
403 llvm::twine_to_string(opt.message)));
411 // Unsafe due to LLVM calls.
412 unsafe fn optimize_and_codegen(cgcx: &CodegenContext,
413 mtrans: ModuleTranslation,
414 config: ModuleConfig,
416 output_names: OutputFilenames) {
417 let ModuleTranslation { llmod, llcx } = mtrans;
420 // llcx doesn't outlive this function, so we can put this on the stack.
421 let fv = HandlerFreeVars {
425 let fv = &fv as *const HandlerFreeVars as *mut c_void;
427 llvm::LLVMSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, fv);
428 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, fv);
430 if config.emit_no_opt_bc {
431 let ext = format!("{}.no-opt.bc", name_extra);
432 let out = output_names.with_extension(&ext);
433 let out = path2cstr(&out);
434 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
437 if config.opt_level.is_some() {
438 // Create the two optimizing pass managers. These mirror what clang
439 // does, and are by populated by LLVM's default PassManagerBuilder.
440 // Each manager has a different set of passes, but they also share
441 // some common passes.
442 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
443 let mpm = llvm::LLVMCreatePassManager();
445 // If we're verifying or linting, add them to the function pass
447 let addpass = |pass: &str| {
448 let pass = CString::new(pass).unwrap();
449 llvm::LLVMRustAddPass(fpm, pass.as_ptr())
452 if !config.no_verify { assert!(addpass("verify")); }
453 if !config.no_prepopulate_passes {
454 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
455 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
456 with_llvm_pmb(llmod, &config, &mut |b| {
457 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
458 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
462 for pass in &config.passes {
464 cgcx.handler.warn(&format!("unknown pass `{}`, ignoring",
469 for pass in &cgcx.plugin_passes {
471 cgcx.handler.err(&format!("a plugin asked for LLVM pass \
472 `{}` but LLVM does not \
473 recognize it", pass));
477 cgcx.handler.abort_if_errors();
479 // Finally, run the actual optimization passes
480 time(config.time_passes, &format!("llvm function passes [{}]", cgcx.worker), ||
481 llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
482 time(config.time_passes, &format!("llvm module passes [{}]", cgcx.worker), ||
483 llvm::LLVMRunPassManager(mpm, llmod));
485 // Deallocate managers that we're now done with
486 llvm::LLVMDisposePassManager(fpm);
487 llvm::LLVMDisposePassManager(mpm);
489 match cgcx.lto_ctxt {
490 Some((sess, reachable)) if sess.lto() => {
491 time(sess.time_passes(), "all lto passes", ||
492 lto::run(sess, llmod, tm, reachable, &config,
493 &name_extra, &output_names));
495 if config.emit_lto_bc {
496 let name = format!("{}.lto.bc", name_extra);
497 let out = output_names.with_extension(&name);
498 let out = path2cstr(&out);
499 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
506 // A codegen-specific pass manager is used to generate object
507 // files for an LLVM module.
509 // Apparently each of these pass managers is a one-shot kind of
510 // thing, so we create a new one for each type of output. The
511 // pass manager passed to the closure should be ensured to not
512 // escape the closure itself, and the manager should only be
514 unsafe fn with_codegen<F>(tm: TargetMachineRef,
518 F: FnOnce(PassManagerRef),
520 let cpm = llvm::LLVMCreatePassManager();
521 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
522 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
527 let ext = format!("{}.bc", name_extra);
528 let out = output_names.with_extension(&ext);
529 let out = path2cstr(&out);
530 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
533 time(config.time_passes, &format!("codegen passes [{}]", cgcx.worker), || {
535 let ext = format!("{}.ll", name_extra);
536 let out = output_names.with_extension(&ext);
537 let out = path2cstr(&out);
538 with_codegen(tm, llmod, config.no_builtins, |cpm| {
539 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr());
540 llvm::LLVMDisposePassManager(cpm);
545 let path = output_names.with_extension(&format!("{}.s", name_extra));
546 with_codegen(tm, llmod, config.no_builtins, |cpm| {
547 write_output_file(cgcx.handler, tm, cpm, llmod, &path,
548 llvm::AssemblyFileType);
553 let path = output_names.with_extension(&format!("{}.o", name_extra));
554 with_codegen(tm, llmod, config.no_builtins, |cpm| {
555 write_output_file(cgcx.handler, tm, cpm, llmod, &path, llvm::ObjectFileType);
560 llvm::LLVMDisposeModule(llmod);
561 llvm::LLVMContextDispose(llcx);
562 llvm::LLVMRustDisposeTargetMachine(tm);
565 pub fn run_passes(sess: &Session,
566 trans: &CrateTranslation,
567 output_types: &HashMap<OutputType, Option<PathBuf>>,
568 crate_output: &OutputFilenames) {
569 // It's possible that we have `codegen_units > 1` but only one item in
570 // `trans.modules`. We could theoretically proceed and do LTO in that
571 // case, but it would be confusing to have the validity of
572 // `-Z lto -C codegen-units=2` depend on details of the crate being
573 // compiled, so we complain regardless.
574 if sess.lto() && sess.opts.cg.codegen_units > 1 {
575 // This case is impossible to handle because LTO expects to be able
576 // to combine the entire crate and all its dependencies into a
577 // single compilation unit, but each codegen unit is in a separate
578 // LLVM context, so they can't easily be combined.
579 sess.fatal("can't perform LTO when using multiple codegen units");
583 assert!(trans.modules.len() == sess.opts.cg.codegen_units);
585 let tm = create_target_machine(sess);
587 // Figure out what we actually need to build.
589 let mut modules_config = ModuleConfig::new(tm, sess.opts.cg.passes.clone());
590 let mut metadata_config = ModuleConfig::new(tm, vec!());
592 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
594 // Save all versions of the bytecode if we're saving our temporaries.
595 if sess.opts.cg.save_temps {
596 modules_config.emit_no_opt_bc = true;
597 modules_config.emit_bc = true;
598 modules_config.emit_lto_bc = true;
599 metadata_config.emit_bc = true;
602 // Emit bitcode files for the crate if we're emitting an rlib.
603 // Whenever an rlib is created, the bitcode is inserted into the
604 // archive in order to allow LTO against it.
605 let needs_crate_bitcode =
606 sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
607 sess.opts.output_types.contains_key(&OutputType::Exe);
608 let needs_crate_object =
609 sess.opts.output_types.contains_key(&OutputType::Exe);
610 if needs_crate_bitcode {
611 modules_config.emit_bc = true;
614 for output_type in output_types.keys() {
616 OutputType::Bitcode => { modules_config.emit_bc = true; },
617 OutputType::LlvmAssembly => { modules_config.emit_ir = true; },
618 OutputType::Assembly => {
619 modules_config.emit_asm = true;
620 // If we're not using the LLVM assembler, this function
621 // could be invoked specially with output_type_assembly, so
622 // in this case we still want the metadata object file.
623 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
624 metadata_config.emit_obj = true;
627 OutputType::Object => { modules_config.emit_obj = true; },
629 modules_config.emit_obj = true;
630 metadata_config.emit_obj = true;
632 OutputType::DepInfo => {}
636 modules_config.set_flags(sess, trans);
637 metadata_config.set_flags(sess, trans);
640 // Populate a buffer with a list of codegen threads. Items are processed in
641 // LIFO order, just because it's a tiny bit simpler that way. (The order
642 // doesn't actually matter.)
643 let mut work_items = Vec::with_capacity(1 + trans.modules.len());
646 let work = build_work_item(sess,
647 trans.metadata_module,
648 metadata_config.clone(),
649 crate_output.clone(),
650 "metadata".to_string());
651 work_items.push(work);
654 for (index, mtrans) in trans.modules.iter().enumerate() {
655 let work = build_work_item(sess,
657 modules_config.clone(),
658 crate_output.clone(),
659 format!("{}", index));
660 work_items.push(work);
663 // Process the work items, optionally using worker threads.
664 if sess.opts.cg.codegen_units == 1 {
665 run_work_singlethreaded(sess, &trans.reachable, work_items);
667 run_work_multithreaded(sess, work_items, sess.opts.cg.codegen_units);
670 // All codegen is finished.
672 llvm::LLVMRustDisposeTargetMachine(tm);
675 // Produce final compile outputs.
676 let copy_gracefully = |from: &Path, to: &Path| {
677 if let Err(e) = fs::copy(from, to) {
678 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
682 let copy_if_one_unit = |ext: &str,
683 output_type: OutputType,
684 keep_numbered: bool| {
685 if sess.opts.cg.codegen_units == 1 {
686 // 1) Only one codegen unit. In this case it's no difficulty
687 // to copy `foo.0.x` to `foo.x`.
688 copy_gracefully(&crate_output.with_extension(ext),
689 &crate_output.path(output_type));
690 if !sess.opts.cg.save_temps && !keep_numbered {
691 // The user just wants `foo.x`, not `foo.0.x`.
692 remove(sess, &crate_output.with_extension(ext));
694 } else if crate_output.outputs.contains_key(&output_type) {
695 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
696 // no good solution for this case, so warn the user.
697 sess.warn(&format!("ignoring emit path because multiple .{} files \
698 were produced", ext));
699 } else if crate_output.single_output_file.is_some() {
700 // 3) Multiple codegen units, with `-o some_name`. We have
701 // no good solution for this case, so warn the user.
702 sess.warn(&format!("ignoring -o because multiple .{} files \
703 were produced", ext));
705 // 4) Multiple codegen units, but no explicit name. We
706 // just leave the `foo.0.x` files in place.
707 // (We don't have to do any work in this case.)
711 // Flag to indicate whether the user explicitly requested bitcode.
712 // Otherwise, we produced it only as a temporary output, and will need
714 let mut user_wants_bitcode = false;
715 let mut user_wants_objects = false;
716 for output_type in output_types.keys() {
718 OutputType::Bitcode => {
719 user_wants_bitcode = true;
720 // Copy to .bc, but always keep the .0.bc. There is a later
721 // check to figure out if we should delete .0.bc files, or keep
722 // them for making an rlib.
723 copy_if_one_unit("0.bc", OutputType::Bitcode, true);
725 OutputType::LlvmAssembly => {
726 copy_if_one_unit("0.ll", OutputType::LlvmAssembly, false);
728 OutputType::Assembly => {
729 copy_if_one_unit("0.s", OutputType::Assembly, false);
731 OutputType::Object => {
732 user_wants_objects = true;
733 copy_if_one_unit("0.o", OutputType::Object, true);
736 OutputType::DepInfo => {}
739 let user_wants_bitcode = user_wants_bitcode;
741 // Clean up unwanted temporary files.
743 // We create the following files by default:
746 // - crate.metadata.bc
747 // - crate.metadata.o
748 // - crate.o (linked from crate.##.o)
749 // - crate.bc (copied from crate.0.bc)
750 // We may create additional files if requested by the user (through
751 // `-C save-temps` or `--emit=` flags).
753 if !sess.opts.cg.save_temps {
754 // Remove the temporary .0.o objects. If the user didn't
755 // explicitly request bitcode (with --emit=bc), and the bitcode is not
756 // needed for building an rlib, then we must remove .0.bc as well.
758 // Specific rules for keeping .0.bc:
759 // - If we're building an rlib (`needs_crate_bitcode`), then keep
761 // - If the user requested bitcode (`user_wants_bitcode`), and
762 // codegen_units > 1, then keep it.
763 // - If the user requested bitcode but codegen_units == 1, then we
764 // can toss .0.bc because we copied it to .bc earlier.
765 // - If we're not building an rlib and the user didn't request
766 // bitcode, then delete .0.bc.
767 // If you change how this works, also update back::link::link_rlib,
768 // where .0.bc files are (maybe) deleted after making an rlib.
769 let keep_numbered_bitcode = needs_crate_bitcode ||
770 (user_wants_bitcode && sess.opts.cg.codegen_units > 1);
772 let keep_numbered_objects = needs_crate_object ||
773 (user_wants_objects && sess.opts.cg.codegen_units > 1);
775 for i in 0..trans.modules.len() {
776 if modules_config.emit_obj && !keep_numbered_objects {
777 let ext = format!("{}.o", i);
778 remove(sess, &crate_output.with_extension(&ext));
781 if modules_config.emit_bc && !keep_numbered_bitcode {
782 let ext = format!("{}.bc", i);
783 remove(sess, &crate_output.with_extension(&ext));
787 if metadata_config.emit_bc && !user_wants_bitcode {
788 remove(sess, &crate_output.with_extension("metadata.bc"));
792 // We leave the following files around by default:
794 // - crate.metadata.o
796 // These are used in linking steps and will be cleaned up afterward.
798 // FIXME: time_llvm_passes support - does this use a global context or
800 if sess.opts.cg.codegen_units == 1 && sess.time_llvm_passes() {
801 unsafe { llvm::LLVMRustPrintPassTimings(); }
806 mtrans: ModuleTranslation,
807 config: ModuleConfig,
808 output_names: OutputFilenames,
812 fn build_work_item(sess: &Session,
813 mtrans: ModuleTranslation,
814 config: ModuleConfig,
815 output_names: OutputFilenames,
819 let mut config = config;
820 config.tm = create_target_machine(sess);
821 WorkItem { mtrans: mtrans, config: config, output_names: output_names,
822 name_extra: name_extra }
825 fn execute_work_item(cgcx: &CodegenContext,
826 work_item: WorkItem) {
828 optimize_and_codegen(cgcx, work_item.mtrans, work_item.config,
829 work_item.name_extra, work_item.output_names);
833 fn run_work_singlethreaded(sess: &Session,
834 reachable: &[String],
835 work_items: Vec<WorkItem>) {
836 let cgcx = CodegenContext::new_with_session(sess, reachable);
838 // Since we're running single-threaded, we can pass the session to
839 // the proc, allowing `optimize_and_codegen` to perform LTO.
840 for work in work_items.into_iter().rev() {
841 execute_work_item(&cgcx, work);
845 fn run_work_multithreaded(sess: &Session,
846 work_items: Vec<WorkItem>,
847 num_workers: usize) {
848 // Run some workers to process the work items.
849 let work_items_arc = Arc::new(Mutex::new(work_items));
850 let mut diag_emitter = SharedEmitter::new();
851 let mut futures = Vec::with_capacity(num_workers);
853 for i in 0..num_workers {
854 let work_items_arc = work_items_arc.clone();
855 let diag_emitter = diag_emitter.clone();
856 let plugin_passes = sess.plugin_llvm_passes.borrow().clone();
857 let remark = sess.opts.cg.remark.clone();
859 let (tx, rx) = channel();
860 let mut tx = Some(tx);
863 thread::Builder::new().name(format!("codegen-{}", i)).spawn(move || {
864 let diag_handler = Handler::with_emitter(true, box diag_emitter);
866 // Must construct cgcx inside the proc because it has non-Send
868 let cgcx = CodegenContext {
870 handler: &diag_handler,
871 plugin_passes: plugin_passes,
877 // Avoid holding the lock for the entire duration of the match.
878 let maybe_work = work_items_arc.lock().unwrap().pop();
881 execute_work_item(&cgcx, work);
883 // Make sure to fail the worker so the main thread can
884 // tell that there were errors.
885 cgcx.handler.abort_if_errors();
891 tx.take().unwrap().send(()).unwrap();
895 let mut panicked = false;
903 // Display any new diagnostics.
904 diag_emitter.dump(sess.diagnostic().handler());
907 sess.fatal("aborting due to worker thread panic");
911 pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
912 let (pname, mut cmd) = get_linker(sess);
914 cmd.arg("-c").arg("-o").arg(&outputs.path(OutputType::Object))
915 .arg(&outputs.temp_path(OutputType::Assembly));
920 if !prog.status.success() {
921 sess.err(&format!("linking with `{}` failed: {}",
924 sess.note(&format!("{:?}", &cmd));
925 let mut note = prog.stderr.clone();
926 note.push_all(&prog.stdout);
927 sess.note(str::from_utf8(¬e[..]).unwrap());
928 sess.abort_if_errors();
932 sess.err(&format!("could not exec the linker `{}`: {}", pname, e));
933 sess.abort_if_errors();
938 pub unsafe fn configure_llvm(sess: &Session) {
939 let mut llvm_c_strs = Vec::new();
940 let mut llvm_args = Vec::new();
943 let mut add = |arg: &str| {
944 let s = CString::new(arg).unwrap();
945 llvm_args.push(s.as_ptr());
948 add("rustc"); // fake program name
949 if sess.time_llvm_passes() { add("-time-passes"); }
950 if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
952 // FIXME #21627 disable faulty FastISel on AArch64 (even for -O0)
953 if sess.target.target.arch == "aarch64" { add("-fast-isel=0"); }
955 for arg in &sess.opts.cg.llvm_args {
960 llvm::LLVMInitializePasses();
962 // Only initialize the platforms supported by Rust here, because
963 // using --llvm-root will have multiple platforms that rustllvm
964 // doesn't actually link to and it's pointless to put target info
965 // into the registry that Rust cannot generate machine code for.
966 llvm::LLVMInitializeX86TargetInfo();
967 llvm::LLVMInitializeX86Target();
968 llvm::LLVMInitializeX86TargetMC();
969 llvm::LLVMInitializeX86AsmPrinter();
970 llvm::LLVMInitializeX86AsmParser();
972 llvm::LLVMInitializeARMTargetInfo();
973 llvm::LLVMInitializeARMTarget();
974 llvm::LLVMInitializeARMTargetMC();
975 llvm::LLVMInitializeARMAsmPrinter();
976 llvm::LLVMInitializeARMAsmParser();
978 llvm::LLVMInitializeAArch64TargetInfo();
979 llvm::LLVMInitializeAArch64Target();
980 llvm::LLVMInitializeAArch64TargetMC();
981 llvm::LLVMInitializeAArch64AsmPrinter();
982 llvm::LLVMInitializeAArch64AsmParser();
984 llvm::LLVMInitializeMipsTargetInfo();
985 llvm::LLVMInitializeMipsTarget();
986 llvm::LLVMInitializeMipsTargetMC();
987 llvm::LLVMInitializeMipsAsmPrinter();
988 llvm::LLVMInitializeMipsAsmParser();
990 llvm::LLVMInitializePowerPCTargetInfo();
991 llvm::LLVMInitializePowerPCTarget();
992 llvm::LLVMInitializePowerPCTargetMC();
993 llvm::LLVMInitializePowerPCAsmPrinter();
994 llvm::LLVMInitializePowerPCAsmParser();
996 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
1000 pub unsafe fn with_llvm_pmb(llmod: ModuleRef,
1001 config: &ModuleConfig,
1002 f: &mut FnMut(llvm::PassManagerBuilderRef)) {
1003 // Create the PassManagerBuilder for LLVM. We configure it with
1004 // reasonable defaults and prepare it to actually populate the pass
1006 let builder = llvm::LLVMPassManagerBuilderCreate();
1007 let opt = config.opt_level.unwrap_or(llvm::CodeGenLevelNone);
1009 llvm::LLVMRustConfigurePassManagerBuilder(builder, opt,
1010 config.merge_functions,
1011 config.vectorize_slp,
1012 config.vectorize_loop);
1014 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
1016 // Here we match what clang does (kinda). For O0 we only inline
1017 // always-inline functions (but don't add lifetime intrinsics), at O1 we
1018 // inline with lifetime intrinsics, and O2+ we add an inliner with a
1019 // thresholds copied from clang.
1021 llvm::CodeGenLevelNone => {
1022 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
1024 llvm::CodeGenLevelLess => {
1025 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
1027 llvm::CodeGenLevelDefault => {
1028 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1030 llvm::CodeGenLevelAggressive => {
1031 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
1036 llvm::LLVMPassManagerBuilderDispose(builder);