]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/back/write.rs
Rollup merge of #101738 - dpaoliello:linkname, r=petrochenkov
[rust.git] / compiler / rustc_codegen_llvm / src / back / write.rs
1 use crate::back::lto::ThinBuffer;
2 use crate::back::profiling::{
3     selfprofile_after_pass_callback, selfprofile_before_pass_callback, LlvmSelfProfiler,
4 };
5 use crate::base;
6 use crate::common;
7 use crate::consts;
8 use crate::llvm::{self, DiagnosticInfo, PassManager};
9 use crate::llvm_util;
10 use crate::type_::Type;
11 use crate::LlvmCodegenBackend;
12 use crate::ModuleLlvm;
13 use rustc_codegen_ssa::back::link::ensure_removed;
14 use rustc_codegen_ssa::back::write::{
15     BitcodeSection, CodegenContext, EmitObj, ModuleConfig, TargetMachineFactoryConfig,
16     TargetMachineFactoryFn,
17 };
18 use rustc_codegen_ssa::traits::*;
19 use rustc_codegen_ssa::{CompiledModule, ModuleCodegen};
20 use rustc_data_structures::profiling::SelfProfilerRef;
21 use rustc_data_structures::small_c_str::SmallCStr;
22 use rustc_errors::{FatalError, Handler, Level};
23 use rustc_fs_util::{link_or_copy, path_to_c_string};
24 use rustc_middle::bug;
25 use rustc_middle::ty::TyCtxt;
26 use rustc_session::config::{self, Lto, OutputType, Passes, SplitDwarfKind, SwitchWithOptPath};
27 use rustc_session::Session;
28 use rustc_span::symbol::sym;
29 use rustc_span::InnerSpan;
30 use rustc_target::spec::{CodeModel, RelocModel, SanitizerSet, SplitDebuginfo};
31
32 use libc::{c_char, c_int, c_uint, c_void, size_t};
33 use std::ffi::CString;
34 use std::fs;
35 use std::io::{self, Write};
36 use std::path::{Path, PathBuf};
37 use std::slice;
38 use std::str;
39 use std::sync::Arc;
40
41 pub fn llvm_err(handler: &rustc_errors::Handler, msg: &str) -> FatalError {
42     match llvm::last_error() {
43         Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
44         None => handler.fatal(msg),
45     }
46 }
47
48 pub fn write_output_file<'ll>(
49     handler: &rustc_errors::Handler,
50     target: &'ll llvm::TargetMachine,
51     pm: &llvm::PassManager<'ll>,
52     m: &'ll llvm::Module,
53     output: &Path,
54     dwo_output: Option<&Path>,
55     file_type: llvm::FileType,
56     self_profiler_ref: &SelfProfilerRef,
57 ) -> Result<(), FatalError> {
58     debug!("write_output_file output={:?} dwo_output={:?}", output, dwo_output);
59     unsafe {
60         let output_c = path_to_c_string(output);
61         let dwo_output_c;
62         let dwo_output_ptr = if let Some(dwo_output) = dwo_output {
63             dwo_output_c = path_to_c_string(dwo_output);
64             dwo_output_c.as_ptr()
65         } else {
66             std::ptr::null()
67         };
68         let result = llvm::LLVMRustWriteOutputFile(
69             target,
70             pm,
71             m,
72             output_c.as_ptr(),
73             dwo_output_ptr,
74             file_type,
75         );
76
77         // Record artifact sizes for self-profiling
78         if result == llvm::LLVMRustResult::Success {
79             let artifact_kind = match file_type {
80                 llvm::FileType::ObjectFile => "object_file",
81                 llvm::FileType::AssemblyFile => "assembly_file",
82             };
83             record_artifact_size(self_profiler_ref, artifact_kind, output);
84             if let Some(dwo_file) = dwo_output {
85                 record_artifact_size(self_profiler_ref, "dwo_file", dwo_file);
86             }
87         }
88
89         result.into_result().map_err(|()| {
90             let msg = format!("could not write output to {}", output.display());
91             llvm_err(handler, &msg)
92         })
93     }
94 }
95
96 pub fn create_informational_target_machine(sess: &Session) -> &'static mut llvm::TargetMachine {
97     let config = TargetMachineFactoryConfig { split_dwarf_file: None };
98     // Can't use query system here quite yet because this function is invoked before the query
99     // system/tcx is set up.
100     let features = llvm_util::global_llvm_features(sess, false);
101     target_machine_factory(sess, config::OptLevel::No, &features)(config)
102         .unwrap_or_else(|err| llvm_err(sess.diagnostic(), &err).raise())
103 }
104
105 pub fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> &'static mut llvm::TargetMachine {
106     let split_dwarf_file = if tcx.sess.target_can_use_split_dwarf() {
107         tcx.output_filenames(()).split_dwarf_path(
108             tcx.sess.split_debuginfo(),
109             tcx.sess.opts.unstable_opts.split_dwarf_kind,
110             Some(mod_name),
111         )
112     } else {
113         None
114     };
115     let config = TargetMachineFactoryConfig { split_dwarf_file };
116     target_machine_factory(
117         &tcx.sess,
118         tcx.backend_optimization_level(()),
119         tcx.global_backend_features(()),
120     )(config)
121     .unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise())
122 }
123
124 pub fn to_llvm_opt_settings(
125     cfg: config::OptLevel,
126 ) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
127     use self::config::OptLevel::*;
128     match cfg {
129         No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
130         Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
131         Default => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
132         Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
133         Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
134         SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
135     }
136 }
137
138 fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel {
139     use config::OptLevel::*;
140     match cfg {
141         No => llvm::PassBuilderOptLevel::O0,
142         Less => llvm::PassBuilderOptLevel::O1,
143         Default => llvm::PassBuilderOptLevel::O2,
144         Aggressive => llvm::PassBuilderOptLevel::O3,
145         Size => llvm::PassBuilderOptLevel::Os,
146         SizeMin => llvm::PassBuilderOptLevel::Oz,
147     }
148 }
149
150 fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
151     match relocation_model {
152         RelocModel::Static => llvm::RelocModel::Static,
153         // LLVM doesn't have a PIE relocation model, it represents PIE as PIC with an extra attribute.
154         RelocModel::Pic | RelocModel::Pie => llvm::RelocModel::PIC,
155         RelocModel::DynamicNoPic => llvm::RelocModel::DynamicNoPic,
156         RelocModel::Ropi => llvm::RelocModel::ROPI,
157         RelocModel::Rwpi => llvm::RelocModel::RWPI,
158         RelocModel::RopiRwpi => llvm::RelocModel::ROPI_RWPI,
159     }
160 }
161
162 pub(crate) fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeModel {
163     match code_model {
164         Some(CodeModel::Tiny) => llvm::CodeModel::Tiny,
165         Some(CodeModel::Small) => llvm::CodeModel::Small,
166         Some(CodeModel::Kernel) => llvm::CodeModel::Kernel,
167         Some(CodeModel::Medium) => llvm::CodeModel::Medium,
168         Some(CodeModel::Large) => llvm::CodeModel::Large,
169         None => llvm::CodeModel::None,
170     }
171 }
172
173 pub fn target_machine_factory(
174     sess: &Session,
175     optlvl: config::OptLevel,
176     target_features: &[String],
177 ) -> TargetMachineFactoryFn<LlvmCodegenBackend> {
178     let reloc_model = to_llvm_relocation_model(sess.relocation_model());
179
180     let (opt_level, _) = to_llvm_opt_settings(optlvl);
181     let use_softfp = sess.opts.cg.soft_float;
182
183     let ffunction_sections =
184         sess.opts.unstable_opts.function_sections.unwrap_or(sess.target.function_sections);
185     let fdata_sections = ffunction_sections;
186     let funique_section_names = !sess.opts.unstable_opts.no_unique_section_names;
187
188     let code_model = to_llvm_code_model(sess.code_model());
189
190     let mut singlethread = sess.target.singlethread;
191
192     // On the wasm target once the `atomics` feature is enabled that means that
193     // we're no longer single-threaded, or otherwise we don't want LLVM to
194     // lower atomic operations to single-threaded operations.
195     if singlethread && sess.target.is_like_wasm && sess.target_features.contains(&sym::atomics) {
196         singlethread = false;
197     }
198
199     let triple = SmallCStr::new(&sess.target.llvm_target);
200     let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
201     let features = CString::new(target_features.join(",")).unwrap();
202     let abi = SmallCStr::new(&sess.target.llvm_abiname);
203     let trap_unreachable =
204         sess.opts.unstable_opts.trap_unreachable.unwrap_or(sess.target.trap_unreachable);
205     let emit_stack_size_section = sess.opts.unstable_opts.emit_stack_sizes;
206
207     let asm_comments = sess.asm_comments();
208     let relax_elf_relocations =
209         sess.opts.unstable_opts.relax_elf_relocations.unwrap_or(sess.target.relax_elf_relocations);
210
211     let use_init_array =
212         !sess.opts.unstable_opts.use_ctors_section.unwrap_or(sess.target.use_ctors_section);
213
214     let path_mapping = sess.source_map().path_mapping().clone();
215
216     Arc::new(move |config: TargetMachineFactoryConfig| {
217         let split_dwarf_file =
218             path_mapping.map_prefix(config.split_dwarf_file.unwrap_or_default()).0;
219         let split_dwarf_file = CString::new(split_dwarf_file.to_str().unwrap()).unwrap();
220
221         let tm = unsafe {
222             llvm::LLVMRustCreateTargetMachine(
223                 triple.as_ptr(),
224                 cpu.as_ptr(),
225                 features.as_ptr(),
226                 abi.as_ptr(),
227                 code_model,
228                 reloc_model,
229                 opt_level,
230                 use_softfp,
231                 ffunction_sections,
232                 fdata_sections,
233                 funique_section_names,
234                 trap_unreachable,
235                 singlethread,
236                 asm_comments,
237                 emit_stack_size_section,
238                 relax_elf_relocations,
239                 use_init_array,
240                 split_dwarf_file.as_ptr(),
241             )
242         };
243
244         tm.ok_or_else(|| {
245             format!("Could not create LLVM TargetMachine for triple: {}", triple.to_str().unwrap())
246         })
247     })
248 }
249
250 pub(crate) fn save_temp_bitcode(
251     cgcx: &CodegenContext<LlvmCodegenBackend>,
252     module: &ModuleCodegen<ModuleLlvm>,
253     name: &str,
254 ) {
255     if !cgcx.save_temps {
256         return;
257     }
258     unsafe {
259         let ext = format!("{}.bc", name);
260         let cgu = Some(&module.name[..]);
261         let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
262         let cstr = path_to_c_string(&path);
263         let llmod = module.module_llvm.llmod();
264         llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
265     }
266 }
267
268 pub struct DiagnosticHandlers<'a> {
269     data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
270     llcx: &'a llvm::Context,
271     old_handler: Option<&'a llvm::DiagnosticHandler>,
272 }
273
274 impl<'a> DiagnosticHandlers<'a> {
275     pub fn new(
276         cgcx: &'a CodegenContext<LlvmCodegenBackend>,
277         handler: &'a Handler,
278         llcx: &'a llvm::Context,
279     ) -> Self {
280         let remark_passes_all: bool;
281         let remark_passes: Vec<CString>;
282         match &cgcx.remark {
283             Passes::All => {
284                 remark_passes_all = true;
285                 remark_passes = Vec::new();
286             }
287             Passes::Some(passes) => {
288                 remark_passes_all = false;
289                 remark_passes =
290                     passes.iter().map(|name| CString::new(name.as_str()).unwrap()).collect();
291             }
292         };
293         let remark_passes: Vec<*const c_char> =
294             remark_passes.iter().map(|name: &CString| name.as_ptr()).collect();
295         let data = Box::into_raw(Box::new((cgcx, handler)));
296         unsafe {
297             let old_handler = llvm::LLVMRustContextGetDiagnosticHandler(llcx);
298             llvm::LLVMRustContextConfigureDiagnosticHandler(
299                 llcx,
300                 diagnostic_handler,
301                 data.cast(),
302                 remark_passes_all,
303                 remark_passes.as_ptr(),
304                 remark_passes.len(),
305             );
306             DiagnosticHandlers { data, llcx, old_handler }
307         }
308     }
309 }
310
311 impl<'a> Drop for DiagnosticHandlers<'a> {
312     fn drop(&mut self) {
313         unsafe {
314             llvm::LLVMRustContextSetDiagnosticHandler(self.llcx, self.old_handler);
315             drop(Box::from_raw(self.data));
316         }
317     }
318 }
319
320 fn report_inline_asm(
321     cgcx: &CodegenContext<LlvmCodegenBackend>,
322     msg: String,
323     level: llvm::DiagnosticLevel,
324     mut cookie: c_uint,
325     source: Option<(String, Vec<InnerSpan>)>,
326 ) {
327     // In LTO build we may get srcloc values from other crates which are invalid
328     // since they use a different source map. To be safe we just suppress these
329     // in LTO builds.
330     if matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
331         cookie = 0;
332     }
333     let level = match level {
334         llvm::DiagnosticLevel::Error => Level::Error { lint: false },
335         llvm::DiagnosticLevel::Warning => Level::Warning(None),
336         llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
337     };
338     cgcx.diag_emitter.inline_asm_error(cookie as u32, msg, level, source);
339 }
340
341 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
342     if user.is_null() {
343         return;
344     }
345     let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
346
347     match llvm::diagnostic::Diagnostic::unpack(info) {
348         llvm::diagnostic::InlineAsm(inline) => {
349             report_inline_asm(cgcx, inline.message, inline.level, inline.cookie, inline.source);
350         }
351
352         llvm::diagnostic::Optimization(opt) => {
353             let enabled = match cgcx.remark {
354                 Passes::All => true,
355                 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
356             };
357
358             if enabled {
359                 diag_handler.note_without_error(&format!(
360                     "{}:{}:{}: {}: {}",
361                     opt.filename, opt.line, opt.column, opt.pass_name, opt.message,
362                 ));
363             }
364         }
365         llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
366             let msg = llvm::build_string(|s| {
367                 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
368             })
369             .expect("non-UTF8 diagnostic");
370             diag_handler.warn(&msg);
371         }
372         llvm::diagnostic::Unsupported(diagnostic_ref) => {
373             let msg = llvm::build_string(|s| {
374                 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
375             })
376             .expect("non-UTF8 diagnostic");
377             diag_handler.err(&msg);
378         }
379         llvm::diagnostic::UnknownDiagnostic(..) => {}
380     }
381 }
382
383 fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
384     match config.pgo_gen {
385         SwitchWithOptPath::Enabled(ref opt_dir_path) => {
386             let path = if let Some(dir_path) = opt_dir_path {
387                 dir_path.join("default_%m.profraw")
388             } else {
389                 PathBuf::from("default_%m.profraw")
390             };
391
392             Some(CString::new(format!("{}", path.display())).unwrap())
393         }
394         SwitchWithOptPath::Disabled => None,
395     }
396 }
397
398 fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
399     config
400         .pgo_use
401         .as_ref()
402         .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
403 }
404
405 fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option<CString> {
406     config
407         .pgo_sample_use
408         .as_ref()
409         .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
410 }
411
412 fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> {
413     if config.instrument_coverage {
414         Some(CString::new("default_%m_%p.profraw").unwrap())
415     } else {
416         None
417     }
418 }
419
420 pub(crate) unsafe fn optimize_with_new_llvm_pass_manager(
421     cgcx: &CodegenContext<LlvmCodegenBackend>,
422     diag_handler: &Handler,
423     module: &ModuleCodegen<ModuleLlvm>,
424     config: &ModuleConfig,
425     opt_level: config::OptLevel,
426     opt_stage: llvm::OptStage,
427 ) -> Result<(), FatalError> {
428     let unroll_loops =
429         opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
430     let using_thin_buffers = opt_stage == llvm::OptStage::PreLinkThinLTO || config.bitcode_needed();
431     let pgo_gen_path = get_pgo_gen_path(config);
432     let pgo_use_path = get_pgo_use_path(config);
433     let pgo_sample_use_path = get_pgo_sample_use_path(config);
434     let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
435     let instr_profile_output_path = get_instr_profile_output_path(config);
436     // Sanitizer instrumentation is only inserted during the pre-link optimization stage.
437     let sanitizer_options = if !is_lto {
438         Some(llvm::SanitizerOptions {
439             sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
440             sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
441             sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
442             sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
443             sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
444             sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
445             sanitize_hwaddress: config.sanitizer.contains(SanitizerSet::HWADDRESS),
446             sanitize_hwaddress_recover: config.sanitizer_recover.contains(SanitizerSet::HWADDRESS),
447         })
448     } else {
449         None
450     };
451
452     let mut llvm_profiler = if cgcx.prof.llvm_recording_enabled() {
453         Some(LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap()))
454     } else {
455         None
456     };
457
458     let llvm_selfprofiler =
459         llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut());
460
461     let extra_passes = if !is_lto { config.passes.join(",") } else { "".to_string() };
462
463     let llvm_plugins = config.llvm_plugins.join(",");
464
465     // FIXME: NewPM doesn't provide a facility to pass custom InlineParams.
466     // We would have to add upstream support for this first, before we can support
467     // config.inline_threshold and our more aggressive default thresholds.
468     let result = llvm::LLVMRustOptimizeWithNewPassManager(
469         module.module_llvm.llmod(),
470         &*module.module_llvm.tm,
471         to_pass_builder_opt_level(opt_level),
472         opt_stage,
473         config.no_prepopulate_passes,
474         config.verify_llvm_ir,
475         using_thin_buffers,
476         config.merge_functions,
477         unroll_loops,
478         config.vectorize_slp,
479         config.vectorize_loop,
480         config.no_builtins,
481         config.emit_lifetime_markers,
482         sanitizer_options.as_ref(),
483         pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
484         pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
485         config.instrument_coverage,
486         instr_profile_output_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
487         config.instrument_gcov,
488         pgo_sample_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
489         config.debug_info_for_profiling,
490         llvm_selfprofiler,
491         selfprofile_before_pass_callback,
492         selfprofile_after_pass_callback,
493         extra_passes.as_ptr().cast(),
494         extra_passes.len(),
495         llvm_plugins.as_ptr().cast(),
496         llvm_plugins.len(),
497     );
498     result.into_result().map_err(|()| llvm_err(diag_handler, "failed to run LLVM passes"))
499 }
500
501 // Unsafe due to LLVM calls.
502 pub(crate) unsafe fn optimize(
503     cgcx: &CodegenContext<LlvmCodegenBackend>,
504     diag_handler: &Handler,
505     module: &ModuleCodegen<ModuleLlvm>,
506     config: &ModuleConfig,
507 ) -> Result<(), FatalError> {
508     let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_optimize", &*module.name);
509
510     let llmod = module.module_llvm.llmod();
511     let llcx = &*module.module_llvm.llcx;
512     let tm = &*module.module_llvm.tm;
513     let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
514
515     let module_name = module.name.clone();
516     let module_name = Some(&module_name[..]);
517
518     if let Some(false) = config.new_llvm_pass_manager && llvm_util::get_version() >= (15, 0, 0) {
519         diag_handler.warn(
520             "ignoring `-Z new-llvm-pass-manager=no`, which is no longer supported with LLVM 15",
521         );
522     }
523
524     if config.emit_no_opt_bc {
525         let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
526         let out = path_to_c_string(&out);
527         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
528     }
529
530     if let Some(opt_level) = config.opt_level {
531         if llvm_util::should_use_new_llvm_pass_manager(
532             &config.new_llvm_pass_manager,
533             &cgcx.target_arch,
534         ) {
535             let opt_stage = match cgcx.lto {
536                 Lto::Fat => llvm::OptStage::PreLinkFatLTO,
537                 Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
538                 _ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO,
539                 _ => llvm::OptStage::PreLinkNoLTO,
540             };
541             return optimize_with_new_llvm_pass_manager(
542                 cgcx,
543                 diag_handler,
544                 module,
545                 config,
546                 opt_level,
547                 opt_stage,
548             );
549         }
550
551         if cgcx.prof.llvm_recording_enabled() {
552             diag_handler
553                 .warn("`-Z self-profile-events = llvm` requires `-Z new-llvm-pass-manager`");
554         }
555
556         // Create the two optimizing pass managers. These mirror what clang
557         // does, and are by populated by LLVM's default PassManagerBuilder.
558         // Each manager has a different set of passes, but they also share
559         // some common passes.
560         let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
561         let mpm = llvm::LLVMCreatePassManager();
562
563         {
564             let find_pass = |pass_name: &str| {
565                 let pass_name = SmallCStr::new(pass_name);
566                 llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr())
567             };
568
569             if config.verify_llvm_ir {
570                 // Verification should run as the very first pass.
571                 llvm::LLVMRustAddPass(fpm, find_pass("verify").unwrap());
572             }
573
574             let mut extra_passes = Vec::new();
575             let mut have_name_anon_globals_pass = false;
576
577             for pass_name in &config.passes {
578                 if pass_name == "lint" {
579                     // Linting should also be performed early, directly on the generated IR.
580                     llvm::LLVMRustAddPass(fpm, find_pass("lint").unwrap());
581                     continue;
582                 }
583
584                 if let Some(pass) = find_pass(pass_name) {
585                     extra_passes.push(pass);
586                 } else {
587                     diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass_name));
588                 }
589
590                 if pass_name == "name-anon-globals" {
591                     have_name_anon_globals_pass = true;
592                 }
593             }
594
595             // Instrumentation must be inserted before optimization,
596             // otherwise LLVM may optimize some functions away which
597             // breaks llvm-cov.
598             //
599             // This mirrors what Clang does in lib/CodeGen/BackendUtil.cpp.
600             if config.instrument_gcov {
601                 llvm::LLVMRustAddPass(mpm, find_pass("insert-gcov-profiling").unwrap());
602             }
603             if config.instrument_coverage {
604                 llvm::LLVMRustAddPass(mpm, find_pass("instrprof").unwrap());
605             }
606             if config.debug_info_for_profiling {
607                 llvm::LLVMRustAddPass(mpm, find_pass("add-discriminators").unwrap());
608             }
609
610             add_sanitizer_passes(config, &mut extra_passes);
611
612             // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
613             // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
614             // we'll get errors in LLVM.
615             let using_thin_buffers = config.bitcode_needed();
616             if !config.no_prepopulate_passes {
617                 llvm::LLVMAddAnalysisPasses(tm, fpm);
618                 llvm::LLVMAddAnalysisPasses(tm, mpm);
619                 let opt_level = to_llvm_opt_settings(opt_level).0;
620                 let prepare_for_thin_lto = cgcx.lto == Lto::Thin
621                     || cgcx.lto == Lto::ThinLocal
622                     || (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled());
623                 with_llvm_pmb(llmod, config, opt_level, prepare_for_thin_lto, &mut |b| {
624                     llvm::LLVMRustAddLastExtensionPasses(
625                         b,
626                         extra_passes.as_ptr(),
627                         extra_passes.len() as size_t,
628                     );
629                     llvm::LLVMRustPassManagerBuilderPopulateFunctionPassManager(b, fpm);
630                     llvm::LLVMRustPassManagerBuilderPopulateModulePassManager(b, mpm);
631                 });
632
633                 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
634                 if using_thin_buffers && !prepare_for_thin_lto {
635                     llvm::LLVMRustAddPass(mpm, find_pass("name-anon-globals").unwrap());
636                     have_name_anon_globals_pass = true;
637                 }
638             } else {
639                 // If we don't use the standard pipeline, directly populate the MPM
640                 // with the extra passes.
641                 for pass in extra_passes {
642                     llvm::LLVMRustAddPass(mpm, pass);
643                 }
644             }
645
646             if using_thin_buffers && !have_name_anon_globals_pass {
647                 // As described above, this will probably cause an error in LLVM
648                 if config.no_prepopulate_passes {
649                     diag_handler.err(
650                         "The current compilation is going to use thin LTO buffers \
651                                       without running LLVM's NameAnonGlobals pass. \
652                                       This will likely cause errors in LLVM. Consider adding \
653                                       -C passes=name-anon-globals to the compiler command line.",
654                     );
655                 } else {
656                     bug!(
657                         "We are using thin LTO buffers without running the NameAnonGlobals pass. \
658                           This will likely cause errors in LLVM and should never happen."
659                     );
660                 }
661             }
662         }
663
664         diag_handler.abort_if_errors();
665
666         // Finally, run the actual optimization passes
667         {
668             let _timer = cgcx.prof.extra_verbose_generic_activity(
669                 "LLVM_module_optimize_function_passes",
670                 &*module.name,
671             );
672             llvm::LLVMRustRunFunctionPassManager(fpm, llmod);
673         }
674         {
675             let _timer = cgcx.prof.extra_verbose_generic_activity(
676                 "LLVM_module_optimize_module_passes",
677                 &*module.name,
678             );
679             llvm::LLVMRunPassManager(mpm, llmod);
680         }
681
682         // Deallocate managers that we're now done with
683         llvm::LLVMDisposePassManager(fpm);
684         llvm::LLVMDisposePassManager(mpm);
685     }
686     Ok(())
687 }
688
689 unsafe fn add_sanitizer_passes(config: &ModuleConfig, passes: &mut Vec<&'static mut llvm::Pass>) {
690     if config.sanitizer.contains(SanitizerSet::ADDRESS) {
691         let recover = config.sanitizer_recover.contains(SanitizerSet::ADDRESS);
692         passes.push(llvm::LLVMRustCreateAddressSanitizerFunctionPass(recover));
693         passes.push(llvm::LLVMRustCreateModuleAddressSanitizerPass(recover));
694     }
695     if config.sanitizer.contains(SanitizerSet::MEMORY) {
696         let track_origins = config.sanitizer_memory_track_origins as c_int;
697         let recover = config.sanitizer_recover.contains(SanitizerSet::MEMORY);
698         passes.push(llvm::LLVMRustCreateMemorySanitizerPass(track_origins, recover));
699     }
700     if config.sanitizer.contains(SanitizerSet::THREAD) {
701         passes.push(llvm::LLVMRustCreateThreadSanitizerPass());
702     }
703     if config.sanitizer.contains(SanitizerSet::HWADDRESS) {
704         let recover = config.sanitizer_recover.contains(SanitizerSet::HWADDRESS);
705         passes.push(llvm::LLVMRustCreateHWAddressSanitizerPass(recover));
706     }
707 }
708
709 pub(crate) fn link(
710     cgcx: &CodegenContext<LlvmCodegenBackend>,
711     diag_handler: &Handler,
712     mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
713 ) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
714     use super::lto::{Linker, ModuleBuffer};
715     // Sort the modules by name to ensure to ensure deterministic behavior.
716     modules.sort_by(|a, b| a.name.cmp(&b.name));
717     let (first, elements) =
718         modules.split_first().expect("Bug! modules must contain at least one module.");
719
720     let mut linker = Linker::new(first.module_llvm.llmod());
721     for module in elements {
722         let _timer = cgcx.prof.generic_activity_with_arg("LLVM_link_module", &*module.name);
723         let buffer = ModuleBuffer::new(module.module_llvm.llmod());
724         linker.add(buffer.data()).map_err(|()| {
725             let msg = format!("failed to serialize module {:?}", module.name);
726             llvm_err(diag_handler, &msg)
727         })?;
728     }
729     drop(linker);
730     Ok(modules.remove(0))
731 }
732
733 pub(crate) unsafe fn codegen(
734     cgcx: &CodegenContext<LlvmCodegenBackend>,
735     diag_handler: &Handler,
736     module: ModuleCodegen<ModuleLlvm>,
737     config: &ModuleConfig,
738 ) -> Result<CompiledModule, FatalError> {
739     let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_codegen", &*module.name);
740     {
741         let llmod = module.module_llvm.llmod();
742         let llcx = &*module.module_llvm.llcx;
743         let tm = &*module.module_llvm.tm;
744         let module_name = module.name.clone();
745         let module_name = Some(&module_name[..]);
746         let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
747
748         if cgcx.msvc_imps_needed {
749             create_msvc_imps(cgcx, llcx, llmod);
750         }
751
752         // A codegen-specific pass manager is used to generate object
753         // files for an LLVM module.
754         //
755         // Apparently each of these pass managers is a one-shot kind of
756         // thing, so we create a new one for each type of output. The
757         // pass manager passed to the closure should be ensured to not
758         // escape the closure itself, and the manager should only be
759         // used once.
760         unsafe fn with_codegen<'ll, F, R>(
761             tm: &'ll llvm::TargetMachine,
762             llmod: &'ll llvm::Module,
763             no_builtins: bool,
764             f: F,
765         ) -> R
766         where
767             F: FnOnce(&'ll mut PassManager<'ll>) -> R,
768         {
769             let cpm = llvm::LLVMCreatePassManager();
770             llvm::LLVMAddAnalysisPasses(tm, cpm);
771             llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
772             f(cpm)
773         }
774
775         // Two things to note:
776         // - If object files are just LLVM bitcode we write bitcode, copy it to
777         //   the .o file, and delete the bitcode if it wasn't otherwise
778         //   requested.
779         // - If we don't have the integrated assembler then we need to emit
780         //   asm from LLVM and use `gcc` to create the object file.
781
782         let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
783         let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
784
785         if config.bitcode_needed() {
786             let _timer = cgcx
787                 .prof
788                 .generic_activity_with_arg("LLVM_module_codegen_make_bitcode", &*module.name);
789             let thin = ThinBuffer::new(llmod, config.emit_thin_lto);
790             let data = thin.data();
791
792             if let Some(bitcode_filename) = bc_out.file_name() {
793                 cgcx.prof.artifact_size(
794                     "llvm_bitcode",
795                     bitcode_filename.to_string_lossy(),
796                     data.len() as u64,
797                 );
798             }
799
800             if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
801                 let _timer = cgcx
802                     .prof
803                     .generic_activity_with_arg("LLVM_module_codegen_emit_bitcode", &*module.name);
804                 if let Err(e) = fs::write(&bc_out, data) {
805                     let msg = format!("failed to write bytecode to {}: {}", bc_out.display(), e);
806                     diag_handler.err(&msg);
807                 }
808             }
809
810             if config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full) {
811                 let _timer = cgcx
812                     .prof
813                     .generic_activity_with_arg("LLVM_module_codegen_embed_bitcode", &*module.name);
814                 embed_bitcode(cgcx, llcx, llmod, &config.bc_cmdline, data);
815             }
816         }
817
818         if config.emit_ir {
819             let _timer =
820                 cgcx.prof.generic_activity_with_arg("LLVM_module_codegen_emit_ir", &*module.name);
821             let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
822             let out_c = path_to_c_string(&out);
823
824             extern "C" fn demangle_callback(
825                 input_ptr: *const c_char,
826                 input_len: size_t,
827                 output_ptr: *mut c_char,
828                 output_len: size_t,
829             ) -> size_t {
830                 let input =
831                     unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
832
833                 let Ok(input) = str::from_utf8(input) else { return 0 };
834
835                 let output = unsafe {
836                     slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
837                 };
838                 let mut cursor = io::Cursor::new(output);
839
840                 let Ok(demangled) = rustc_demangle::try_demangle(input) else { return 0 };
841
842                 if write!(cursor, "{:#}", demangled).is_err() {
843                     // Possible only if provided buffer is not big enough
844                     return 0;
845                 }
846
847                 cursor.position() as size_t
848             }
849
850             let result = llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback);
851
852             if result == llvm::LLVMRustResult::Success {
853                 record_artifact_size(&cgcx.prof, "llvm_ir", &out);
854             }
855
856             result.into_result().map_err(|()| {
857                 let msg = format!("failed to write LLVM IR to {}", out.display());
858                 llvm_err(diag_handler, &msg)
859             })?;
860         }
861
862         if config.emit_asm {
863             let _timer =
864                 cgcx.prof.generic_activity_with_arg("LLVM_module_codegen_emit_asm", &*module.name);
865             let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
866
867             // We can't use the same module for asm and object code output,
868             // because that triggers various errors like invalid IR or broken
869             // binaries. So we must clone the module to produce the asm output
870             // if we are also producing object code.
871             let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
872                 llvm::LLVMCloneModule(llmod)
873             } else {
874                 llmod
875             };
876             with_codegen(tm, llmod, config.no_builtins, |cpm| {
877                 write_output_file(
878                     diag_handler,
879                     tm,
880                     cpm,
881                     llmod,
882                     &path,
883                     None,
884                     llvm::FileType::AssemblyFile,
885                     &cgcx.prof,
886                 )
887             })?;
888         }
889
890         match config.emit_obj {
891             EmitObj::ObjectCode(_) => {
892                 let _timer = cgcx
893                     .prof
894                     .generic_activity_with_arg("LLVM_module_codegen_emit_obj", &*module.name);
895
896                 let dwo_out = cgcx.output_filenames.temp_path_dwo(module_name);
897                 let dwo_out = match (cgcx.split_debuginfo, cgcx.split_dwarf_kind) {
898                     // Don't change how DWARF is emitted when disabled.
899                     (SplitDebuginfo::Off, _) => None,
900                     // Don't provide a DWARF object path if split debuginfo is enabled but this is
901                     // a platform that doesn't support Split DWARF.
902                     _ if !cgcx.target_can_use_split_dwarf => None,
903                     // Don't provide a DWARF object path in single mode, sections will be written
904                     // into the object as normal but ignored by linker.
905                     (_, SplitDwarfKind::Single) => None,
906                     // Emit (a subset of the) DWARF into a separate dwarf object file in split
907                     // mode.
908                     (_, SplitDwarfKind::Split) => Some(dwo_out.as_path()),
909                 };
910
911                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
912                     write_output_file(
913                         diag_handler,
914                         tm,
915                         cpm,
916                         llmod,
917                         &obj_out,
918                         dwo_out,
919                         llvm::FileType::ObjectFile,
920                         &cgcx.prof,
921                     )
922                 })?;
923             }
924
925             EmitObj::Bitcode => {
926                 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
927                 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
928                     diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
929                 }
930
931                 if !config.emit_bc {
932                     debug!("removing_bitcode {:?}", bc_out);
933                     ensure_removed(diag_handler, &bc_out);
934                 }
935             }
936
937             EmitObj::None => {}
938         }
939
940         drop(handlers);
941     }
942
943     Ok(module.into_compiled_module(
944         config.emit_obj != EmitObj::None,
945         cgcx.target_can_use_split_dwarf
946             && cgcx.split_debuginfo != SplitDebuginfo::Off
947             && cgcx.split_dwarf_kind == SplitDwarfKind::Split,
948         config.emit_bc,
949         &cgcx.output_filenames,
950     ))
951 }
952
953 fn create_section_with_flags_asm(section_name: &str, section_flags: &str, data: &[u8]) -> Vec<u8> {
954     let mut asm = format!(".section {},\"{}\"\n", section_name, section_flags).into_bytes();
955     asm.extend_from_slice(b".ascii \"");
956     asm.reserve(data.len());
957     for &byte in data {
958         if byte == b'\\' || byte == b'"' {
959             asm.push(b'\\');
960             asm.push(byte);
961         } else if byte < 0x20 || byte >= 0x80 {
962             // Avoid non UTF-8 inline assembly. Use octal escape sequence, because it is fixed
963             // width, while hex escapes will consume following characters.
964             asm.push(b'\\');
965             asm.push(b'0' + ((byte >> 6) & 0x7));
966             asm.push(b'0' + ((byte >> 3) & 0x7));
967             asm.push(b'0' + ((byte >> 0) & 0x7));
968         } else {
969             asm.push(byte);
970         }
971     }
972     asm.extend_from_slice(b"\"\n");
973     asm
974 }
975
976 /// Embed the bitcode of an LLVM module in the LLVM module itself.
977 ///
978 /// This is done primarily for iOS where it appears to be standard to compile C
979 /// code at least with `-fembed-bitcode` which creates two sections in the
980 /// executable:
981 ///
982 /// * __LLVM,__bitcode
983 /// * __LLVM,__cmdline
984 ///
985 /// It appears *both* of these sections are necessary to get the linker to
986 /// recognize what's going on. A suitable cmdline value is taken from the
987 /// target spec.
988 ///
989 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
990 /// embed an empty section.
991 ///
992 /// Basically all of this is us attempting to follow in the footsteps of clang
993 /// on iOS. See #35968 for lots more info.
994 unsafe fn embed_bitcode(
995     cgcx: &CodegenContext<LlvmCodegenBackend>,
996     llcx: &llvm::Context,
997     llmod: &llvm::Module,
998     cmdline: &str,
999     bitcode: &[u8],
1000 ) {
1001     // We're adding custom sections to the output object file, but we definitely
1002     // do not want these custom sections to make their way into the final linked
1003     // executable. The purpose of these custom sections is for tooling
1004     // surrounding object files to work with the LLVM IR, if necessary. For
1005     // example rustc's own LTO will look for LLVM IR inside of the object file
1006     // in these sections by default.
1007     //
1008     // To handle this is a bit different depending on the object file format
1009     // used by the backend, broken down into a few different categories:
1010     //
1011     // * Mach-O - this is for macOS. Inspecting the source code for the native
1012     //   linker here shows that the `.llvmbc` and `.llvmcmd` sections are
1013     //   automatically skipped by the linker. In that case there's nothing extra
1014     //   that we need to do here.
1015     //
1016     // * Wasm - the native LLD linker is hard-coded to skip `.llvmbc` and
1017     //   `.llvmcmd` sections, so there's nothing extra we need to do.
1018     //
1019     // * COFF - if we don't do anything the linker will by default copy all
1020     //   these sections to the output artifact, not what we want! To subvert
1021     //   this we want to flag the sections we inserted here as
1022     //   `IMAGE_SCN_LNK_REMOVE`.
1023     //
1024     // * ELF - this is very similar to COFF above. One difference is that these
1025     //   sections are removed from the output linked artifact when
1026     //   `--gc-sections` is passed, which we pass by default. If that flag isn't
1027     //   passed though then these sections will show up in the final output.
1028     //   Additionally the flag that we need to set here is `SHF_EXCLUDE`.
1029     //
1030     // Unfortunately, LLVM provides no way to set custom section flags. For ELF
1031     // and COFF we emit the sections using module level inline assembly for that
1032     // reason (see issue #90326 for historical background).
1033     let is_apple = cgcx.opts.target_triple.triple().contains("-ios")
1034         || cgcx.opts.target_triple.triple().contains("-darwin")
1035         || cgcx.opts.target_triple.triple().contains("-tvos")
1036         || cgcx.opts.target_triple.triple().contains("-watchos");
1037     if is_apple
1038         || cgcx.opts.target_triple.triple().starts_with("wasm")
1039         || cgcx.opts.target_triple.triple().starts_with("asmjs")
1040     {
1041         // We don't need custom section flags, create LLVM globals.
1042         let llconst = common::bytes_in_context(llcx, bitcode);
1043         let llglobal = llvm::LLVMAddGlobal(
1044             llmod,
1045             common::val_ty(llconst),
1046             "rustc.embedded.module\0".as_ptr().cast(),
1047         );
1048         llvm::LLVMSetInitializer(llglobal, llconst);
1049
1050         let section = if is_apple { "__LLVM,__bitcode\0" } else { ".llvmbc\0" };
1051         llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
1052         llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
1053         llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
1054
1055         let llconst = common::bytes_in_context(llcx, cmdline.as_bytes());
1056         let llglobal = llvm::LLVMAddGlobal(
1057             llmod,
1058             common::val_ty(llconst),
1059             "rustc.embedded.cmdline\0".as_ptr().cast(),
1060         );
1061         llvm::LLVMSetInitializer(llglobal, llconst);
1062         let section = if is_apple { "__LLVM,__cmdline\0" } else { ".llvmcmd\0" };
1063         llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
1064         llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
1065     } else {
1066         // We need custom section flags, so emit module-level inline assembly.
1067         let section_flags = if cgcx.is_pe_coff { "n" } else { "e" };
1068         let asm = create_section_with_flags_asm(".llvmbc", section_flags, bitcode);
1069         llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
1070         let asm = create_section_with_flags_asm(".llvmcmd", section_flags, cmdline.as_bytes());
1071         llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
1072     }
1073 }
1074
1075 pub unsafe fn with_llvm_pmb(
1076     llmod: &llvm::Module,
1077     config: &ModuleConfig,
1078     opt_level: llvm::CodeGenOptLevel,
1079     prepare_for_thin_lto: bool,
1080     f: &mut dyn FnMut(&llvm::PassManagerBuilder),
1081 ) {
1082     use std::ptr;
1083
1084     // Create the PassManagerBuilder for LLVM. We configure it with
1085     // reasonable defaults and prepare it to actually populate the pass
1086     // manager.
1087     let builder = llvm::LLVMRustPassManagerBuilderCreate();
1088     let opt_size = config.opt_size.map_or(llvm::CodeGenOptSizeNone, |x| to_llvm_opt_settings(x).1);
1089     let inline_threshold = config.inline_threshold;
1090     let pgo_gen_path = get_pgo_gen_path(config);
1091     let pgo_use_path = get_pgo_use_path(config);
1092     let pgo_sample_use_path = get_pgo_sample_use_path(config);
1093
1094     llvm::LLVMRustConfigurePassManagerBuilder(
1095         builder,
1096         opt_level,
1097         config.merge_functions,
1098         config.vectorize_slp,
1099         config.vectorize_loop,
1100         prepare_for_thin_lto,
1101         pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
1102         pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
1103         pgo_sample_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
1104         opt_size as c_int,
1105     );
1106
1107     llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
1108
1109     // Here we match what clang does (kinda). For O0 we only inline
1110     // always-inline functions (but don't add lifetime intrinsics), at O1 we
1111     // inline with lifetime intrinsics, and O2+ we add an inliner with a
1112     // thresholds copied from clang.
1113     match (opt_level, opt_size, inline_threshold) {
1114         (.., Some(t)) => {
1115             llvm::LLVMRustPassManagerBuilderUseInlinerWithThreshold(builder, t);
1116         }
1117         (llvm::CodeGenOptLevel::Aggressive, ..) => {
1118             llvm::LLVMRustPassManagerBuilderUseInlinerWithThreshold(builder, 275);
1119         }
1120         (_, llvm::CodeGenOptSizeDefault, _) => {
1121             llvm::LLVMRustPassManagerBuilderUseInlinerWithThreshold(builder, 75);
1122         }
1123         (_, llvm::CodeGenOptSizeAggressive, _) => {
1124             llvm::LLVMRustPassManagerBuilderUseInlinerWithThreshold(builder, 25);
1125         }
1126         (llvm::CodeGenOptLevel::None, ..) => {
1127             llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
1128         }
1129         (llvm::CodeGenOptLevel::Less, ..) => {
1130             llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
1131         }
1132         (llvm::CodeGenOptLevel::Default, ..) => {
1133             llvm::LLVMRustPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1134         }
1135     }
1136
1137     f(builder);
1138     llvm::LLVMRustPassManagerBuilderDispose(builder);
1139 }
1140
1141 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
1142 // This is required to satisfy `dllimport` references to static data in .rlibs
1143 // when using MSVC linker.  We do this only for data, as linker can fix up
1144 // code references on its own.
1145 // See #26591, #27438
1146 fn create_msvc_imps(
1147     cgcx: &CodegenContext<LlvmCodegenBackend>,
1148     llcx: &llvm::Context,
1149     llmod: &llvm::Module,
1150 ) {
1151     if !cgcx.msvc_imps_needed {
1152         return;
1153     }
1154     // The x86 ABI seems to require that leading underscores are added to symbol
1155     // names, so we need an extra underscore on x86. There's also a leading
1156     // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
1157     // underscores added in front).
1158     let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" };
1159
1160     unsafe {
1161         let i8p_ty = Type::i8p_llcx(llcx);
1162         let globals = base::iter_globals(llmod)
1163             .filter(|&val| {
1164                 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage
1165                     && llvm::LLVMIsDeclaration(val) == 0
1166             })
1167             .filter_map(|val| {
1168                 // Exclude some symbols that we know are not Rust symbols.
1169                 let name = llvm::get_value_name(val);
1170                 if ignored(name) { None } else { Some((val, name)) }
1171             })
1172             .map(move |(val, name)| {
1173                 let mut imp_name = prefix.as_bytes().to_vec();
1174                 imp_name.extend(name);
1175                 let imp_name = CString::new(imp_name).unwrap();
1176                 (imp_name, val)
1177             })
1178             .collect::<Vec<_>>();
1179
1180         for (imp_name, val) in globals {
1181             let imp = llvm::LLVMAddGlobal(llmod, i8p_ty, imp_name.as_ptr().cast());
1182             llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
1183             llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
1184         }
1185     }
1186
1187     // Use this function to exclude certain symbols from `__imp` generation.
1188     fn ignored(symbol_name: &[u8]) -> bool {
1189         // These are symbols generated by LLVM's profiling instrumentation
1190         symbol_name.starts_with(b"__llvm_profile_")
1191     }
1192 }
1193
1194 fn record_artifact_size(
1195     self_profiler_ref: &SelfProfilerRef,
1196     artifact_kind: &'static str,
1197     path: &Path,
1198 ) {
1199     // Don't stat the file if we are not going to record its size.
1200     if !self_profiler_ref.enabled() {
1201         return;
1202     }
1203
1204     if let Some(artifact_name) = path.file_name() {
1205         let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
1206         self_profiler_ref.artifact_size(artifact_kind, artifact_name.to_string_lossy(), file_size);
1207     }
1208 }