2 use crate::back::lto::ThinBuffer;
3 use crate::back::profiling::{
4 selfprofile_after_pass_callback, selfprofile_before_pass_callback, LlvmSelfProfiler,
9 use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
11 use crate::type_::Type;
12 use crate::LlvmCodegenBackend;
13 use crate::ModuleLlvm;
14 use rustc_codegen_ssa::back::write::{BitcodeSection, CodegenContext, EmitObj, ModuleConfig};
15 use rustc_codegen_ssa::traits::*;
16 use rustc_codegen_ssa::{CompiledModule, ModuleCodegen};
17 use rustc_data_structures::small_c_str::SmallCStr;
18 use rustc_errors::{FatalError, Handler, Level};
19 use rustc_fs_util::{link_or_copy, path_to_c_string};
20 use rustc_hir::def_id::LOCAL_CRATE;
21 use rustc_middle::bug;
22 use rustc_middle::ty::TyCtxt;
23 use rustc_session::config::{self, Lto, OutputType, Passes, SanitizerSet, SwitchWithOptPath};
24 use rustc_session::Session;
25 use rustc_span::symbol::sym;
26 use rustc_span::InnerSpan;
27 use rustc_target::spec::{CodeModel, RelocModel};
30 use libc::{c_char, c_int, c_uint, c_void, size_t};
31 use std::ffi::CString;
33 use std::io::{self, Write};
34 use std::path::{Path, PathBuf};
39 pub fn llvm_err(handler: &rustc_errors::Handler, msg: &str) -> FatalError {
40 match llvm::last_error() {
41 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
42 None => handler.fatal(&msg),
46 pub fn write_output_file(
47 handler: &rustc_errors::Handler,
48 target: &'ll llvm::TargetMachine,
49 pm: &llvm::PassManager<'ll>,
52 file_type: llvm::FileType,
53 ) -> Result<(), FatalError> {
55 let output_c = path_to_c_string(output);
56 let result = llvm::LLVMRustWriteOutputFile(target, pm, m, output_c.as_ptr(), file_type);
57 result.into_result().map_err(|()| {
58 let msg = format!("could not write output to {}", output.display());
59 llvm_err(handler, &msg)
64 pub fn create_informational_target_machine(sess: &Session) -> &'static mut llvm::TargetMachine {
65 target_machine_factory(sess, config::OptLevel::No)()
66 .unwrap_or_else(|err| llvm_err(sess.diagnostic(), &err).raise())
69 pub fn create_target_machine(tcx: TyCtxt<'_>) -> &'static mut llvm::TargetMachine {
70 target_machine_factory(&tcx.sess, tcx.backend_optimization_level(LOCAL_CRATE))()
71 .unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise())
74 pub fn to_llvm_opt_settings(
75 cfg: config::OptLevel,
76 ) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
77 use self::config::OptLevel::*;
79 No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
80 Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
81 Default => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
82 Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
83 Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
84 SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
88 fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel {
89 use config::OptLevel::*;
91 No => llvm::PassBuilderOptLevel::O0,
92 Less => llvm::PassBuilderOptLevel::O1,
93 Default => llvm::PassBuilderOptLevel::O2,
94 Aggressive => llvm::PassBuilderOptLevel::O3,
95 Size => llvm::PassBuilderOptLevel::Os,
96 SizeMin => llvm::PassBuilderOptLevel::Oz,
100 fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
101 match relocation_model {
102 RelocModel::Static => llvm::RelocModel::Static,
103 RelocModel::Pic => llvm::RelocModel::PIC,
104 RelocModel::DynamicNoPic => llvm::RelocModel::DynamicNoPic,
105 RelocModel::Ropi => llvm::RelocModel::ROPI,
106 RelocModel::Rwpi => llvm::RelocModel::RWPI,
107 RelocModel::RopiRwpi => llvm::RelocModel::ROPI_RWPI,
111 fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeModel {
113 Some(CodeModel::Tiny) => llvm::CodeModel::Tiny,
114 Some(CodeModel::Small) => llvm::CodeModel::Small,
115 Some(CodeModel::Kernel) => llvm::CodeModel::Kernel,
116 Some(CodeModel::Medium) => llvm::CodeModel::Medium,
117 Some(CodeModel::Large) => llvm::CodeModel::Large,
118 None => llvm::CodeModel::None,
122 pub fn target_machine_factory(
124 optlvl: config::OptLevel,
125 ) -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
126 let reloc_model = to_llvm_relocation_model(sess.relocation_model());
128 let (opt_level, _) = to_llvm_opt_settings(optlvl);
129 let use_softfp = sess.opts.cg.soft_float;
131 let ffunction_sections =
132 sess.opts.debugging_opts.function_sections.unwrap_or(sess.target.options.function_sections);
133 let fdata_sections = ffunction_sections;
135 let code_model = to_llvm_code_model(sess.code_model());
137 let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
138 let mut singlethread = sess.target.options.singlethread;
140 // On the wasm target once the `atomics` feature is enabled that means that
141 // we're no longer single-threaded, or otherwise we don't want LLVM to
142 // lower atomic operations to single-threaded operations.
144 && sess.target.llvm_target.contains("wasm32")
145 && sess.target_features.contains(&sym::atomics)
147 singlethread = false;
150 let triple = SmallCStr::new(&sess.target.llvm_target);
151 let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
152 let features = features.join(",");
153 let features = CString::new(features).unwrap();
154 let abi = SmallCStr::new(&sess.target.options.llvm_abiname);
155 let trap_unreachable = sess.target.options.trap_unreachable;
156 let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
158 let asm_comments = sess.asm_comments();
159 let relax_elf_relocations = sess
162 .relax_elf_relocations
163 .unwrap_or(sess.target.options.relax_elf_relocations);
165 let use_init_array = !sess
169 .unwrap_or(sess.target.options.use_ctors_section);
173 llvm::LLVMRustCreateTargetMachine(
187 emit_stack_size_section,
188 relax_elf_relocations,
194 format!("Could not create LLVM TargetMachine for triple: {}", triple.to_str().unwrap())
199 pub(crate) fn save_temp_bitcode(
200 cgcx: &CodegenContext<LlvmCodegenBackend>,
201 module: &ModuleCodegen<ModuleLlvm>,
204 if !cgcx.save_temps {
208 let ext = format!("{}.bc", name);
209 let cgu = Some(&module.name[..]);
210 let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
211 let cstr = path_to_c_string(&path);
212 let llmod = module.module_llvm.llmod();
213 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
217 pub struct DiagnosticHandlers<'a> {
218 data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
219 llcx: &'a llvm::Context,
222 impl<'a> DiagnosticHandlers<'a> {
224 cgcx: &'a CodegenContext<LlvmCodegenBackend>,
225 handler: &'a Handler,
226 llcx: &'a llvm::Context,
228 let data = Box::into_raw(Box::new((cgcx, handler)));
230 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data.cast());
231 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data.cast());
233 DiagnosticHandlers { data, llcx }
237 impl<'a> Drop for DiagnosticHandlers<'a> {
239 use std::ptr::null_mut;
241 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
242 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
243 drop(Box::from_raw(self.data));
248 fn report_inline_asm(
249 cgcx: &CodegenContext<LlvmCodegenBackend>,
251 level: llvm::DiagnosticLevel,
253 source: Option<(String, Vec<InnerSpan>)>,
255 // In LTO build we may get srcloc values from other crates which are invalid
256 // since they use a different source map. To be safe we just suppress these
258 if matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
261 let level = match level {
262 llvm::DiagnosticLevel::Error => Level::Error,
263 llvm::DiagnosticLevel::Warning => Level::Warning,
264 llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
266 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg, level, source);
269 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic, user: *const c_void, cookie: c_uint) {
273 let (cgcx, _) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
275 // Recover the post-substitution assembly code from LLVM for better
277 let mut have_source = false;
278 let mut buffer = String::new();
279 let mut level = llvm::DiagnosticLevel::Error;
281 let mut ranges = [0; 8];
282 let mut num_ranges = ranges.len() / 2;
283 let msg = llvm::build_string(|msg| {
284 buffer = llvm::build_string(|buffer| {
285 have_source = llvm::LLVMRustUnpackSMDiagnostic(
295 .expect("non-UTF8 inline asm");
297 .expect("non-UTF8 SMDiagnostic");
299 let source = have_source.then(|| {
300 let mut spans = vec![InnerSpan::new(loc as usize, loc as usize)];
301 for i in 0..num_ranges {
302 spans.push(InnerSpan::new(ranges[i * 2] as usize, ranges[i * 2 + 1] as usize));
307 report_inline_asm(cgcx, msg, level, cookie, source);
310 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
314 let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
316 match llvm::diagnostic::Diagnostic::unpack(info) {
317 llvm::diagnostic::InlineAsm(inline) => {
320 llvm::twine_to_string(inline.message),
327 llvm::diagnostic::Optimization(opt) => {
328 let enabled = match cgcx.remark {
330 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
334 diag_handler.note_without_error(&format!(
335 "optimization {} for {} at {}:{}:{}: {}",
345 llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
346 let msg = llvm::build_string(|s| {
347 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
349 .expect("non-UTF8 diagnostic");
350 diag_handler.warn(&msg);
352 llvm::diagnostic::Unsupported(diagnostic_ref) => {
353 let msg = llvm::build_string(|s| {
354 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
356 .expect("non-UTF8 diagnostic");
357 diag_handler.err(&msg);
359 llvm::diagnostic::UnknownDiagnostic(..) => {}
363 fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
364 match config.pgo_gen {
365 SwitchWithOptPath::Enabled(ref opt_dir_path) => {
366 let path = if let Some(dir_path) = opt_dir_path {
367 dir_path.join("default_%m.profraw")
369 PathBuf::from("default_%m.profraw")
372 Some(CString::new(format!("{}", path.display())).unwrap())
374 SwitchWithOptPath::Disabled => None,
378 fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
382 .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
385 pub(crate) fn should_use_new_llvm_pass_manager(config: &ModuleConfig) -> bool {
386 // We only support the new pass manager starting with LLVM 9.
387 if llvm_util::get_major_version() < 9 {
391 // The new pass manager is disabled by default.
392 config.new_llvm_pass_manager
395 pub(crate) unsafe fn optimize_with_new_llvm_pass_manager(
396 cgcx: &CodegenContext<LlvmCodegenBackend>,
397 module: &ModuleCodegen<ModuleLlvm>,
398 config: &ModuleConfig,
399 opt_level: config::OptLevel,
400 opt_stage: llvm::OptStage,
403 opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
404 let using_thin_buffers = opt_stage == llvm::OptStage::PreLinkThinLTO || config.bitcode_needed();
405 let pgo_gen_path = get_pgo_gen_path(config);
406 let pgo_use_path = get_pgo_use_path(config);
407 let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
408 // Sanitizer instrumentation is only inserted during the pre-link optimization stage.
409 let sanitizer_options = if !is_lto {
410 Some(llvm::SanitizerOptions {
411 sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
412 sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
413 sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
414 sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
415 sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
416 sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
422 let llvm_selfprofiler = if cgcx.prof.llvm_recording_enabled() {
423 let mut llvm_profiler = LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap());
424 &mut llvm_profiler as *mut _ as *mut c_void
429 // FIXME: NewPM doesn't provide a facility to pass custom InlineParams.
430 // We would have to add upstream support for this first, before we can support
431 // config.inline_threshold and our more aggressive default thresholds.
432 // FIXME: NewPM uses an different and more explicit way to textually represent
433 // pass pipelines. It would probably make sense to expose this, but it would
434 // require a different format than the current -C passes.
435 llvm::LLVMRustOptimizeWithNewPassManager(
436 module.module_llvm.llmod(),
437 &*module.module_llvm.tm,
438 to_pass_builder_opt_level(opt_level),
440 config.no_prepopulate_passes,
441 config.verify_llvm_ir,
443 config.merge_functions,
445 config.vectorize_slp,
446 config.vectorize_loop,
448 config.emit_lifetime_markers,
449 sanitizer_options.as_ref(),
450 pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
451 pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
453 selfprofile_before_pass_callback,
454 selfprofile_after_pass_callback,
458 // Unsafe due to LLVM calls.
459 pub(crate) unsafe fn optimize(
460 cgcx: &CodegenContext<LlvmCodegenBackend>,
461 diag_handler: &Handler,
462 module: &ModuleCodegen<ModuleLlvm>,
463 config: &ModuleConfig,
464 ) -> Result<(), FatalError> {
465 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_optimize", &module.name[..]);
467 let llmod = module.module_llvm.llmod();
468 let llcx = &*module.module_llvm.llcx;
469 let tm = &*module.module_llvm.tm;
470 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
472 let module_name = module.name.clone();
473 let module_name = Some(&module_name[..]);
475 if config.emit_no_opt_bc {
476 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
477 let out = path_to_c_string(&out);
478 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
481 if let Some(opt_level) = config.opt_level {
482 if should_use_new_llvm_pass_manager(config) {
483 let opt_stage = match cgcx.lto {
484 Lto::Fat => llvm::OptStage::PreLinkFatLTO,
485 Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
486 _ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO,
487 _ => llvm::OptStage::PreLinkNoLTO,
489 optimize_with_new_llvm_pass_manager(cgcx, module, config, opt_level, opt_stage);
493 if cgcx.prof.llvm_recording_enabled() {
495 .warn("`-Z self-profile-events = llvm` requires `-Z new-llvm-pass-manager`");
498 // Create the two optimizing pass managers. These mirror what clang
499 // does, and are by populated by LLVM's default PassManagerBuilder.
500 // Each manager has a different set of passes, but they also share
501 // some common passes.
502 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
503 let mpm = llvm::LLVMCreatePassManager();
506 let find_pass = |pass_name: &str| {
507 let pass_name = SmallCStr::new(pass_name);
508 llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr())
511 if config.verify_llvm_ir {
512 // Verification should run as the very first pass.
513 llvm::LLVMRustAddPass(fpm, find_pass("verify").unwrap());
516 let mut extra_passes = Vec::new();
517 let mut have_name_anon_globals_pass = false;
519 for pass_name in &config.passes {
520 if pass_name == "lint" {
521 // Linting should also be performed early, directly on the generated IR.
522 llvm::LLVMRustAddPass(fpm, find_pass("lint").unwrap());
526 if let Some(pass) = find_pass(pass_name) {
527 extra_passes.push(pass);
529 diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass_name));
532 if pass_name == "name-anon-globals" {
533 have_name_anon_globals_pass = true;
537 add_sanitizer_passes(config, &mut extra_passes);
539 // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
540 // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
541 // we'll get errors in LLVM.
542 let using_thin_buffers = config.bitcode_needed();
543 if !config.no_prepopulate_passes {
544 llvm::LLVMAddAnalysisPasses(tm, fpm);
545 llvm::LLVMAddAnalysisPasses(tm, mpm);
546 let opt_level = to_llvm_opt_settings(opt_level).0;
547 let prepare_for_thin_lto = cgcx.lto == Lto::Thin
548 || cgcx.lto == Lto::ThinLocal
549 || (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled());
550 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
551 llvm::LLVMRustAddLastExtensionPasses(
553 extra_passes.as_ptr(),
554 extra_passes.len() as size_t,
556 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
557 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
560 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
561 if using_thin_buffers && !prepare_for_thin_lto {
562 llvm::LLVMRustAddPass(mpm, find_pass("name-anon-globals").unwrap());
563 have_name_anon_globals_pass = true;
566 // If we don't use the standard pipeline, directly populate the MPM
567 // with the extra passes.
568 for pass in extra_passes {
569 llvm::LLVMRustAddPass(mpm, pass);
573 if using_thin_buffers && !have_name_anon_globals_pass {
574 // As described above, this will probably cause an error in LLVM
575 if config.no_prepopulate_passes {
577 "The current compilation is going to use thin LTO buffers \
578 without running LLVM's NameAnonGlobals pass. \
579 This will likely cause errors in LLVM. Consider adding \
580 -C passes=name-anon-globals to the compiler command line.",
584 "We are using thin LTO buffers without running the NameAnonGlobals pass. \
585 This will likely cause errors in LLVM and should never happen."
591 diag_handler.abort_if_errors();
593 // Finally, run the actual optimization passes
595 let _timer = cgcx.prof.extra_verbose_generic_activity(
596 "LLVM_module_optimize_function_passes",
599 llvm::LLVMRustRunFunctionPassManager(fpm, llmod);
602 let _timer = cgcx.prof.extra_verbose_generic_activity(
603 "LLVM_module_optimize_module_passes",
606 llvm::LLVMRunPassManager(mpm, llmod);
609 // Deallocate managers that we're now done with
610 llvm::LLVMDisposePassManager(fpm);
611 llvm::LLVMDisposePassManager(mpm);
616 unsafe fn add_sanitizer_passes(config: &ModuleConfig, passes: &mut Vec<&'static mut llvm::Pass>) {
617 if config.sanitizer.contains(SanitizerSet::ADDRESS) {
618 let recover = config.sanitizer_recover.contains(SanitizerSet::ADDRESS);
619 passes.push(llvm::LLVMRustCreateAddressSanitizerFunctionPass(recover));
620 passes.push(llvm::LLVMRustCreateModuleAddressSanitizerPass(recover));
622 if config.sanitizer.contains(SanitizerSet::MEMORY) {
623 let track_origins = config.sanitizer_memory_track_origins as c_int;
624 let recover = config.sanitizer_recover.contains(SanitizerSet::MEMORY);
625 passes.push(llvm::LLVMRustCreateMemorySanitizerPass(track_origins, recover));
627 if config.sanitizer.contains(SanitizerSet::THREAD) {
628 passes.push(llvm::LLVMRustCreateThreadSanitizerPass());
633 cgcx: &CodegenContext<LlvmCodegenBackend>,
634 diag_handler: &Handler,
635 mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
636 ) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
637 use super::lto::{Linker, ModuleBuffer};
638 // Sort the modules by name to ensure to ensure deterministic behavior.
639 modules.sort_by(|a, b| a.name.cmp(&b.name));
640 let (first, elements) =
641 modules.split_first().expect("Bug! modules must contain at least one module.");
643 let mut linker = Linker::new(first.module_llvm.llmod());
644 for module in elements {
646 cgcx.prof.generic_activity_with_arg("LLVM_link_module", format!("{:?}", module.name));
647 let buffer = ModuleBuffer::new(module.module_llvm.llmod());
648 linker.add(&buffer.data()).map_err(|()| {
649 let msg = format!("failed to serialize module {:?}", module.name);
650 llvm_err(&diag_handler, &msg)
654 Ok(modules.remove(0))
657 pub(crate) unsafe fn codegen(
658 cgcx: &CodegenContext<LlvmCodegenBackend>,
659 diag_handler: &Handler,
660 module: ModuleCodegen<ModuleLlvm>,
661 config: &ModuleConfig,
662 ) -> Result<CompiledModule, FatalError> {
663 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_codegen", &module.name[..]);
665 let llmod = module.module_llvm.llmod();
666 let llcx = &*module.module_llvm.llcx;
667 let tm = &*module.module_llvm.tm;
668 let module_name = module.name.clone();
669 let module_name = Some(&module_name[..]);
670 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
672 if cgcx.msvc_imps_needed {
673 create_msvc_imps(cgcx, llcx, llmod);
676 // A codegen-specific pass manager is used to generate object
677 // files for an LLVM module.
679 // Apparently each of these pass managers is a one-shot kind of
680 // thing, so we create a new one for each type of output. The
681 // pass manager passed to the closure should be ensured to not
682 // escape the closure itself, and the manager should only be
684 unsafe fn with_codegen<'ll, F, R>(
685 tm: &'ll llvm::TargetMachine,
686 llmod: &'ll llvm::Module,
691 F: FnOnce(&'ll mut PassManager<'ll>) -> R,
693 let cpm = llvm::LLVMCreatePassManager();
694 llvm::LLVMAddAnalysisPasses(tm, cpm);
695 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
699 // Two things to note:
700 // - If object files are just LLVM bitcode we write bitcode, copy it to
701 // the .o file, and delete the bitcode if it wasn't otherwise
703 // - If we don't have the integrated assembler then we need to emit
704 // asm from LLVM and use `gcc` to create the object file.
706 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
707 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
709 if config.bitcode_needed() {
712 .generic_activity_with_arg("LLVM_module_codegen_make_bitcode", &module.name[..]);
713 let thin = ThinBuffer::new(llmod);
714 let data = thin.data();
716 if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
717 let _timer = cgcx.prof.generic_activity_with_arg(
718 "LLVM_module_codegen_emit_bitcode",
721 if let Err(e) = fs::write(&bc_out, data) {
722 let msg = format!("failed to write bytecode to {}: {}", bc_out.display(), e);
723 diag_handler.err(&msg);
727 if config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full) {
728 let _timer = cgcx.prof.generic_activity_with_arg(
729 "LLVM_module_codegen_embed_bitcode",
732 embed_bitcode(cgcx, llcx, llmod, &config.bc_cmdline, data);
739 .generic_activity_with_arg("LLVM_module_codegen_emit_ir", &module.name[..]);
740 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
741 let out_c = path_to_c_string(&out);
743 extern "C" fn demangle_callback(
744 input_ptr: *const c_char,
746 output_ptr: *mut c_char,
750 unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
752 let input = match str::from_utf8(input) {
757 let output = unsafe {
758 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
760 let mut cursor = io::Cursor::new(output);
762 let demangled = match rustc_demangle::try_demangle(input) {
767 if write!(cursor, "{:#}", demangled).is_err() {
768 // Possible only if provided buffer is not big enough
772 cursor.position() as size_t
775 let result = llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback);
776 result.into_result().map_err(|()| {
777 let msg = format!("failed to write LLVM IR to {}", out.display());
778 llvm_err(diag_handler, &msg)
785 .generic_activity_with_arg("LLVM_module_codegen_emit_asm", &module.name[..]);
786 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
788 // We can't use the same module for asm and object code output,
789 // because that triggers various errors like invalid IR or broken
790 // binaries. So we must clone the module to produce the asm output
791 // if we are also producing object code.
792 let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
793 llvm::LLVMCloneModule(llmod)
797 with_codegen(tm, llmod, config.no_builtins, |cpm| {
798 write_output_file(diag_handler, tm, cpm, llmod, &path, llvm::FileType::AssemblyFile)
802 match config.emit_obj {
803 EmitObj::ObjectCode(_) => {
806 .generic_activity_with_arg("LLVM_module_codegen_emit_obj", &module.name[..]);
807 with_codegen(tm, llmod, config.no_builtins, |cpm| {
814 llvm::FileType::ObjectFile,
819 EmitObj::Bitcode => {
820 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
821 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
822 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
826 debug!("removing_bitcode {:?}", bc_out);
827 if let Err(e) = fs::remove_file(&bc_out) {
828 diag_handler.err(&format!("failed to remove bitcode: {}", e));
839 Ok(module.into_compiled_module(
840 config.emit_obj != EmitObj::None,
842 &cgcx.output_filenames,
846 /// Embed the bitcode of an LLVM module in the LLVM module itself.
848 /// This is done primarily for iOS where it appears to be standard to compile C
849 /// code at least with `-fembed-bitcode` which creates two sections in the
852 /// * __LLVM,__bitcode
853 /// * __LLVM,__cmdline
855 /// It appears *both* of these sections are necessary to get the linker to
856 /// recognize what's going on. A suitable cmdline value is taken from the
859 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
860 /// embed an empty section.
862 /// Basically all of this is us attempting to follow in the footsteps of clang
863 /// on iOS. See #35968 for lots more info.
864 unsafe fn embed_bitcode(
865 cgcx: &CodegenContext<LlvmCodegenBackend>,
866 llcx: &llvm::Context,
867 llmod: &llvm::Module,
871 let llconst = common::bytes_in_context(llcx, bitcode);
872 let llglobal = llvm::LLVMAddGlobal(
874 common::val_ty(llconst),
875 "rustc.embedded.module\0".as_ptr().cast(),
877 llvm::LLVMSetInitializer(llglobal, llconst);
879 let is_apple = cgcx.opts.target_triple.triple().contains("-ios")
880 || cgcx.opts.target_triple.triple().contains("-darwin")
881 || cgcx.opts.target_triple.triple().contains("-tvos");
883 let section = if is_apple { "__LLVM,__bitcode\0" } else { ".llvmbc\0" };
884 llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
885 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
886 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
888 let llconst = common::bytes_in_context(llcx, cmdline.as_bytes());
889 let llglobal = llvm::LLVMAddGlobal(
891 common::val_ty(llconst),
892 "rustc.embedded.cmdline\0".as_ptr().cast(),
894 llvm::LLVMSetInitializer(llglobal, llconst);
895 let section = if is_apple { "__LLVM,__cmdline\0" } else { ".llvmcmd\0" };
896 llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
897 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
899 // We're adding custom sections to the output object file, but we definitely
900 // do not want these custom sections to make their way into the final linked
901 // executable. The purpose of these custom sections is for tooling
902 // surrounding object files to work with the LLVM IR, if necessary. For
903 // example rustc's own LTO will look for LLVM IR inside of the object file
904 // in these sections by default.
906 // To handle this is a bit different depending on the object file format
907 // used by the backend, broken down into a few different categories:
909 // * Mach-O - this is for macOS. Inspecting the source code for the native
910 // linker here shows that the `.llvmbc` and `.llvmcmd` sections are
911 // automatically skipped by the linker. In that case there's nothing extra
912 // that we need to do here.
914 // * Wasm - the native LLD linker is hard-coded to skip `.llvmbc` and
915 // `.llvmcmd` sections, so there's nothing extra we need to do.
917 // * COFF - if we don't do anything the linker will by default copy all
918 // these sections to the output artifact, not what we want! To subvert
919 // this we want to flag the sections we inserted here as
920 // `IMAGE_SCN_LNK_REMOVE`. Unfortunately though LLVM has no native way to
921 // do this. Thankfully though we can do this with some inline assembly,
922 // which is easy enough to add via module-level global inline asm.
924 // * ELF - this is very similar to COFF above. One difference is that these
925 // sections are removed from the output linked artifact when
926 // `--gc-sections` is passed, which we pass by default. If that flag isn't
927 // passed though then these sections will show up in the final output.
928 // Additionally the flag that we need to set here is `SHF_EXCLUDE`.
930 || cgcx.opts.target_triple.triple().starts_with("wasm")
931 || cgcx.opts.target_triple.triple().starts_with("asmjs")
933 // nothing to do here
934 } else if cgcx.opts.target_triple.triple().contains("windows")
935 || cgcx.opts.target_triple.triple().contains("uefi")
938 .section .llvmbc,\"n\"
939 .section .llvmcmd,\"n\"
941 llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
944 .section .llvmbc,\"e\"
945 .section .llvmcmd,\"e\"
947 llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
951 pub unsafe fn with_llvm_pmb(
952 llmod: &llvm::Module,
953 config: &ModuleConfig,
954 opt_level: llvm::CodeGenOptLevel,
955 prepare_for_thin_lto: bool,
956 f: &mut dyn FnMut(&llvm::PassManagerBuilder),
960 // Create the PassManagerBuilder for LLVM. We configure it with
961 // reasonable defaults and prepare it to actually populate the pass
963 let builder = llvm::LLVMPassManagerBuilderCreate();
965 config.opt_size.map(|x| to_llvm_opt_settings(x).1).unwrap_or(llvm::CodeGenOptSizeNone);
966 let inline_threshold = config.inline_threshold;
967 let pgo_gen_path = get_pgo_gen_path(config);
968 let pgo_use_path = get_pgo_use_path(config);
970 llvm::LLVMRustConfigurePassManagerBuilder(
973 config.merge_functions,
974 config.vectorize_slp,
975 config.vectorize_loop,
976 prepare_for_thin_lto,
977 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
978 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
981 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
983 if opt_size != llvm::CodeGenOptSizeNone {
984 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
987 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
989 // Here we match what clang does (kinda). For O0 we only inline
990 // always-inline functions (but don't add lifetime intrinsics), at O1 we
991 // inline with lifetime intrinsics, and O2+ we add an inliner with a
992 // thresholds copied from clang.
993 match (opt_level, opt_size, inline_threshold) {
995 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
997 (llvm::CodeGenOptLevel::Aggressive, ..) => {
998 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
1000 (_, llvm::CodeGenOptSizeDefault, _) => {
1001 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
1003 (_, llvm::CodeGenOptSizeAggressive, _) => {
1004 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
1006 (llvm::CodeGenOptLevel::None, ..) => {
1007 llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
1009 (llvm::CodeGenOptLevel::Less, ..) => {
1010 llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
1012 (llvm::CodeGenOptLevel::Default, ..) => {
1013 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1018 llvm::LLVMPassManagerBuilderDispose(builder);
1021 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
1022 // This is required to satisfy `dllimport` references to static data in .rlibs
1023 // when using MSVC linker. We do this only for data, as linker can fix up
1024 // code references on its own.
1025 // See #26591, #27438
1026 fn create_msvc_imps(
1027 cgcx: &CodegenContext<LlvmCodegenBackend>,
1028 llcx: &llvm::Context,
1029 llmod: &llvm::Module,
1031 if !cgcx.msvc_imps_needed {
1034 // The x86 ABI seems to require that leading underscores are added to symbol
1035 // names, so we need an extra underscore on x86. There's also a leading
1036 // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
1037 // underscores added in front).
1038 let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" };
1041 let i8p_ty = Type::i8p_llcx(llcx);
1042 let globals = base::iter_globals(llmod)
1044 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage
1045 && llvm::LLVMIsDeclaration(val) == 0
1048 // Exclude some symbols that we know are not Rust symbols.
1049 let name = llvm::get_value_name(val);
1050 if ignored(name) { None } else { Some((val, name)) }
1052 .map(move |(val, name)| {
1053 let mut imp_name = prefix.as_bytes().to_vec();
1054 imp_name.extend(name);
1055 let imp_name = CString::new(imp_name).unwrap();
1058 .collect::<Vec<_>>();
1060 for (imp_name, val) in globals {
1061 let imp = llvm::LLVMAddGlobal(llmod, i8p_ty, imp_name.as_ptr().cast());
1062 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
1063 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
1067 // Use this function to exclude certain symbols from `__imp` generation.
1068 fn ignored(symbol_name: &[u8]) -> bool {
1069 // These are symbols generated by LLVM's profiling instrumentation
1070 symbol_name.starts_with(b"__llvm_profile_")