rustc_codegen_llvm/back/
write.rs

1use std::ffi::{CStr, CString};
2use std::io::{self, Write};
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5use std::{fs, slice, str};
6
7use libc::{c_char, c_int, c_void, size_t};
8use llvm::{
9    LLVMRustLLVMHasZlibCompressionForDebugSymbols, LLVMRustLLVMHasZstdCompressionForDebugSymbols,
10};
11use rustc_codegen_ssa::back::link::ensure_removed;
12use rustc_codegen_ssa::back::versioned_llvm_target;
13use rustc_codegen_ssa::back::write::{
14    BitcodeSection, CodegenContext, EmitObj, ModuleConfig, TargetMachineFactoryConfig,
15    TargetMachineFactoryFn,
16};
17use rustc_codegen_ssa::traits::*;
18use rustc_codegen_ssa::{CompiledModule, ModuleCodegen};
19use rustc_data_structures::profiling::SelfProfilerRef;
20use rustc_data_structures::small_c_str::SmallCStr;
21use rustc_errors::{DiagCtxtHandle, FatalError, Level};
22use rustc_fs_util::{link_or_copy, path_to_c_string};
23use rustc_middle::ty::TyCtxt;
24use rustc_session::Session;
25use rustc_session::config::{
26    self, Lto, OutputType, Passes, RemapPathScopeComponents, SplitDwarfKind, SwitchWithOptPath,
27};
28use rustc_span::{BytePos, InnerSpan, Pos, SpanData, SyntaxContext, sym};
29use rustc_target::spec::{CodeModel, FloatAbi, RelocModel, SanitizerSet, SplitDebuginfo, TlsModel};
30use tracing::{debug, trace};
31
32use crate::back::lto::ThinBuffer;
33use crate::back::owned_target_machine::OwnedTargetMachine;
34use crate::back::profiling::{
35    LlvmSelfProfiler, selfprofile_after_pass_callback, selfprofile_before_pass_callback,
36};
37use crate::common::AsCCharPtr;
38use crate::errors::{
39    CopyBitcode, FromLlvmDiag, FromLlvmOptimizationDiag, LlvmError, UnknownCompression,
40    WithLlvmError, WriteBytecode,
41};
42use crate::llvm::diagnostic::OptimizationDiagnosticKind::*;
43use crate::llvm::{self, DiagnosticInfo};
44use crate::type_::Type;
45use crate::{LlvmCodegenBackend, ModuleLlvm, base, common, llvm_util};
46
47pub(crate) fn llvm_err<'a>(dcx: DiagCtxtHandle<'_>, err: LlvmError<'a>) -> FatalError {
48    match llvm::last_error() {
49        Some(llvm_err) => dcx.emit_almost_fatal(WithLlvmError(err, llvm_err)),
50        None => dcx.emit_almost_fatal(err),
51    }
52}
53
54fn write_output_file<'ll>(
55    dcx: DiagCtxtHandle<'_>,
56    target: &'ll llvm::TargetMachine,
57    no_builtins: bool,
58    m: &'ll llvm::Module,
59    output: &Path,
60    dwo_output: Option<&Path>,
61    file_type: llvm::FileType,
62    self_profiler_ref: &SelfProfilerRef,
63    verify_llvm_ir: bool,
64) -> Result<(), FatalError> {
65    debug!("write_output_file output={:?} dwo_output={:?}", output, dwo_output);
66    let output_c = path_to_c_string(output);
67    let dwo_output_c;
68    let dwo_output_ptr = if let Some(dwo_output) = dwo_output {
69        dwo_output_c = path_to_c_string(dwo_output);
70        dwo_output_c.as_ptr()
71    } else {
72        std::ptr::null()
73    };
74    let result = unsafe {
75        let pm = llvm::LLVMCreatePassManager();
76        llvm::LLVMAddAnalysisPasses(target, pm);
77        llvm::LLVMRustAddLibraryInfo(pm, m, no_builtins);
78        llvm::LLVMRustWriteOutputFile(
79            target,
80            pm,
81            m,
82            output_c.as_ptr(),
83            dwo_output_ptr,
84            file_type,
85            verify_llvm_ir,
86        )
87    };
88
89    // Record artifact sizes for self-profiling
90    if result == llvm::LLVMRustResult::Success {
91        let artifact_kind = match file_type {
92            llvm::FileType::ObjectFile => "object_file",
93            llvm::FileType::AssemblyFile => "assembly_file",
94        };
95        record_artifact_size(self_profiler_ref, artifact_kind, output);
96        if let Some(dwo_file) = dwo_output {
97            record_artifact_size(self_profiler_ref, "dwo_file", dwo_file);
98        }
99    }
100
101    result.into_result().map_err(|()| llvm_err(dcx, LlvmError::WriteOutput { path: output }))
102}
103
104pub(crate) fn create_informational_target_machine(
105    sess: &Session,
106    only_base_features: bool,
107) -> OwnedTargetMachine {
108    let config = TargetMachineFactoryConfig { split_dwarf_file: None, output_obj_file: None };
109    // Can't use query system here quite yet because this function is invoked before the query
110    // system/tcx is set up.
111    let features = llvm_util::global_llvm_features(sess, false, only_base_features);
112    target_machine_factory(sess, config::OptLevel::No, &features)(config)
113        .unwrap_or_else(|err| llvm_err(sess.dcx(), err).raise())
114}
115
116pub(crate) fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> OwnedTargetMachine {
117    let split_dwarf_file = if tcx.sess.target_can_use_split_dwarf() {
118        tcx.output_filenames(()).split_dwarf_path(
119            tcx.sess.split_debuginfo(),
120            tcx.sess.opts.unstable_opts.split_dwarf_kind,
121            Some(mod_name),
122        )
123    } else {
124        None
125    };
126
127    let output_obj_file =
128        Some(tcx.output_filenames(()).temp_path(OutputType::Object, Some(mod_name)));
129    let config = TargetMachineFactoryConfig { split_dwarf_file, output_obj_file };
130
131    target_machine_factory(
132        tcx.sess,
133        tcx.backend_optimization_level(()),
134        tcx.global_backend_features(()),
135    )(config)
136    .unwrap_or_else(|err| llvm_err(tcx.dcx(), err).raise())
137}
138
139fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
140    use self::config::OptLevel::*;
141    match cfg {
142        No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
143        Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
144        More => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
145        Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
146        Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
147        SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
148    }
149}
150
151fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel {
152    use config::OptLevel::*;
153    match cfg {
154        No => llvm::PassBuilderOptLevel::O0,
155        Less => llvm::PassBuilderOptLevel::O1,
156        More => llvm::PassBuilderOptLevel::O2,
157        Aggressive => llvm::PassBuilderOptLevel::O3,
158        Size => llvm::PassBuilderOptLevel::Os,
159        SizeMin => llvm::PassBuilderOptLevel::Oz,
160    }
161}
162
163fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
164    match relocation_model {
165        RelocModel::Static => llvm::RelocModel::Static,
166        // LLVM doesn't have a PIE relocation model, it represents PIE as PIC with an extra
167        // attribute.
168        RelocModel::Pic | RelocModel::Pie => llvm::RelocModel::PIC,
169        RelocModel::DynamicNoPic => llvm::RelocModel::DynamicNoPic,
170        RelocModel::Ropi => llvm::RelocModel::ROPI,
171        RelocModel::Rwpi => llvm::RelocModel::RWPI,
172        RelocModel::RopiRwpi => llvm::RelocModel::ROPI_RWPI,
173    }
174}
175
176pub(crate) fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeModel {
177    match code_model {
178        Some(CodeModel::Tiny) => llvm::CodeModel::Tiny,
179        Some(CodeModel::Small) => llvm::CodeModel::Small,
180        Some(CodeModel::Kernel) => llvm::CodeModel::Kernel,
181        Some(CodeModel::Medium) => llvm::CodeModel::Medium,
182        Some(CodeModel::Large) => llvm::CodeModel::Large,
183        None => llvm::CodeModel::None,
184    }
185}
186
187fn to_llvm_float_abi(float_abi: Option<FloatAbi>) -> llvm::FloatAbi {
188    match float_abi {
189        None => llvm::FloatAbi::Default,
190        Some(FloatAbi::Soft) => llvm::FloatAbi::Soft,
191        Some(FloatAbi::Hard) => llvm::FloatAbi::Hard,
192    }
193}
194
195pub(crate) fn target_machine_factory(
196    sess: &Session,
197    optlvl: config::OptLevel,
198    target_features: &[String],
199) -> TargetMachineFactoryFn<LlvmCodegenBackend> {
200    let reloc_model = to_llvm_relocation_model(sess.relocation_model());
201
202    let (opt_level, _) = to_llvm_opt_settings(optlvl);
203    let float_abi = if sess.target.arch == "arm" && sess.opts.cg.soft_float {
204        llvm::FloatAbi::Soft
205    } else {
206        // `validate_commandline_args_with_session_available` has already warned about this being
207        // ignored. Let's make sure LLVM doesn't suddenly start using this flag on more targets.
208        to_llvm_float_abi(sess.target.llvm_floatabi)
209    };
210
211    let ffunction_sections =
212        sess.opts.unstable_opts.function_sections.unwrap_or(sess.target.function_sections);
213    let fdata_sections = ffunction_sections;
214    let funique_section_names = !sess.opts.unstable_opts.no_unique_section_names;
215
216    let code_model = to_llvm_code_model(sess.code_model());
217
218    let mut singlethread = sess.target.singlethread;
219
220    // On the wasm target once the `atomics` feature is enabled that means that
221    // we're no longer single-threaded, or otherwise we don't want LLVM to
222    // lower atomic operations to single-threaded operations.
223    if singlethread && sess.target.is_like_wasm && sess.target_features.contains(&sym::atomics) {
224        singlethread = false;
225    }
226
227    let triple = SmallCStr::new(&versioned_llvm_target(sess));
228    let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
229    let features = CString::new(target_features.join(",")).unwrap();
230    let abi = SmallCStr::new(&sess.target.llvm_abiname);
231    let trap_unreachable =
232        sess.opts.unstable_opts.trap_unreachable.unwrap_or(sess.target.trap_unreachable);
233    let emit_stack_size_section = sess.opts.unstable_opts.emit_stack_sizes;
234
235    let verbose_asm = sess.opts.unstable_opts.verbose_asm;
236    let relax_elf_relocations =
237        sess.opts.unstable_opts.relax_elf_relocations.unwrap_or(sess.target.relax_elf_relocations);
238
239    let use_init_array =
240        !sess.opts.unstable_opts.use_ctors_section.unwrap_or(sess.target.use_ctors_section);
241
242    let path_mapping = sess.source_map().path_mapping().clone();
243
244    let use_emulated_tls = matches!(sess.tls_model(), TlsModel::Emulated);
245
246    // copy the exe path, followed by path all into one buffer
247    // null terminating them so we can use them as null terminated strings
248    let args_cstr_buff = {
249        let mut args_cstr_buff: Vec<u8> = Vec::new();
250        let exe_path = std::env::current_exe().unwrap_or_default();
251        let exe_path_str = exe_path.into_os_string().into_string().unwrap_or_default();
252
253        args_cstr_buff.extend_from_slice(exe_path_str.as_bytes());
254        args_cstr_buff.push(0);
255
256        for arg in sess.expanded_args.iter() {
257            args_cstr_buff.extend_from_slice(arg.as_bytes());
258            args_cstr_buff.push(0);
259        }
260
261        args_cstr_buff
262    };
263
264    let debuginfo_compression = sess.opts.debuginfo_compression.to_string();
265    match sess.opts.debuginfo_compression {
266        rustc_session::config::DebugInfoCompression::Zlib => {
267            if !unsafe { LLVMRustLLVMHasZlibCompressionForDebugSymbols() } {
268                sess.dcx().emit_warn(UnknownCompression { algorithm: "zlib" });
269            }
270        }
271        rustc_session::config::DebugInfoCompression::Zstd => {
272            if !unsafe { LLVMRustLLVMHasZstdCompressionForDebugSymbols() } {
273                sess.dcx().emit_warn(UnknownCompression { algorithm: "zstd" });
274            }
275        }
276        rustc_session::config::DebugInfoCompression::None => {}
277    };
278    let debuginfo_compression = SmallCStr::new(&debuginfo_compression);
279
280    let file_name_display_preference =
281        sess.filename_display_preference(RemapPathScopeComponents::DEBUGINFO);
282
283    Arc::new(move |config: TargetMachineFactoryConfig| {
284        let path_to_cstring_helper = |path: Option<PathBuf>| -> CString {
285            let path = path.unwrap_or_default();
286            let path = path_mapping
287                .to_real_filename(path)
288                .to_string_lossy(file_name_display_preference)
289                .into_owned();
290            CString::new(path).unwrap()
291        };
292
293        let split_dwarf_file = path_to_cstring_helper(config.split_dwarf_file);
294        let output_obj_file = path_to_cstring_helper(config.output_obj_file);
295
296        OwnedTargetMachine::new(
297            &triple,
298            &cpu,
299            &features,
300            &abi,
301            code_model,
302            reloc_model,
303            opt_level,
304            float_abi,
305            ffunction_sections,
306            fdata_sections,
307            funique_section_names,
308            trap_unreachable,
309            singlethread,
310            verbose_asm,
311            emit_stack_size_section,
312            relax_elf_relocations,
313            use_init_array,
314            &split_dwarf_file,
315            &output_obj_file,
316            &debuginfo_compression,
317            use_emulated_tls,
318            &args_cstr_buff,
319        )
320    })
321}
322
323pub(crate) fn save_temp_bitcode(
324    cgcx: &CodegenContext<LlvmCodegenBackend>,
325    module: &ModuleCodegen<ModuleLlvm>,
326    name: &str,
327) {
328    if !cgcx.save_temps {
329        return;
330    }
331    let ext = format!("{name}.bc");
332    let cgu = Some(&module.name[..]);
333    let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
334    write_bitcode_to_file(module, &path)
335}
336
337fn write_bitcode_to_file(module: &ModuleCodegen<ModuleLlvm>, path: &Path) {
338    unsafe {
339        let path = path_to_c_string(&path);
340        let llmod = module.module_llvm.llmod();
341        llvm::LLVMWriteBitcodeToFile(llmod, path.as_ptr());
342    }
343}
344
345/// In what context is a dignostic handler being attached to a codegen unit?
346pub(crate) enum CodegenDiagnosticsStage {
347    /// Prelink optimization stage.
348    Opt,
349    /// LTO/ThinLTO postlink optimization stage.
350    LTO,
351    /// Code generation.
352    Codegen,
353}
354
355pub(crate) struct DiagnosticHandlers<'a> {
356    data: *mut (&'a CodegenContext<LlvmCodegenBackend>, DiagCtxtHandle<'a>),
357    llcx: &'a llvm::Context,
358    old_handler: Option<&'a llvm::DiagnosticHandler>,
359}
360
361impl<'a> DiagnosticHandlers<'a> {
362    pub(crate) fn new(
363        cgcx: &'a CodegenContext<LlvmCodegenBackend>,
364        dcx: DiagCtxtHandle<'a>,
365        llcx: &'a llvm::Context,
366        module: &ModuleCodegen<ModuleLlvm>,
367        stage: CodegenDiagnosticsStage,
368    ) -> Self {
369        let remark_passes_all: bool;
370        let remark_passes: Vec<CString>;
371        match &cgcx.remark {
372            Passes::All => {
373                remark_passes_all = true;
374                remark_passes = Vec::new();
375            }
376            Passes::Some(passes) => {
377                remark_passes_all = false;
378                remark_passes =
379                    passes.iter().map(|name| CString::new(name.as_str()).unwrap()).collect();
380            }
381        };
382        let remark_passes: Vec<*const c_char> =
383            remark_passes.iter().map(|name: &CString| name.as_ptr()).collect();
384        let remark_file = cgcx
385            .remark_dir
386            .as_ref()
387            // Use the .opt.yaml file suffix, which is supported by LLVM's opt-viewer.
388            .map(|dir| {
389                let stage_suffix = match stage {
390                    CodegenDiagnosticsStage::Codegen => "codegen",
391                    CodegenDiagnosticsStage::Opt => "opt",
392                    CodegenDiagnosticsStage::LTO => "lto",
393                };
394                dir.join(format!("{}.{stage_suffix}.opt.yaml", module.name))
395            })
396            .and_then(|dir| dir.to_str().and_then(|p| CString::new(p).ok()));
397
398        let pgo_available = cgcx.opts.cg.profile_use.is_some();
399        let data = Box::into_raw(Box::new((cgcx, dcx)));
400        unsafe {
401            let old_handler = llvm::LLVMRustContextGetDiagnosticHandler(llcx);
402            llvm::LLVMRustContextConfigureDiagnosticHandler(
403                llcx,
404                diagnostic_handler,
405                data.cast(),
406                remark_passes_all,
407                remark_passes.as_ptr(),
408                remark_passes.len(),
409                // The `as_ref()` is important here, otherwise the `CString` will be dropped
410                // too soon!
411                remark_file.as_ref().map(|dir| dir.as_ptr()).unwrap_or(std::ptr::null()),
412                pgo_available,
413            );
414            DiagnosticHandlers { data, llcx, old_handler }
415        }
416    }
417}
418
419impl<'a> Drop for DiagnosticHandlers<'a> {
420    fn drop(&mut self) {
421        unsafe {
422            llvm::LLVMRustContextSetDiagnosticHandler(self.llcx, self.old_handler);
423            drop(Box::from_raw(self.data));
424        }
425    }
426}
427
428fn report_inline_asm(
429    cgcx: &CodegenContext<LlvmCodegenBackend>,
430    msg: String,
431    level: llvm::DiagnosticLevel,
432    cookie: u64,
433    source: Option<(String, Vec<InnerSpan>)>,
434) {
435    // In LTO build we may get srcloc values from other crates which are invalid
436    // since they use a different source map. To be safe we just suppress these
437    // in LTO builds.
438    let span = if cookie == 0 || matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
439        SpanData::default()
440    } else {
441        let lo = BytePos::from_u32(cookie as u32);
442        let hi = BytePos::from_u32((cookie >> 32) as u32);
443        SpanData {
444            lo,
445            // LLVM version < 19 silently truncates the cookie to 32 bits in some situations.
446            hi: if hi.to_u32() != 0 { hi } else { lo },
447            ctxt: SyntaxContext::root(),
448            parent: None,
449        }
450    };
451    let level = match level {
452        llvm::DiagnosticLevel::Error => Level::Error,
453        llvm::DiagnosticLevel::Warning => Level::Warning,
454        llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
455    };
456    let msg = msg.strip_prefix("error: ").unwrap_or(&msg).to_string();
457    cgcx.diag_emitter.inline_asm_error(span, msg, level, source);
458}
459
460unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
461    if user.is_null() {
462        return;
463    }
464    let (cgcx, dcx) =
465        unsafe { *(user as *const (&CodegenContext<LlvmCodegenBackend>, DiagCtxtHandle<'_>)) };
466
467    match unsafe { llvm::diagnostic::Diagnostic::unpack(info) } {
468        llvm::diagnostic::InlineAsm(inline) => {
469            report_inline_asm(cgcx, inline.message, inline.level, inline.cookie, inline.source);
470        }
471
472        llvm::diagnostic::Optimization(opt) => {
473            dcx.emit_note(FromLlvmOptimizationDiag {
474                filename: &opt.filename,
475                line: opt.line,
476                column: opt.column,
477                pass_name: &opt.pass_name,
478                kind: match opt.kind {
479                    OptimizationRemark => "success",
480                    OptimizationMissed | OptimizationFailure => "missed",
481                    OptimizationAnalysis
482                    | OptimizationAnalysisFPCommute
483                    | OptimizationAnalysisAliasing => "analysis",
484                    OptimizationRemarkOther => "other",
485                },
486                message: &opt.message,
487            });
488        }
489        llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
490            let message = llvm::build_string(|s| unsafe {
491                llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
492            })
493            .expect("non-UTF8 diagnostic");
494            dcx.emit_warn(FromLlvmDiag { message });
495        }
496        llvm::diagnostic::Unsupported(diagnostic_ref) => {
497            let message = llvm::build_string(|s| unsafe {
498                llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
499            })
500            .expect("non-UTF8 diagnostic");
501            dcx.emit_err(FromLlvmDiag { message });
502        }
503        llvm::diagnostic::UnknownDiagnostic(..) => {}
504    }
505}
506
507fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
508    match config.pgo_gen {
509        SwitchWithOptPath::Enabled(ref opt_dir_path) => {
510            let path = if let Some(dir_path) = opt_dir_path {
511                dir_path.join("default_%m.profraw")
512            } else {
513                PathBuf::from("default_%m.profraw")
514            };
515
516            Some(CString::new(format!("{}", path.display())).unwrap())
517        }
518        SwitchWithOptPath::Disabled => None,
519    }
520}
521
522fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
523    config
524        .pgo_use
525        .as_ref()
526        .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
527}
528
529fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option<CString> {
530    config
531        .pgo_sample_use
532        .as_ref()
533        .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
534}
535
536fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> {
537    config.instrument_coverage.then(|| c"default_%m_%p.profraw".to_owned())
538}
539
540// PreAD will run llvm opts but disable size increasing opts (vectorization, loop unrolling)
541// DuringAD is the same as above, but also runs the enzyme opt and autodiff passes.
542// PostAD will run all opts, including size increasing opts.
543#[derive(Debug, Eq, PartialEq)]
544pub(crate) enum AutodiffStage {
545    PreAD,
546    DuringAD,
547    PostAD,
548}
549
550pub(crate) unsafe fn llvm_optimize(
551    cgcx: &CodegenContext<LlvmCodegenBackend>,
552    dcx: DiagCtxtHandle<'_>,
553    module: &ModuleCodegen<ModuleLlvm>,
554    config: &ModuleConfig,
555    opt_level: config::OptLevel,
556    opt_stage: llvm::OptStage,
557    autodiff_stage: AutodiffStage,
558) -> Result<(), FatalError> {
559    // Enzyme:
560    // The whole point of compiler based AD is to differentiate optimized IR instead of unoptimized
561    // source code. However, benchmarks show that optimizations increasing the code size
562    // tend to reduce AD performance. Therefore deactivate them before AD, then differentiate the code
563    // and finally re-optimize the module, now with all optimizations available.
564    // FIXME(ZuseZ4): In a future update we could figure out how to only optimize individual functions getting
565    // differentiated.
566
567    let unroll_loops;
568    let vectorize_slp;
569    let vectorize_loop;
570    let run_enzyme = cfg!(llvm_enzyme) && autodiff_stage == AutodiffStage::DuringAD;
571
572    // When we build rustc with enzyme/autodiff support, we want to postpone size-increasing
573    // optimizations until after differentiation. Our pipeline is thus: (opt + enzyme), (full opt).
574    // We therefore have two calls to llvm_optimize, if autodiff is used.
575    //
576    // FIXME(ZuseZ4): Before shipping on nightly,
577    // we should make this more granular, or at least check that the user has at least one autodiff
578    // call in their code, to justify altering the compilation pipeline.
579    if cfg!(llvm_enzyme) && autodiff_stage != AutodiffStage::PostAD {
580        unroll_loops = false;
581        vectorize_slp = false;
582        vectorize_loop = false;
583    } else {
584        unroll_loops =
585            opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
586        vectorize_slp = config.vectorize_slp;
587        vectorize_loop = config.vectorize_loop;
588    }
589    trace!(?unroll_loops, ?vectorize_slp, ?vectorize_loop, ?run_enzyme);
590    let using_thin_buffers = opt_stage == llvm::OptStage::PreLinkThinLTO || config.bitcode_needed();
591    let pgo_gen_path = get_pgo_gen_path(config);
592    let pgo_use_path = get_pgo_use_path(config);
593    let pgo_sample_use_path = get_pgo_sample_use_path(config);
594    let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
595    let instr_profile_output_path = get_instr_profile_output_path(config);
596    let sanitize_dataflow_abilist: Vec<_> = config
597        .sanitizer_dataflow_abilist
598        .iter()
599        .map(|file| CString::new(file.as_str()).unwrap())
600        .collect();
601    let sanitize_dataflow_abilist_ptrs: Vec<_> =
602        sanitize_dataflow_abilist.iter().map(|file| file.as_ptr()).collect();
603    // Sanitizer instrumentation is only inserted during the pre-link optimization stage.
604    let sanitizer_options = if !is_lto {
605        Some(llvm::SanitizerOptions {
606            sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
607            sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
608            sanitize_cfi: config.sanitizer.contains(SanitizerSet::CFI),
609            sanitize_dataflow: config.sanitizer.contains(SanitizerSet::DATAFLOW),
610            sanitize_dataflow_abilist: sanitize_dataflow_abilist_ptrs.as_ptr(),
611            sanitize_dataflow_abilist_len: sanitize_dataflow_abilist_ptrs.len(),
612            sanitize_kcfi: config.sanitizer.contains(SanitizerSet::KCFI),
613            sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
614            sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
615            sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
616            sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
617            sanitize_hwaddress: config.sanitizer.contains(SanitizerSet::HWADDRESS),
618            sanitize_hwaddress_recover: config.sanitizer_recover.contains(SanitizerSet::HWADDRESS),
619            sanitize_kernel_address: config.sanitizer.contains(SanitizerSet::KERNELADDRESS),
620            sanitize_kernel_address_recover: config
621                .sanitizer_recover
622                .contains(SanitizerSet::KERNELADDRESS),
623        })
624    } else {
625        None
626    };
627
628    let mut llvm_profiler = cgcx
629        .prof
630        .llvm_recording_enabled()
631        .then(|| LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap()));
632
633    let llvm_selfprofiler =
634        llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut());
635
636    let extra_passes = if !is_lto { config.passes.join(",") } else { "".to_string() };
637
638    let llvm_plugins = config.llvm_plugins.join(",");
639
640    let result = unsafe {
641        llvm::LLVMRustOptimize(
642            module.module_llvm.llmod(),
643            &*module.module_llvm.tm,
644            to_pass_builder_opt_level(opt_level),
645            opt_stage,
646            cgcx.opts.cg.linker_plugin_lto.enabled(),
647            config.no_prepopulate_passes,
648            config.verify_llvm_ir,
649            config.lint_llvm_ir,
650            using_thin_buffers,
651            config.merge_functions,
652            unroll_loops,
653            vectorize_slp,
654            vectorize_loop,
655            config.no_builtins,
656            config.emit_lifetime_markers,
657            run_enzyme,
658            sanitizer_options.as_ref(),
659            pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
660            pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
661            config.instrument_coverage,
662            instr_profile_output_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
663            pgo_sample_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
664            config.debug_info_for_profiling,
665            llvm_selfprofiler,
666            selfprofile_before_pass_callback,
667            selfprofile_after_pass_callback,
668            extra_passes.as_c_char_ptr(),
669            extra_passes.len(),
670            llvm_plugins.as_c_char_ptr(),
671            llvm_plugins.len(),
672        )
673    };
674    result.into_result().map_err(|()| llvm_err(dcx, LlvmError::RunLlvmPasses))
675}
676
677// Unsafe due to LLVM calls.
678pub(crate) unsafe fn optimize(
679    cgcx: &CodegenContext<LlvmCodegenBackend>,
680    dcx: DiagCtxtHandle<'_>,
681    module: &ModuleCodegen<ModuleLlvm>,
682    config: &ModuleConfig,
683) -> Result<(), FatalError> {
684    let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_optimize", &*module.name);
685
686    let llcx = &*module.module_llvm.llcx;
687    let _handlers = DiagnosticHandlers::new(cgcx, dcx, llcx, module, CodegenDiagnosticsStage::Opt);
688
689    let module_name = module.name.clone();
690    let module_name = Some(&module_name[..]);
691
692    if config.emit_no_opt_bc {
693        let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
694        write_bitcode_to_file(module, &out)
695    }
696
697    // FIXME(ZuseZ4): support SanitizeHWAddress and prevent illegal/unsupported opts
698
699    if let Some(opt_level) = config.opt_level {
700        let opt_stage = match cgcx.lto {
701            Lto::Fat => llvm::OptStage::PreLinkFatLTO,
702            Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
703            _ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO,
704            _ => llvm::OptStage::PreLinkNoLTO,
705        };
706
707        // If we know that we will later run AD, then we disable vectorization and loop unrolling.
708        // Otherwise we pretend AD is already done and run the normal opt pipeline (=PostAD).
709        // FIXME(ZuseZ4): Make this more granular, only set PreAD if we actually have autodiff
710        // usages, not just if we build rustc with autodiff support.
711        let autodiff_stage =
712            if cfg!(llvm_enzyme) { AutodiffStage::PreAD } else { AutodiffStage::PostAD };
713        return unsafe {
714            llvm_optimize(cgcx, dcx, module, config, opt_level, opt_stage, autodiff_stage)
715        };
716    }
717    Ok(())
718}
719
720pub(crate) fn link(
721    cgcx: &CodegenContext<LlvmCodegenBackend>,
722    dcx: DiagCtxtHandle<'_>,
723    mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
724) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
725    use super::lto::{Linker, ModuleBuffer};
726    // Sort the modules by name to ensure deterministic behavior.
727    modules.sort_by(|a, b| a.name.cmp(&b.name));
728    let (first, elements) =
729        modules.split_first().expect("Bug! modules must contain at least one module.");
730
731    let mut linker = Linker::new(first.module_llvm.llmod());
732    for module in elements {
733        let _timer = cgcx.prof.generic_activity_with_arg("LLVM_link_module", &*module.name);
734        let buffer = ModuleBuffer::new(module.module_llvm.llmod());
735        linker
736            .add(buffer.data())
737            .map_err(|()| llvm_err(dcx, LlvmError::SerializeModule { name: &module.name }))?;
738    }
739    drop(linker);
740    Ok(modules.remove(0))
741}
742
743pub(crate) unsafe fn codegen(
744    cgcx: &CodegenContext<LlvmCodegenBackend>,
745    dcx: DiagCtxtHandle<'_>,
746    module: ModuleCodegen<ModuleLlvm>,
747    config: &ModuleConfig,
748) -> Result<CompiledModule, FatalError> {
749    let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_codegen", &*module.name);
750    {
751        let llmod = module.module_llvm.llmod();
752        let llcx = &*module.module_llvm.llcx;
753        let tm = &*module.module_llvm.tm;
754        let module_name = module.name.clone();
755        let module_name = Some(&module_name[..]);
756        let _handlers =
757            DiagnosticHandlers::new(cgcx, dcx, llcx, &module, CodegenDiagnosticsStage::Codegen);
758
759        if cgcx.msvc_imps_needed {
760            create_msvc_imps(cgcx, llcx, llmod);
761        }
762
763        // Note that if object files are just LLVM bitcode we write bitcode,
764        // copy it to the .o file, and delete the bitcode if it wasn't
765        // otherwise requested.
766
767        let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
768        let bc_summary_out =
769            cgcx.output_filenames.temp_path(OutputType::ThinLinkBitcode, module_name);
770        let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
771
772        if config.bitcode_needed() {
773            let _timer = cgcx
774                .prof
775                .generic_activity_with_arg("LLVM_module_codegen_make_bitcode", &*module.name);
776            let thin = ThinBuffer::new(llmod, config.emit_thin_lto, config.emit_thin_lto_summary);
777            let data = thin.data();
778
779            if let Some(bitcode_filename) = bc_out.file_name() {
780                cgcx.prof.artifact_size(
781                    "llvm_bitcode",
782                    bitcode_filename.to_string_lossy(),
783                    data.len() as u64,
784                );
785            }
786
787            if config.emit_thin_lto_summary
788                && let Some(thin_link_bitcode_filename) = bc_summary_out.file_name()
789            {
790                let summary_data = thin.thin_link_data();
791                cgcx.prof.artifact_size(
792                    "llvm_bitcode_summary",
793                    thin_link_bitcode_filename.to_string_lossy(),
794                    summary_data.len() as u64,
795                );
796
797                let _timer = cgcx.prof.generic_activity_with_arg(
798                    "LLVM_module_codegen_emit_bitcode_summary",
799                    &*module.name,
800                );
801                if let Err(err) = fs::write(&bc_summary_out, summary_data) {
802                    dcx.emit_err(WriteBytecode { path: &bc_summary_out, err });
803                }
804            }
805
806            if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
807                let _timer = cgcx
808                    .prof
809                    .generic_activity_with_arg("LLVM_module_codegen_emit_bitcode", &*module.name);
810                if let Err(err) = fs::write(&bc_out, data) {
811                    dcx.emit_err(WriteBytecode { path: &bc_out, err });
812                }
813            }
814
815            if config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full) {
816                let _timer = cgcx
817                    .prof
818                    .generic_activity_with_arg("LLVM_module_codegen_embed_bitcode", &*module.name);
819                unsafe {
820                    embed_bitcode(cgcx, llcx, llmod, &config.bc_cmdline, data);
821                }
822            }
823        }
824
825        if config.emit_ir {
826            let _timer =
827                cgcx.prof.generic_activity_with_arg("LLVM_module_codegen_emit_ir", &*module.name);
828            let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
829            let out_c = path_to_c_string(&out);
830
831            extern "C" fn demangle_callback(
832                input_ptr: *const c_char,
833                input_len: size_t,
834                output_ptr: *mut c_char,
835                output_len: size_t,
836            ) -> size_t {
837                let input =
838                    unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
839
840                let Ok(input) = str::from_utf8(input) else { return 0 };
841
842                let output = unsafe {
843                    slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
844                };
845                let mut cursor = io::Cursor::new(output);
846
847                let Ok(demangled) = rustc_demangle::try_demangle(input) else { return 0 };
848
849                if write!(cursor, "{demangled:#}").is_err() {
850                    // Possible only if provided buffer is not big enough
851                    return 0;
852                }
853
854                cursor.position() as size_t
855            }
856
857            let result =
858                unsafe { llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback) };
859
860            if result == llvm::LLVMRustResult::Success {
861                record_artifact_size(&cgcx.prof, "llvm_ir", &out);
862            }
863
864            result.into_result().map_err(|()| llvm_err(dcx, LlvmError::WriteIr { path: &out }))?;
865        }
866
867        if config.emit_asm {
868            let _timer =
869                cgcx.prof.generic_activity_with_arg("LLVM_module_codegen_emit_asm", &*module.name);
870            let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
871
872            // We can't use the same module for asm and object code output,
873            // because that triggers various errors like invalid IR or broken
874            // binaries. So we must clone the module to produce the asm output
875            // if we are also producing object code.
876            let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
877                unsafe { llvm::LLVMCloneModule(llmod) }
878            } else {
879                llmod
880            };
881            write_output_file(
882                dcx,
883                tm,
884                config.no_builtins,
885                llmod,
886                &path,
887                None,
888                llvm::FileType::AssemblyFile,
889                &cgcx.prof,
890                config.verify_llvm_ir,
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                write_output_file(
916                    dcx,
917                    tm,
918                    config.no_builtins,
919                    llmod,
920                    &obj_out,
921                    dwo_out,
922                    llvm::FileType::ObjectFile,
923                    &cgcx.prof,
924                    config.verify_llvm_ir,
925                )?;
926            }
927
928            EmitObj::Bitcode => {
929                debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
930                if let Err(err) = link_or_copy(&bc_out, &obj_out) {
931                    dcx.emit_err(CopyBitcode { err });
932                }
933
934                if !config.emit_bc {
935                    debug!("removing_bitcode {:?}", bc_out);
936                    ensure_removed(dcx, &bc_out);
937                }
938            }
939
940            EmitObj::None => {}
941        }
942
943        record_llvm_cgu_instructions_stats(&cgcx.prof, llmod);
944    }
945
946    // `.dwo` files are only emitted if:
947    //
948    // - Object files are being emitted (i.e. bitcode only or metadata only compilations will not
949    //   produce dwarf objects, even if otherwise enabled)
950    // - Target supports Split DWARF
951    // - Split debuginfo is enabled
952    // - Split DWARF kind is `split` (i.e. debuginfo is split into `.dwo` files, not different
953    //   sections in the `.o` files).
954    let dwarf_object_emitted = matches!(config.emit_obj, EmitObj::ObjectCode(_))
955        && cgcx.target_can_use_split_dwarf
956        && cgcx.split_debuginfo != SplitDebuginfo::Off
957        && cgcx.split_dwarf_kind == SplitDwarfKind::Split;
958    Ok(module.into_compiled_module(
959        config.emit_obj != EmitObj::None,
960        dwarf_object_emitted,
961        config.emit_bc,
962        config.emit_asm,
963        config.emit_ir,
964        &cgcx.output_filenames,
965    ))
966}
967
968fn create_section_with_flags_asm(section_name: &str, section_flags: &str, data: &[u8]) -> Vec<u8> {
969    let mut asm = format!(".section {section_name},\"{section_flags}\"\n").into_bytes();
970    asm.extend_from_slice(b".ascii \"");
971    asm.reserve(data.len());
972    for &byte in data {
973        if byte == b'\\' || byte == b'"' {
974            asm.push(b'\\');
975            asm.push(byte);
976        } else if byte < 0x20 || byte >= 0x80 {
977            // Avoid non UTF-8 inline assembly. Use octal escape sequence, because it is fixed
978            // width, while hex escapes will consume following characters.
979            asm.push(b'\\');
980            asm.push(b'0' + ((byte >> 6) & 0x7));
981            asm.push(b'0' + ((byte >> 3) & 0x7));
982            asm.push(b'0' + ((byte >> 0) & 0x7));
983        } else {
984            asm.push(byte);
985        }
986    }
987    asm.extend_from_slice(b"\"\n");
988    asm
989}
990
991pub(crate) fn bitcode_section_name(cgcx: &CodegenContext<LlvmCodegenBackend>) -> &'static CStr {
992    if cgcx.target_is_like_osx {
993        c"__LLVM,__bitcode"
994    } else if cgcx.target_is_like_aix {
995        c".ipa"
996    } else {
997        c".llvmbc"
998    }
999}
1000
1001/// Embed the bitcode of an LLVM module for LTO in the LLVM module itself.
1002unsafe fn embed_bitcode(
1003    cgcx: &CodegenContext<LlvmCodegenBackend>,
1004    llcx: &llvm::Context,
1005    llmod: &llvm::Module,
1006    cmdline: &str,
1007    bitcode: &[u8],
1008) {
1009    // We're adding custom sections to the output object file, but we definitely
1010    // do not want these custom sections to make their way into the final linked
1011    // executable. The purpose of these custom sections is for tooling
1012    // surrounding object files to work with the LLVM IR, if necessary. For
1013    // example rustc's own LTO will look for LLVM IR inside of the object file
1014    // in these sections by default.
1015    //
1016    // To handle this is a bit different depending on the object file format
1017    // used by the backend, broken down into a few different categories:
1018    //
1019    // * Mach-O - this is for macOS. Inspecting the source code for the native
1020    //   linker here shows that the `.llvmbc` and `.llvmcmd` sections are
1021    //   automatically skipped by the linker. In that case there's nothing extra
1022    //   that we need to do here.
1023    //
1024    // * Wasm - the native LLD linker is hard-coded to skip `.llvmbc` and
1025    //   `.llvmcmd` sections, so there's nothing extra we need to do.
1026    //
1027    // * COFF - if we don't do anything the linker will by default copy all
1028    //   these sections to the output artifact, not what we want! To subvert
1029    //   this we want to flag the sections we inserted here as
1030    //   `IMAGE_SCN_LNK_REMOVE`.
1031    //
1032    // * ELF - this is very similar to COFF above. One difference is that these
1033    //   sections are removed from the output linked artifact when
1034    //   `--gc-sections` is passed, which we pass by default. If that flag isn't
1035    //   passed though then these sections will show up in the final output.
1036    //   Additionally the flag that we need to set here is `SHF_EXCLUDE`.
1037    //
1038    // * XCOFF - AIX linker ignores content in .ipa and .info if no auxiliary
1039    //   symbol associated with these sections.
1040    //
1041    // Unfortunately, LLVM provides no way to set custom section flags. For ELF
1042    // and COFF we emit the sections using module level inline assembly for that
1043    // reason (see issue #90326 for historical background).
1044    unsafe {
1045        if cgcx.target_is_like_osx
1046            || cgcx.target_is_like_aix
1047            || cgcx.target_arch == "wasm32"
1048            || cgcx.target_arch == "wasm64"
1049        {
1050            // We don't need custom section flags, create LLVM globals.
1051            let llconst = common::bytes_in_context(llcx, bitcode);
1052            let llglobal =
1053                llvm::add_global(llmod, common::val_ty(llconst), c"rustc.embedded.module");
1054            llvm::set_initializer(llglobal, llconst);
1055
1056            llvm::set_section(llglobal, bitcode_section_name(cgcx));
1057            llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage);
1058            llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
1059
1060            let llconst = common::bytes_in_context(llcx, cmdline.as_bytes());
1061            let llglobal =
1062                llvm::add_global(llmod, common::val_ty(llconst), c"rustc.embedded.cmdline");
1063            llvm::set_initializer(llglobal, llconst);
1064            let section = if cgcx.target_is_like_osx {
1065                c"__LLVM,__cmdline"
1066            } else if cgcx.target_is_like_aix {
1067                c".info"
1068            } else {
1069                c".llvmcmd"
1070            };
1071            llvm::set_section(llglobal, section);
1072            llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage);
1073        } else {
1074            // We need custom section flags, so emit module-level inline assembly.
1075            let section_flags = if cgcx.is_pe_coff { "n" } else { "e" };
1076            let asm = create_section_with_flags_asm(".llvmbc", section_flags, bitcode);
1077            llvm::LLVMAppendModuleInlineAsm(llmod, asm.as_c_char_ptr(), asm.len());
1078            let asm = create_section_with_flags_asm(".llvmcmd", section_flags, cmdline.as_bytes());
1079            llvm::LLVMAppendModuleInlineAsm(llmod, asm.as_c_char_ptr(), asm.len());
1080        }
1081    }
1082}
1083
1084// Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
1085// This is required to satisfy `dllimport` references to static data in .rlibs
1086// when using MSVC linker. We do this only for data, as linker can fix up
1087// code references on its own.
1088// See #26591, #27438
1089fn create_msvc_imps(
1090    cgcx: &CodegenContext<LlvmCodegenBackend>,
1091    llcx: &llvm::Context,
1092    llmod: &llvm::Module,
1093) {
1094    if !cgcx.msvc_imps_needed {
1095        return;
1096    }
1097    // The x86 ABI seems to require that leading underscores are added to symbol
1098    // names, so we need an extra underscore on x86. There's also a leading
1099    // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
1100    // underscores added in front).
1101    let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" };
1102
1103    let ptr_ty = Type::ptr_llcx(llcx);
1104    let globals = base::iter_globals(llmod)
1105        .filter(|&val| {
1106            llvm::get_linkage(val) == llvm::Linkage::ExternalLinkage && !llvm::is_declaration(val)
1107        })
1108        .filter_map(|val| {
1109            // Exclude some symbols that we know are not Rust symbols.
1110            let name = llvm::get_value_name(val);
1111            if ignored(name) { None } else { Some((val, name)) }
1112        })
1113        .map(move |(val, name)| {
1114            let mut imp_name = prefix.as_bytes().to_vec();
1115            imp_name.extend(name);
1116            let imp_name = CString::new(imp_name).unwrap();
1117            (imp_name, val)
1118        })
1119        .collect::<Vec<_>>();
1120
1121    for (imp_name, val) in globals {
1122        let imp = llvm::add_global(llmod, ptr_ty, &imp_name);
1123
1124        llvm::set_initializer(imp, val);
1125        llvm::set_linkage(imp, llvm::Linkage::ExternalLinkage);
1126    }
1127
1128    // Use this function to exclude certain symbols from `__imp` generation.
1129    fn ignored(symbol_name: &[u8]) -> bool {
1130        // These are symbols generated by LLVM's profiling instrumentation
1131        symbol_name.starts_with(b"__llvm_profile_")
1132    }
1133}
1134
1135fn record_artifact_size(
1136    self_profiler_ref: &SelfProfilerRef,
1137    artifact_kind: &'static str,
1138    path: &Path,
1139) {
1140    // Don't stat the file if we are not going to record its size.
1141    if !self_profiler_ref.enabled() {
1142        return;
1143    }
1144
1145    if let Some(artifact_name) = path.file_name() {
1146        let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
1147        self_profiler_ref.artifact_size(artifact_kind, artifact_name.to_string_lossy(), file_size);
1148    }
1149}
1150
1151fn record_llvm_cgu_instructions_stats(prof: &SelfProfilerRef, llmod: &llvm::Module) {
1152    if !prof.enabled() {
1153        return;
1154    }
1155
1156    let raw_stats =
1157        llvm::build_string(|s| unsafe { llvm::LLVMRustModuleInstructionStats(llmod, s) })
1158            .expect("cannot get module instruction stats");
1159
1160    #[derive(serde::Deserialize)]
1161    struct InstructionsStats {
1162        module: String,
1163        total: u64,
1164    }
1165
1166    let InstructionsStats { module, total } =
1167        serde_json::from_str(&raw_stats).expect("cannot parse llvm cgu instructions stats");
1168    prof.artifact_size("cgu_instructions", module, total);
1169}