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