2 use crate::back::bytecode;
3 use crate::back::lto::ThinBuffer;
6 use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
9 use crate::type_::Type;
10 use crate::context::{is_pie_binary, get_reloc_model};
12 use crate::LlvmCodegenBackend;
13 use rustc::hir::def_id::LOCAL_CRATE;
14 use rustc_codegen_ssa::back::write::{CodegenContext, ModuleConfig, run_assembler};
15 use rustc_codegen_ssa::traits::*;
16 use rustc::session::config::{self, OutputType, Passes, Lto, PgoGenerate};
17 use rustc::session::Session;
18 use rustc::ty::TyCtxt;
19 use rustc_codegen_ssa::{RLIB_BYTECODE_EXTENSION, ModuleCodegen, CompiledModule};
20 use rustc::util::common::time_ext;
21 use rustc_fs_util::{path_to_c_string, link_or_copy};
22 use rustc_data_structures::small_c_str::SmallCStr;
23 use errors::{Handler, FatalError};
25 use std::ffi::{CString, CStr};
27 use std::io::{self, Write};
28 use std::path::{Path, PathBuf};
32 use libc::{c_uint, c_void, c_char, size_t};
34 pub const RELOC_MODEL_ARGS : [(&str, llvm::RelocMode); 7] = [
35 ("pic", llvm::RelocMode::PIC),
36 ("static", llvm::RelocMode::Static),
37 ("default", llvm::RelocMode::Default),
38 ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
39 ("ropi", llvm::RelocMode::ROPI),
40 ("rwpi", llvm::RelocMode::RWPI),
41 ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
44 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
45 ("small", llvm::CodeModel::Small),
46 ("kernel", llvm::CodeModel::Kernel),
47 ("medium", llvm::CodeModel::Medium),
48 ("large", llvm::CodeModel::Large),
51 pub const TLS_MODEL_ARGS : [(&str, llvm::ThreadLocalMode); 4] = [
52 ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
53 ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
54 ("initial-exec", llvm::ThreadLocalMode::InitialExec),
55 ("local-exec", llvm::ThreadLocalMode::LocalExec),
58 pub fn llvm_err(handler: &errors::Handler, msg: &str) -> FatalError {
59 match llvm::last_error() {
60 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
61 None => handler.fatal(&msg),
65 pub fn write_output_file(
66 handler: &errors::Handler,
67 target: &'ll llvm::TargetMachine,
68 pm: &llvm::PassManager<'ll>,
71 file_type: llvm::FileType) -> Result<(), FatalError> {
73 let output_c = path_to_c_string(output);
74 let result = llvm::LLVMRustWriteOutputFile(target, pm, m, output_c.as_ptr(), file_type);
75 result.into_result().map_err(|()| {
76 let msg = format!("could not write output to {}", output.display());
77 llvm_err(handler, &msg)
82 pub fn create_informational_target_machine(
85 ) -> &'static mut llvm::TargetMachine {
86 target_machine_factory(sess, config::OptLevel::No, find_features)().unwrap_or_else(|err| {
87 llvm_err(sess.diagnostic(), &err).raise()
91 pub fn create_target_machine(
92 tcx: TyCtxt<'_, '_, '_>,
94 ) -> &'static mut llvm::TargetMachine {
95 target_machine_factory(&tcx.sess, tcx.backend_optimization_level(LOCAL_CRATE), find_features)()
96 .unwrap_or_else(|err| {
97 llvm_err(tcx.sess.diagnostic(), &err).raise()
101 pub fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize)
103 use self::config::OptLevel::*;
105 No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
106 Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
107 Default => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
108 Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
109 Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
110 SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
114 // If find_features is true this won't access `sess.crate_types` by assuming
115 // that `is_pie_binary` is false. When we discover LLVM target features
116 // `sess.crate_types` is uninitialized so we cannot access it.
117 pub fn target_machine_factory(sess: &Session, optlvl: config::OptLevel, find_features: bool)
118 -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>
120 let reloc_model = get_reloc_model(sess);
122 let (opt_level, _) = to_llvm_opt_settings(optlvl);
123 let use_softfp = sess.opts.cg.soft_float;
125 let ffunction_sections = sess.target.target.options.function_sections;
126 let fdata_sections = ffunction_sections;
128 let code_model_arg = sess.opts.cg.code_model.as_ref().or(
129 sess.target.target.options.code_model.as_ref(),
132 let code_model = match code_model_arg {
134 match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
137 sess.err(&format!("{:?} is not a valid code model",
139 sess.abort_if_errors();
144 None => llvm::CodeModel::None,
147 let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
148 let mut singlethread = sess.target.target.options.singlethread;
150 // On the wasm target once the `atomics` feature is enabled that means that
151 // we're no longer single-threaded, or otherwise we don't want LLVM to
152 // lower atomic operations to single-threaded operations.
154 sess.target.target.llvm_target.contains("wasm32") &&
155 features.iter().any(|s| *s == "+atomics")
157 singlethread = false;
160 let triple = SmallCStr::new(&sess.target.target.llvm_target);
161 let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
162 let features = features.join(",");
163 let features = CString::new(features).unwrap();
164 let is_pie_binary = !find_features && is_pie_binary(sess);
165 let trap_unreachable = sess.target.target.options.trap_unreachable;
166 let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
168 let asm_comments = sess.asm_comments();
172 llvm::LLVMRustCreateTargetMachine(
173 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
184 emit_stack_size_section,
189 format!("Could not create LLVM TargetMachine for triple: {}",
190 triple.to_str().unwrap())
195 pub(crate) fn save_temp_bitcode(
196 cgcx: &CodegenContext<LlvmCodegenBackend>,
197 module: &ModuleCodegen<ModuleLlvm>,
200 if !cgcx.save_temps {
204 let ext = format!("{}.bc", name);
205 let cgu = Some(&module.name[..]);
206 let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
207 let cstr = path_to_c_string(&path);
208 let llmod = module.module_llvm.llmod();
209 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
213 pub struct DiagnosticHandlers<'a> {
214 data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
215 llcx: &'a llvm::Context,
218 impl<'a> DiagnosticHandlers<'a> {
219 pub fn new(cgcx: &'a CodegenContext<LlvmCodegenBackend>,
220 handler: &'a Handler,
221 llcx: &'a llvm::Context) -> Self {
222 let data = Box::into_raw(Box::new((cgcx, handler)));
224 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
225 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
227 DiagnosticHandlers { data, llcx }
231 impl<'a> Drop for DiagnosticHandlers<'a> {
233 use std::ptr::null_mut;
235 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
236 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
237 drop(Box::from_raw(self.data));
242 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext<LlvmCodegenBackend>,
245 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_owned());
248 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
254 let (cgcx, _) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
256 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
257 .expect("non-UTF8 SMDiagnostic");
259 report_inline_asm(cgcx, &msg, cookie);
262 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
266 let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
268 match llvm::diagnostic::Diagnostic::unpack(info) {
269 llvm::diagnostic::InlineAsm(inline) => {
270 report_inline_asm(cgcx,
271 &llvm::twine_to_string(inline.message),
275 llvm::diagnostic::Optimization(opt) => {
276 let enabled = match cgcx.remark {
278 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
282 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
291 llvm::diagnostic::PGO(diagnostic_ref) |
292 llvm::diagnostic::Linker(diagnostic_ref) => {
293 let msg = llvm::build_string(|s| {
294 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
295 }).expect("non-UTF8 diagnostic");
296 diag_handler.warn(&msg);
298 llvm::diagnostic::UnknownDiagnostic(..) => {},
302 // Unsafe due to LLVM calls.
303 pub(crate) unsafe fn optimize(cgcx: &CodegenContext<LlvmCodegenBackend>,
304 diag_handler: &Handler,
305 module: &ModuleCodegen<ModuleLlvm>,
306 config: &ModuleConfig)
307 -> Result<(), FatalError>
309 let llmod = module.module_llvm.llmod();
310 let llcx = &*module.module_llvm.llcx;
311 let tm = &*module.module_llvm.tm;
312 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
314 let module_name = module.name.clone();
315 let module_name = Some(&module_name[..]);
317 if config.emit_no_opt_bc {
318 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
319 let out = path_to_c_string(&out);
320 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
323 if config.opt_level.is_some() {
324 // Create the two optimizing pass managers. These mirror what clang
325 // does, and are by populated by LLVM's default PassManagerBuilder.
326 // Each manager has a different set of passes, but they also share
327 // some common passes.
328 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
329 let mpm = llvm::LLVMCreatePassManager();
332 // If we're verifying or linting, add them to the function pass
334 let addpass = |pass_name: &str| {
335 let pass_name = SmallCStr::new(pass_name);
336 let pass = match llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr()) {
338 None => return false,
340 let pass_manager = match llvm::LLVMRustPassKind(pass) {
341 llvm::PassKind::Function => &*fpm,
342 llvm::PassKind::Module => &*mpm,
343 llvm::PassKind::Other => {
344 diag_handler.err("Encountered LLVM pass kind we can't handle");
348 llvm::LLVMRustAddPass(pass_manager, pass);
352 if config.verify_llvm_ir { assert!(addpass("verify")); }
354 // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
355 // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
356 // we'll get errors in LLVM.
357 let using_thin_buffers = config.bitcode_needed();
358 let mut have_name_anon_globals_pass = false;
359 if !config.no_prepopulate_passes {
360 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
361 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
362 let opt_level = config.opt_level.map(|x| to_llvm_opt_settings(x).0)
363 .unwrap_or(llvm::CodeGenOptLevel::None);
364 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal ||
365 (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled());
366 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
367 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
368 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
371 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
372 if using_thin_buffers && !prepare_for_thin_lto {
373 assert!(addpass("name-anon-globals"));
374 have_name_anon_globals_pass = true;
378 for pass in &config.passes {
380 diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass));
382 if pass == "name-anon-globals" {
383 have_name_anon_globals_pass = true;
387 for pass in &cgcx.plugin_passes {
389 diag_handler.err(&format!("a plugin asked for LLVM pass \
390 `{}` but LLVM does not \
391 recognize it", pass));
393 if pass == "name-anon-globals" {
394 have_name_anon_globals_pass = true;
398 if using_thin_buffers && !have_name_anon_globals_pass {
399 // As described above, this will probably cause an error in LLVM
400 if config.no_prepopulate_passes {
401 diag_handler.err("The current compilation is going to use thin LTO buffers \
402 without running LLVM's NameAnonGlobals pass. \
403 This will likely cause errors in LLVM. Consider adding \
404 -C passes=name-anon-globals to the compiler command line.");
406 bug!("We are using thin LTO buffers without running the NameAnonGlobals pass. \
407 This will likely cause errors in LLVM and should never happen.");
412 diag_handler.abort_if_errors();
414 // Finally, run the actual optimization passes
416 let _timer = cgcx.profile_activity("LLVM_function_passes");
417 time_ext(config.time_passes,
419 &format!("llvm function passes [{}]", module_name.unwrap()),
421 llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
425 let _timer = cgcx.profile_activity("LLVM_module_passes");
426 time_ext(config.time_passes,
428 &format!("llvm module passes [{}]", module_name.unwrap()),
430 llvm::LLVMRunPassManager(mpm, llmod)
434 // Deallocate managers that we're now done with
435 llvm::LLVMDisposePassManager(fpm);
436 llvm::LLVMDisposePassManager(mpm);
441 pub(crate) unsafe fn codegen(cgcx: &CodegenContext<LlvmCodegenBackend>,
442 diag_handler: &Handler,
443 module: ModuleCodegen<ModuleLlvm>,
444 config: &ModuleConfig)
445 -> Result<CompiledModule, FatalError>
447 let _timer = cgcx.profile_activity("codegen");
449 let llmod = module.module_llvm.llmod();
450 let llcx = &*module.module_llvm.llcx;
451 let tm = &*module.module_llvm.tm;
452 let module_name = module.name.clone();
453 let module_name = Some(&module_name[..]);
454 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
456 if cgcx.msvc_imps_needed {
457 create_msvc_imps(cgcx, llcx, llmod);
460 // A codegen-specific pass manager is used to generate object
461 // files for an LLVM module.
463 // Apparently each of these pass managers is a one-shot kind of
464 // thing, so we create a new one for each type of output. The
465 // pass manager passed to the closure should be ensured to not
466 // escape the closure itself, and the manager should only be
468 unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine,
469 llmod: &'ll llvm::Module,
472 where F: FnOnce(&'ll mut PassManager<'ll>) -> R,
474 let cpm = llvm::LLVMCreatePassManager();
475 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
476 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
480 // If we don't have the integrated assembler, then we need to emit asm
481 // from LLVM and use `gcc` to create the object file.
482 let asm_to_obj = config.emit_obj && config.no_integrated_as;
484 // Change what we write and cleanup based on whether obj files are
485 // just llvm bitcode. In that case write bitcode, and possibly
486 // delete the bitcode if it wasn't requested. Don't generate the
487 // machine code, instead copy the .o file from the .bc
488 let write_bc = config.emit_bc || config.obj_is_bitcode;
489 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
490 let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
491 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
493 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
494 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
497 if write_bc || config.emit_bc_compressed || config.embed_bitcode {
498 let _timer = cgcx.profile_activity("LLVM_make_bitcode");
499 let thin = ThinBuffer::new(llmod);
500 let data = thin.data();
503 let _timer = cgcx.profile_activity("LLVM_emit_bitcode");
504 if let Err(e) = fs::write(&bc_out, data) {
505 let msg = format!("failed to write bytecode to {}: {}", bc_out.display(), e);
506 diag_handler.err(&msg);
510 if config.embed_bitcode {
511 let _timer = cgcx.profile_activity("LLVM_embed_bitcode");
512 embed_bitcode(cgcx, llcx, llmod, Some(data));
515 if config.emit_bc_compressed {
516 let _timer = cgcx.profile_activity("LLVM_compress_bitcode");
517 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
518 let data = bytecode::encode(&module.name, data);
519 if let Err(e) = fs::write(&dst, data) {
520 let msg = format!("failed to write bytecode to {}: {}", dst.display(), e);
521 diag_handler.err(&msg);
524 } else if config.embed_bitcode_marker {
525 embed_bitcode(cgcx, llcx, llmod, None);
528 time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
529 || -> Result<(), FatalError> {
531 let _timer = cgcx.profile_activity("LLVM_emit_ir");
532 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
533 let out_c = path_to_c_string(&out);
535 extern "C" fn demangle_callback(input_ptr: *const c_char,
537 output_ptr: *mut c_char,
538 output_len: size_t) -> size_t {
540 slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
543 let input = match str::from_utf8(input) {
548 let output = unsafe {
549 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
551 let mut cursor = io::Cursor::new(output);
553 let demangled = match rustc_demangle::try_demangle(input) {
558 if let Err(_) = write!(cursor, "{:#}", demangled) {
559 // Possible only if provided buffer is not big enough
563 cursor.position() as size_t
566 with_codegen(tm, llmod, config.no_builtins, |cpm| {
568 llvm::LLVMRustPrintModule(cpm, llmod, out_c.as_ptr(), demangle_callback);
569 llvm::LLVMDisposePassManager(cpm);
570 result.into_result().map_err(|()| {
571 let msg = format!("failed to write LLVM IR to {}", out.display());
572 llvm_err(diag_handler, &msg)
577 if config.emit_asm || asm_to_obj {
578 let _timer = cgcx.profile_activity("LLVM_emit_asm");
579 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
581 // We can't use the same module for asm and binary output, because that triggers
582 // various errors like invalid IR or broken binaries, so we might have to clone the
583 // module to produce the asm output
584 let llmod = if config.emit_obj {
585 llvm::LLVMCloneModule(llmod)
589 with_codegen(tm, llmod, config.no_builtins, |cpm| {
590 write_output_file(diag_handler, tm, cpm, llmod, &path,
591 llvm::FileType::AssemblyFile)
596 let _timer = cgcx.profile_activity("LLVM_emit_obj");
597 with_codegen(tm, llmod, config.no_builtins, |cpm| {
598 write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
599 llvm::FileType::ObjectFile)
601 } else if asm_to_obj {
602 let _timer = cgcx.profile_activity("LLVM_asm_to_obj");
603 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
604 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
606 if !config.emit_asm && !cgcx.save_temps {
607 drop(fs::remove_file(&assembly));
615 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
616 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
617 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
622 debug!("removing_bitcode {:?}", bc_out);
623 if let Err(e) = fs::remove_file(&bc_out) {
624 diag_handler.err(&format!("failed to remove bitcode: {}", e));
630 Ok(module.into_compiled_module(config.emit_obj,
632 config.emit_bc_compressed,
633 &cgcx.output_filenames))
636 /// Embed the bitcode of an LLVM module in the LLVM module itself.
638 /// This is done primarily for iOS where it appears to be standard to compile C
639 /// code at least with `-fembed-bitcode` which creates two sections in the
642 /// * __LLVM,__bitcode
643 /// * __LLVM,__cmdline
645 /// It appears *both* of these sections are necessary to get the linker to
646 /// recognize what's going on. For us though we just always throw in an empty
649 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
650 /// embed an empty section.
652 /// Basically all of this is us attempting to follow in the footsteps of clang
653 /// on iOS. See #35968 for lots more info.
654 unsafe fn embed_bitcode(cgcx: &CodegenContext<LlvmCodegenBackend>,
655 llcx: &llvm::Context,
656 llmod: &llvm::Module,
657 bitcode: Option<&[u8]>) {
658 let llconst = common::bytes_in_context(llcx, bitcode.unwrap_or(&[]));
659 let llglobal = llvm::LLVMAddGlobal(
661 common::val_ty(llconst),
662 "rustc.embedded.module\0".as_ptr() as *const _,
664 llvm::LLVMSetInitializer(llglobal, llconst);
666 let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
667 cgcx.opts.target_triple.triple().contains("-darwin");
669 let section = if is_apple {
674 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
675 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
676 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
678 let llconst = common::bytes_in_context(llcx, &[]);
679 let llglobal = llvm::LLVMAddGlobal(
681 common::val_ty(llconst),
682 "rustc.embedded.cmdline\0".as_ptr() as *const _,
684 llvm::LLVMSetInitializer(llglobal, llconst);
685 let section = if is_apple {
690 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
691 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
694 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
695 config: &ModuleConfig,
696 opt_level: llvm::CodeGenOptLevel,
697 prepare_for_thin_lto: bool,
698 f: &mut dyn FnMut(&llvm::PassManagerBuilder)) {
701 // Create the PassManagerBuilder for LLVM. We configure it with
702 // reasonable defaults and prepare it to actually populate the pass
704 let builder = llvm::LLVMPassManagerBuilderCreate();
705 let opt_size = config.opt_size.map(|x| to_llvm_opt_settings(x).1)
706 .unwrap_or(llvm::CodeGenOptSizeNone);
707 let inline_threshold = config.inline_threshold;
709 let pgo_gen_path = match config.pgo_gen {
710 PgoGenerate::Enabled(ref opt_dir_path) => {
711 let path = if let Some(dir_path) = opt_dir_path {
712 dir_path.join("default_%m.profraw")
714 PathBuf::from("default_%m.profraw")
717 Some(CString::new(format!("{}", path.display())).unwrap())
719 PgoGenerate::Disabled => {
724 let pgo_use_path = if config.pgo_use.is_empty() {
727 Some(CString::new(config.pgo_use.as_bytes()).unwrap())
730 llvm::LLVMRustConfigurePassManagerBuilder(
733 config.merge_functions,
734 config.vectorize_slp,
735 config.vectorize_loop,
736 prepare_for_thin_lto,
737 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
738 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
741 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
743 if opt_size != llvm::CodeGenOptSizeNone {
744 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
747 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
749 // Here we match what clang does (kinda). For O0 we only inline
750 // always-inline functions (but don't add lifetime intrinsics), at O1 we
751 // inline with lifetime intrinsics, and O2+ we add an inliner with a
752 // thresholds copied from clang.
753 match (opt_level, opt_size, inline_threshold) {
755 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
757 (llvm::CodeGenOptLevel::Aggressive, ..) => {
758 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
760 (_, llvm::CodeGenOptSizeDefault, _) => {
761 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
763 (_, llvm::CodeGenOptSizeAggressive, _) => {
764 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
766 (llvm::CodeGenOptLevel::None, ..) => {
767 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
769 (llvm::CodeGenOptLevel::Less, ..) => {
770 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
772 (llvm::CodeGenOptLevel::Default, ..) => {
773 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
775 (llvm::CodeGenOptLevel::Other, ..) => {
776 bug!("CodeGenOptLevel::Other selected")
781 llvm::LLVMPassManagerBuilderDispose(builder);
784 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
785 // This is required to satisfy `dllimport` references to static data in .rlibs
786 // when using MSVC linker. We do this only for data, as linker can fix up
787 // code references on its own.
788 // See #26591, #27438
790 cgcx: &CodegenContext<LlvmCodegenBackend>,
791 llcx: &llvm::Context,
794 if !cgcx.msvc_imps_needed {
797 // The x86 ABI seems to require that leading underscores are added to symbol
798 // names, so we need an extra underscore on 32-bit. There's also a leading
799 // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
800 // underscores added in front).
801 let prefix = if cgcx.target_pointer_width == "32" {
808 let i8p_ty = Type::i8p_llcx(llcx);
809 let globals = base::iter_globals(llmod)
811 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
812 llvm::LLVMIsDeclaration(val) == 0
815 // Exclude some symbols that we know are not Rust symbols.
816 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
817 if ignored(name.to_bytes()) {
823 .map(move |(val, name)| {
824 let mut imp_name = prefix.as_bytes().to_vec();
825 imp_name.extend(name.to_bytes());
826 let imp_name = CString::new(imp_name).unwrap();
829 .collect::<Vec<_>>();
831 for (imp_name, val) in globals {
832 let imp = llvm::LLVMAddGlobal(llmod,
834 imp_name.as_ptr() as *const _);
835 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
836 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
840 // Use this function to exclude certain symbols from `__imp` generation.
841 fn ignored(symbol_name: &[u8]) -> bool {
842 // These are symbols generated by LLVM's profiling instrumentation
843 symbol_name.starts_with(b"__llvm_profile_")