Skip to main content

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 rustc_codegen_ssa::back::link::ensure_removed;
9use rustc_codegen_ssa::back::versioned_llvm_target;
10use rustc_codegen_ssa::back::write::{
11    BitcodeSection, CodegenContext, EmitObj, InlineAsmError, ModuleConfig, SharedEmitter,
12    TargetMachineFactoryConfig, TargetMachineFactoryFn,
13};
14use rustc_codegen_ssa::base::wants_wasm_eh;
15use rustc_codegen_ssa::common::TypeKind;
16use rustc_codegen_ssa::traits::*;
17use rustc_codegen_ssa::{CompiledModule, ModuleCodegen, ModuleKind};
18use rustc_data_structures::profiling::SelfProfilerRef;
19use rustc_data_structures::small_c_str::SmallCStr;
20use rustc_errors::{DiagCtxt, DiagCtxtHandle, Level};
21use rustc_fs_util::{link_or_copy, path_to_c_string};
22use rustc_middle::ty::TyCtxt;
23use rustc_session::Session;
24use rustc_session::config::{self, Lto, OutputType, Passes, SplitDwarfKind, SwitchWithOptPath};
25use rustc_span::{BytePos, InnerSpan, Pos, RemapPathScopeComponents, SpanData, SyntaxContext};
26use rustc_target::spec::{CodeModel, FloatAbi, RelocModel, SanitizerSet, SplitDebuginfo, TlsModel};
27use tracing::{debug, trace};
28
29use crate::back::lto::{Buffer, ModuleBuffer};
30use crate::back::owned_target_machine::OwnedTargetMachine;
31use crate::back::profiling::{
32    LlvmSelfProfiler, selfprofile_after_pass_callback, selfprofile_before_pass_callback,
33};
34use crate::builder::SBuilder;
35use crate::builder::gpu_offload::scalar_width;
36use crate::common::AsCCharPtr;
37use crate::diagnostics::{
38    CopyBitcode, FromLlvmDiag, FromLlvmOptimizationDiag, LlvmError, ParseTargetMachineConfig,
39    UnsupportedCompression, WithLlvmError, WriteBytecode,
40};
41use crate::llvm::diagnostic::OptimizationDiagnosticKind::*;
42use crate::llvm::{self, DiagnosticInfo};
43use crate::type_::llvm_type_ptr;
44use crate::{LlvmCodegenBackend, ModuleLlvm, SimpleCx, attributes, base, common, llvm_util};
45
46pub(crate) fn llvm_err<'a>(dcx: DiagCtxtHandle<'_>, err: LlvmError<'a>) -> ! {
47    match llvm::last_error() {
48        Some(llvm_err) => dcx.emit_fatal(WithLlvmError(err, llvm_err)),
49        None => dcx.emit_fatal(err),
50    }
51}
52
53fn write_output_file<'ll>(
54    dcx: DiagCtxtHandle<'_>,
55    target: &'ll llvm::TargetMachine,
56    no_builtins: bool,
57    m: &'ll llvm::Module,
58    output: &Path,
59    dwo_output: Option<&Path>,
60    file_type: llvm::FileType,
61    self_profiler_ref: &SelfProfilerRef,
62    verify_llvm_ir: bool,
63) {
64    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/back/write.rs:64",
                        "rustc_codegen_llvm::back::write", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/back/write.rs"),
                        ::tracing_core::__macro_support::Option::Some(64u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::write"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("write_output_file output={0:?} dwo_output={1:?}",
                                                    output, dwo_output) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("write_output_file output={:?} dwo_output={:?}", output, dwo_output);
65    let output_c = path_to_c_string(output);
66    let dwo_output_c;
67    let dwo_output_ptr = if let Some(dwo_output) = dwo_output {
68        dwo_output_c = path_to_c_string(dwo_output);
69        dwo_output_c.as_ptr()
70    } else {
71        std::ptr::null()
72    };
73    let result = unsafe {
74        let pm = llvm::LLVMCreatePassManager();
75        llvm::LLVMAddAnalysisPasses(target, pm);
76        llvm::LLVMRustAddLibraryInfo(target, pm, m, no_builtins);
77        llvm::LLVMRustWriteOutputFile(
78            target,
79            pm,
80            m,
81            output_c.as_ptr(),
82            dwo_output_ptr,
83            file_type,
84            verify_llvm_ir,
85        )
86    };
87
88    // Record artifact sizes for self-profiling
89    if result == llvm::LLVMRustResult::Success {
90        let artifact_kind = match file_type {
91            llvm::FileType::ObjectFile => "object_file",
92            llvm::FileType::AssemblyFile => "assembly_file",
93        };
94        record_artifact_size(self_profiler_ref, artifact_kind, output);
95        if let Some(dwo_file) = dwo_output {
96            record_artifact_size(self_profiler_ref, "dwo_file", dwo_file);
97        }
98    }
99
100    result.into_result().unwrap_or_else(|()| llvm_err(dcx, LlvmError::WriteOutput { path: output }))
101}
102
103pub(crate) fn create_informational_target_machine(sess: &Session) -> OwnedTargetMachine {
104    let config = TargetMachineFactoryConfig { split_dwarf_file: None, output_obj_file: None };
105    target_machine_factory(sess, config::OptLevel::No)(sess.dcx(), config)
106}
107
108pub(crate) fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> OwnedTargetMachine {
109    let split_dwarf_file = if tcx.sess.target_can_use_split_dwarf() {
110        tcx.output_filenames(()).split_dwarf_path(
111            tcx.sess.split_debuginfo(),
112            tcx.sess.opts.unstable_opts.split_dwarf_kind,
113            mod_name,
114        )
115    } else {
116        None
117    };
118
119    let output_obj_file =
120        Some(tcx.output_filenames(()).temp_path_for_cgu(OutputType::Object, mod_name));
121    let config = TargetMachineFactoryConfig { split_dwarf_file, output_obj_file };
122
123    target_machine_factory(tcx.sess, tcx.backend_optimization_level(()))(tcx.dcx(), config)
124}
125
126fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
127    use self::config::OptLevel::*;
128    match cfg {
129        No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
130        Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
131        More => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
132        Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
133        Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
134        SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
135    }
136}
137
138fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel {
139    use config::OptLevel::*;
140    match cfg {
141        No => llvm::PassBuilderOptLevel::O0,
142        Less => llvm::PassBuilderOptLevel::O1,
143        More => llvm::PassBuilderOptLevel::O2,
144        Aggressive => llvm::PassBuilderOptLevel::O3,
145        Size => llvm::PassBuilderOptLevel::Os,
146        SizeMin => llvm::PassBuilderOptLevel::Oz,
147    }
148}
149
150fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
151    match relocation_model {
152        RelocModel::Static => llvm::RelocModel::Static,
153        // LLVM doesn't have a PIE relocation model, it represents PIE as PIC with an extra
154        // 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
163pub(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
174fn to_llvm_float_abi(float_abi: Option<FloatAbi>) -> llvm::FloatAbi {
175    match float_abi {
176        None => llvm::FloatAbi::Default,
177        Some(FloatAbi::Soft) => llvm::FloatAbi::Soft,
178        Some(FloatAbi::Hard) => llvm::FloatAbi::Hard,
179    }
180}
181
182pub(crate) fn target_machine_factory(
183    sess: &Session,
184    optlvl: config::OptLevel,
185) -> TargetMachineFactoryFn<LlvmCodegenBackend> {
186    // Self-profile timer for creating a _factory_.
187    let _prof_timer = sess.prof.generic_activity("target_machine_factory");
188
189    let reloc_model = to_llvm_relocation_model(sess.relocation_model());
190
191    let (opt_level, _) = to_llvm_opt_settings(optlvl);
192    let float_abi = to_llvm_float_abi(sess.target.llvm_floatabi);
193
194    let ffunction_sections =
195        sess.opts.unstable_opts.function_sections.unwrap_or(sess.target.function_sections);
196    let fdata_sections = ffunction_sections;
197    let funique_section_names = !sess.opts.unstable_opts.no_unique_section_names;
198
199    let code_model = to_llvm_code_model(sess.code_model());
200
201    let singlethread = sess.target.singlethread(&sess.internal_target_features);
202
203    let triple = SmallCStr::new(&versioned_llvm_target(sess));
204    let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
205    let features = CString::new(sess.global_backend_features.join(",")).unwrap();
206    let abi = SmallCStr::new(sess.target.llvm_abiname.desc());
207    let trap_unreachable =
208        sess.opts.unstable_opts.trap_unreachable.unwrap_or(sess.target.trap_unreachable);
209    let emit_stack_size_section = sess.opts.unstable_opts.emit_stack_sizes;
210
211    let verbose_asm = sess.opts.unstable_opts.verbose_asm;
212    let relax_elf_relocations =
213        sess.opts.unstable_opts.relax_elf_relocations.unwrap_or(sess.target.relax_elf_relocations);
214
215    let use_init_array =
216        !sess.opts.unstable_opts.use_ctors_section.unwrap_or(sess.target.use_ctors_section);
217
218    let path_mapping = sess.source_map().path_mapping().clone();
219    let working_dir = sess.source_map().working_dir().clone();
220
221    let use_emulated_tls = #[allow(non_exhaustive_omitted_patterns)] match sess.tls_model() {
    TlsModel::Emulated => true,
    _ => false,
}matches!(sess.tls_model(), TlsModel::Emulated);
222
223    let debuginfo_compression = match sess.opts.unstable_opts.debuginfo_compression {
224        config::DebugInfoCompression::None => llvm::CompressionKind::None,
225        config::DebugInfoCompression::Zlib => {
226            if llvm::LLVMRustLLVMHasZlibCompression() {
227                llvm::CompressionKind::Zlib
228            } else {
229                sess.dcx().emit_warn(UnsupportedCompression { algorithm: "zlib" });
230                llvm::CompressionKind::None
231            }
232        }
233        config::DebugInfoCompression::Zstd => {
234            if llvm::LLVMRustLLVMHasZstdCompression() {
235                llvm::CompressionKind::Zstd
236            } else {
237                sess.dcx().emit_warn(UnsupportedCompression { algorithm: "zstd" });
238                llvm::CompressionKind::None
239            }
240        }
241    };
242
243    let use_wasm_eh = wants_wasm_eh(&sess.target);
244
245    let large_data_threshold = sess.opts.unstable_opts.large_data_threshold.unwrap_or(0);
246
247    let prof = SelfProfilerRef::clone(&sess.prof);
248    Arc::new(move |dcx: DiagCtxtHandle<'_>, config: TargetMachineFactoryConfig| {
249        // Self-profile timer for invoking a factory to create a target machine.
250        let _prof_timer = prof.generic_activity("target_machine_factory_inner");
251
252        let path_to_cstring_helper = |path: Option<PathBuf>| -> CString {
253            let path = path.unwrap_or_default();
254            let path = path_mapping
255                .to_real_filename(&working_dir, path)
256                .path(RemapPathScopeComponents::DEBUGINFO)
257                .to_string_lossy()
258                .into_owned();
259            CString::new(path).unwrap()
260        };
261
262        let split_dwarf_file = path_to_cstring_helper(config.split_dwarf_file);
263        let output_obj_file = path_to_cstring_helper(config.output_obj_file);
264
265        OwnedTargetMachine::new(
266            &triple,
267            &cpu,
268            &features,
269            &abi,
270            code_model,
271            reloc_model,
272            opt_level,
273            float_abi,
274            ffunction_sections,
275            fdata_sections,
276            funique_section_names,
277            trap_unreachable,
278            singlethread,
279            verbose_asm,
280            emit_stack_size_section,
281            relax_elf_relocations,
282            use_init_array,
283            &split_dwarf_file,
284            &output_obj_file,
285            debuginfo_compression,
286            use_emulated_tls,
287            use_wasm_eh,
288            large_data_threshold,
289        )
290        .unwrap_or_else(|err| dcx.emit_fatal(ParseTargetMachineConfig(err)))
291    })
292}
293
294pub(crate) fn save_temp_bitcode(
295    cgcx: &CodegenContext,
296    module: &ModuleCodegen<ModuleLlvm>,
297    name: &str,
298) {
299    if !cgcx.save_temps {
300        return;
301    }
302    let ext = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.bc", name))
    })format!("{name}.bc");
303    let path = cgcx.output_filenames.temp_path_ext_for_cgu(&ext, &module.name);
304    write_bitcode_to_file(&module.module_llvm, &path)
305}
306
307fn write_bitcode_to_file(module: &ModuleLlvm, path: &Path) {
308    unsafe {
309        let path = path_to_c_string(&path);
310        let llmod = module.llmod();
311        llvm::LLVMWriteBitcodeToFile(llmod, path.as_ptr());
312    }
313}
314
315/// In what context is a diagnostic handler being attached to a codegen unit?
316pub(crate) enum CodegenDiagnosticsStage {
317    /// Prelink optimization stage.
318    Opt,
319    /// LTO/ThinLTO postlink optimization stage.
320    LTO,
321    /// Code generation.
322    Codegen,
323}
324
325pub(crate) struct DiagnosticHandlers<'a> {
326    data: *mut (&'a CodegenContext, &'a SharedEmitter),
327    llcx: &'a llvm::Context,
328    old_handler: Option<&'a llvm::DiagnosticHandler>,
329}
330
331impl<'a> DiagnosticHandlers<'a> {
332    pub(crate) fn new(
333        cgcx: &'a CodegenContext,
334        shared_emitter: &'a SharedEmitter,
335        llcx: &'a llvm::Context,
336        module: &ModuleCodegen<ModuleLlvm>,
337        stage: CodegenDiagnosticsStage,
338    ) -> Self {
339        let remark_passes_all: bool;
340        let remark_passes: Vec<CString>;
341        match &cgcx.remark {
342            Passes::All => {
343                remark_passes_all = true;
344                remark_passes = Vec::new();
345            }
346            Passes::Some(passes) => {
347                remark_passes_all = false;
348                remark_passes =
349                    passes.iter().map(|name| CString::new(name.as_str()).unwrap()).collect();
350            }
351        };
352        let remark_passes: Vec<*const c_char> =
353            remark_passes.iter().map(|name: &CString| name.as_ptr()).collect();
354        let remark_file = cgcx
355            .remark_dir
356            .as_ref()
357            // Use the .opt.yaml file suffix, which is supported by LLVM's opt-viewer.
358            .map(|dir| {
359                let stage_suffix = match stage {
360                    CodegenDiagnosticsStage::Codegen => "codegen",
361                    CodegenDiagnosticsStage::Opt => "opt",
362                    CodegenDiagnosticsStage::LTO => "lto",
363                };
364                dir.join(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.{1}.opt.yaml", module.name,
                stage_suffix))
    })format!("{}.{stage_suffix}.opt.yaml", module.name))
365            })
366            .and_then(|dir| dir.to_str().and_then(|p| CString::new(p).ok()));
367
368        let pgo_available = cgcx.module_config.pgo_use.is_some();
369        let data = Box::into_raw(Box::new((cgcx, shared_emitter)));
370        unsafe {
371            let old_handler = llvm::LLVMRustContextGetDiagnosticHandler(llcx);
372            llvm::LLVMRustContextConfigureDiagnosticHandler(
373                llcx,
374                diagnostic_handler,
375                data.cast(),
376                remark_passes_all,
377                remark_passes.as_ptr(),
378                remark_passes.len(),
379                // The `as_ref()` is important here, otherwise the `CString` will be dropped
380                // too soon!
381                remark_file.as_ref().map(|dir| dir.as_ptr()).unwrap_or(std::ptr::null()),
382                pgo_available,
383            );
384            DiagnosticHandlers { data, llcx, old_handler }
385        }
386    }
387}
388
389impl<'a> Drop for DiagnosticHandlers<'a> {
390    fn drop(&mut self) {
391        unsafe {
392            llvm::LLVMRustContextSetDiagnosticHandler(self.llcx, self.old_handler);
393            drop(Box::from_raw(self.data));
394        }
395    }
396}
397
398fn report_inline_asm(
399    cgcx: &CodegenContext,
400    msg: String,
401    level: llvm::DiagnosticLevel,
402    cookie: u64,
403    source: Option<(String, Vec<InnerSpan>)>,
404) -> InlineAsmError {
405    // In LTO build we may get srcloc values from other crates which are invalid
406    // since they use a different source map. To be safe we just suppress these
407    // in LTO builds.
408    let span = if cookie == 0 || #[allow(non_exhaustive_omitted_patterns)] match cgcx.lto {
    Lto::Fat | Lto::Thin => true,
    _ => false,
}matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
409        SpanData::default()
410    } else {
411        SpanData {
412            lo: BytePos::from_u32(cookie as u32),
413            hi: BytePos::from_u32((cookie >> 32) as u32),
414            ctxt: SyntaxContext::root(),
415            parent: None,
416        }
417    };
418    let level = match level {
419        llvm::DiagnosticLevel::Error => Level::Error,
420        llvm::DiagnosticLevel::Warning => Level::Warning,
421        llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
422    };
423    let msg = msg.trim_prefix("error: ").to_string();
424    InlineAsmError { span, msg, level, source }
425}
426
427unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
428    if user.is_null() {
429        return;
430    }
431    let (cgcx, shared_emitter) = unsafe { *(user as *const (&CodegenContext, &SharedEmitter)) };
432
433    let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
434    let dcx = dcx.handle();
435
436    match unsafe { llvm::diagnostic::Diagnostic::unpack(info) } {
437        llvm::diagnostic::InlineAsm(inline) => {
438            // FIXME use dcx
439            shared_emitter.inline_asm_error(report_inline_asm(
440                cgcx,
441                inline.message,
442                inline.level,
443                inline.cookie,
444                inline.source,
445            ));
446        }
447
448        llvm::diagnostic::Optimization(opt) => {
449            dcx.emit_note(FromLlvmOptimizationDiag {
450                filename: &opt.filename,
451                line: opt.line,
452                column: opt.column,
453                pass_name: &opt.pass_name,
454                kind: match opt.kind {
455                    OptimizationRemark => "success",
456                    OptimizationMissed | OptimizationFailure => "missed",
457                    OptimizationAnalysis
458                    | OptimizationAnalysisFPCommute
459                    | OptimizationAnalysisAliasing => "analysis",
460                    OptimizationRemarkOther => "other",
461                },
462                message: &opt.message,
463            });
464        }
465        llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
466            let message = llvm::build_string(|s| unsafe {
467                llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
468            })
469            .expect("non-UTF8 diagnostic");
470            dcx.emit_warn(FromLlvmDiag { message });
471        }
472        llvm::diagnostic::Unsupported(diagnostic_ref) => {
473            let message = llvm::build_string(|s| unsafe {
474                llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
475            })
476            .expect("non-UTF8 diagnostic");
477            dcx.emit_err(FromLlvmDiag { message });
478        }
479        llvm::diagnostic::UnknownDiagnostic(..) => {}
480    }
481}
482
483fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
484    match config.pgo_gen {
485        SwitchWithOptPath::Enabled(ref opt_dir_path) => {
486            let path = if let Some(dir_path) = opt_dir_path {
487                dir_path.join("default_%m.profraw")
488            } else {
489                PathBuf::from("default_%m.profraw")
490            };
491
492            Some(CString::new(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", path.display()))
    })format!("{}", path.display())).unwrap())
493        }
494        SwitchWithOptPath::Disabled => None,
495    }
496}
497
498fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
499    config
500        .pgo_use
501        .as_ref()
502        .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
503}
504
505fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option<CString> {
506    config
507        .pgo_sample_use
508        .as_ref()
509        .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
510}
511
512fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> {
513    config.instrument_coverage.then(|| c"default_%m_%p.profraw".to_owned())
514}
515
516// PreAD will run llvm opts but disable size increasing opts (vectorization, loop unrolling)
517// DuringAD is the same as above, but also runs the enzyme opt and autodiff passes.
518// PostAD will run all opts, including size increasing opts.
519#[derive(#[automatically_derived]
impl ::core::fmt::Debug for AutodiffStage {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                AutodiffStage::PreAD => "PreAD",
                AutodiffStage::DuringAD => "DuringAD",
                AutodiffStage::PostAD => "PostAD",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for AutodiffStage { }Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for AutodiffStage { }
#[automatically_derived]
impl ::core::cmp::PartialEq for AutodiffStage {
    #[inline]
    fn eq(&self, other: &AutodiffStage) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
520pub(crate) enum AutodiffStage {
521    PreAD,
522    DuringAD,
523    PostAD,
524}
525
526pub(crate) unsafe fn llvm_optimize(
527    cgcx: &CodegenContext,
528    prof: &SelfProfilerRef,
529    dcx: DiagCtxtHandle<'_>,
530    module: &ModuleCodegen<ModuleLlvm>,
531    thin_lto_buffer: Option<&mut Option<Buffer>>,
532    thin_lto_summary_buffer: Option<&mut Option<Buffer>>,
533    config: &ModuleConfig,
534    opt_level: config::OptLevel,
535    opt_stage: llvm::OptStage,
536    autodiff_stage: AutodiffStage,
537) {
538    // Enzyme:
539    // The whole point of compiler based AD is to differentiate optimized IR instead of unoptimized
540    // source code. However, benchmarks show that optimizations increasing the code size
541    // tend to reduce AD performance. Therefore deactivate them before AD, then differentiate the code
542    // and finally re-optimize the module, now with all optimizations available.
543    // FIXME(ZuseZ4): In a future update we could figure out how to only optimize individual functions getting
544    // differentiated.
545
546    let consider_ad = config.autodiff.contains(&config::AutoDiff::Enable);
547    let run_enzyme = autodiff_stage == AutodiffStage::DuringAD;
548    let print_before_enzyme = config.autodiff.contains(&config::AutoDiff::PrintModBefore);
549    let print_after_enzyme = config.autodiff.contains(&config::AutoDiff::PrintModAfter);
550    let print_passes = config.autodiff.contains(&config::AutoDiff::PrintPasses);
551    let passes_after_enzyme = if autodiff_stage == AutodiffStage::PostAD {
552        config.autodiff_post_passes.as_deref()
553    } else {
554        None
555    };
556    let passes_after_enzyme_ptr =
557        passes_after_enzyme.map_or(std::ptr::null(), |s| s.as_c_char_ptr());
558    let passes_after_enzyme_len = passes_after_enzyme.map_or(0, |s| s.len());
559    let merge_functions;
560    let unroll_loops;
561    let vectorize_slp;
562    let vectorize_loop;
563
564    // When we build rustc with enzyme/autodiff support, we want to postpone size-increasing
565    // optimizations until after differentiation. Our pipeline is thus: (opt + enzyme), (full opt).
566    // We therefore have two calls to llvm_optimize, if autodiff is used.
567    //
568    // We also must disable merge_functions, since autodiff placeholder/dummy bodies tend to be
569    // identical. We run opts before AD, so there is a chance that LLVM will merge our dummies.
570    // In that case, we lack some dummy bodies and can't replace them with the real AD code anymore.
571    // We then would need to abort compilation. This was especially common in test cases.
572    if consider_ad && autodiff_stage != AutodiffStage::PostAD {
573        merge_functions = false;
574        unroll_loops = false;
575        vectorize_slp = false;
576        vectorize_loop = false;
577    } else {
578        unroll_loops =
579            opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
580        merge_functions = config.merge_functions;
581        vectorize_slp = config.vectorize_slp;
582        vectorize_loop = config.vectorize_loop;
583    }
584    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/back/write.rs:584",
                        "rustc_codegen_llvm::back::write", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/back/write.rs"),
                        ::tracing_core::__macro_support::Option::Some(584u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::write"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("unroll_loops")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("unroll_loops");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("vectorize_slp")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("vectorize_slp");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("vectorize_loop")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("vectorize_loop");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("run_enzyme")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("run_enzyme");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&unroll_loops)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vectorize_slp)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&vectorize_loop)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&run_enzyme)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};trace!(?unroll_loops, ?vectorize_slp, ?vectorize_loop, ?run_enzyme);
585    if thin_lto_buffer.is_some() {
586        if !#[allow(non_exhaustive_omitted_patterns)] match opt_stage {
            llvm::OptStage::PreLinkNoLTO | llvm::OptStage::PreLinkFatLTO |
                llvm::OptStage::PreLinkThinLTO => true,
            _ => false,
        } {
    {
        ::core::panicking::panic_fmt(format_args!("the bitcode for LTO can only be obtained at the pre-link stage"));
    }
};assert!(
587            matches!(
588                opt_stage,
589                llvm::OptStage::PreLinkNoLTO
590                    | llvm::OptStage::PreLinkFatLTO
591                    | llvm::OptStage::PreLinkThinLTO
592            ),
593            "the bitcode for LTO can only be obtained at the pre-link stage"
594        );
595    }
596    let pgo_gen_path = get_pgo_gen_path(config);
597    let pgo_use_path = get_pgo_use_path(config);
598    let pgo_sample_use_path = get_pgo_sample_use_path(config);
599    let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
600    let is_final_stage =
601        !#[allow(non_exhaustive_omitted_patterns)] match opt_stage {
    llvm::OptStage::PreLinkFatLTO | llvm::OptStage::PreLinkThinLTO => true,
    _ => false,
}matches!(opt_stage, llvm::OptStage::PreLinkFatLTO | llvm::OptStage::PreLinkThinLTO);
602    let instr_profile_output_path = get_instr_profile_output_path(config);
603    let sanitize_dataflow_abilist: Vec<_> = config
604        .sanitizer_dataflow_abilist
605        .iter()
606        .map(|file| CString::new(file.as_str()).unwrap())
607        .collect();
608    let sanitize_dataflow_abilist_ptrs: Vec<_> =
609        sanitize_dataflow_abilist.iter().map(|file| file.as_ptr()).collect();
610    // Sanitizer instrumentation is only inserted during the pre-link optimization stage.
611    let sanitizer_options = if !is_lto {
612        Some(llvm::SanitizerOptions {
613            sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
614            sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
615            sanitize_cfi: config.sanitizer.contains(SanitizerSet::CFI),
616            sanitize_dataflow: config.sanitizer.contains(SanitizerSet::DATAFLOW),
617            sanitize_dataflow_abilist: sanitize_dataflow_abilist_ptrs.as_ptr(),
618            sanitize_dataflow_abilist_len: sanitize_dataflow_abilist_ptrs.len(),
619            sanitize_kcfi: config.sanitizer.contains(SanitizerSet::KCFI),
620            sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
621            sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
622            sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
623            sanitize_realtime: config.sanitizer.contains(SanitizerSet::REALTIME),
624            sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
625            sanitize_hwaddress: config.sanitizer.contains(SanitizerSet::HWADDRESS),
626            sanitize_hwaddress_recover: config.sanitizer_recover.contains(SanitizerSet::HWADDRESS),
627            sanitize_kernel_address: config.sanitizer.contains(SanitizerSet::KERNELADDRESS),
628            sanitize_kernel_address_recover: config
629                .sanitizer_recover
630                .contains(SanitizerSet::KERNELADDRESS),
631            sanitize_kernel_hwaddress: config.sanitizer.contains(SanitizerSet::KERNELHWADDRESS),
632            sanitize_kernel_hwaddress_recover: config
633                .sanitizer_recover
634                .contains(SanitizerSet::KERNELHWADDRESS),
635        })
636    } else {
637        None
638    };
639
640    fn handle_offload<'ll>(cx: &'ll SimpleCx<'_>, old_fn: &llvm::Value) {
641        let old_fn_ty = cx.get_type_of_global(old_fn);
642        let old_param_types = cx.func_params_types(old_fn_ty);
643        let old_param_count = old_param_types.len();
644        if old_param_count == 0 {
645            return;
646        }
647
648        let first_param = llvm::get_param(old_fn, 0);
649        let c_name = llvm::get_value_name(first_param);
650        let first_arg_name = str::from_utf8(&c_name).unwrap();
651        // We might call llvm_optimize (and thus this code) multiple times on the same IR,
652        // but we shouldn't add this helper ptr multiple times.
653        // FIXME(offload): This could break if the user calls his first argument `dyn_ptr`.
654        if first_arg_name == "dyn_ptr" {
655            return;
656        }
657
658        // Create the new parameter list, with ptr as the first argument
659        let mut new_param_types = Vec::with_capacity(old_param_count as usize + 1);
660        new_param_types.push(cx.type_ptr());
661
662        // This relies on undocumented LLVM knowledge that scalars must be passed as i64
663        for &old_ty in &old_param_types {
664            let new_ty = match cx.type_kind(old_ty) {
665                TypeKind::Half | TypeKind::Float | TypeKind::Double | TypeKind::Integer => {
666                    cx.type_i64()
667                }
668                _ => old_ty,
669            };
670            new_param_types.push(new_ty);
671        }
672
673        // Create the new function type
674        let ret_ty = unsafe { llvm::LLVMGetReturnType(old_fn_ty) };
675        let new_fn_ty = cx.type_func(&new_param_types, ret_ty);
676
677        // Create the new function, with a temporary .offload name to avoid a name collision.
678        let old_fn_name = String::from_utf8(llvm::get_value_name(old_fn)).unwrap();
679        let new_fn_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.offload", &old_fn_name))
    })format!("{}.offload", &old_fn_name);
680        let new_fn = cx.add_func(&new_fn_name, new_fn_ty);
681        let a0 = llvm::get_param(new_fn, 0);
682        llvm::set_value_name(a0, CString::new("dyn_ptr").unwrap().as_bytes());
683
684        let bb = SBuilder::append_block(cx, new_fn, "entry");
685        let mut builder = SBuilder::build(cx, bb);
686
687        let mut old_args_rebuilt = Vec::with_capacity(old_param_types.len());
688
689        for (i, &old_ty) in old_param_types.iter().enumerate() {
690            let new_arg = llvm::get_param(new_fn, (i + 1) as u32);
691
692            let rebuilt = match cx.type_kind(old_ty) {
693                TypeKind::Half | TypeKind::Float | TypeKind::Double | TypeKind::Integer => {
694                    let num_bits = scalar_width(cx, old_ty);
695
696                    let trunc = builder.trunc(new_arg, cx.type_ix(num_bits));
697                    builder.bitcast(trunc, old_ty)
698                }
699                _ => new_arg,
700            };
701
702            old_args_rebuilt.push(rebuilt);
703        }
704
705        builder.ret_void();
706
707        // Here we map the old arguments to the new arguments, with an offset of 1 to make sure
708        // that we don't use the newly added `%dyn_ptr`.
709        unsafe {
710            llvm::RustOffloadWrapper::get_instance().llvm_rust_offload_wrapper(
711                old_fn,
712                new_fn,
713                old_args_rebuilt.as_slice(),
714            );
715        }
716
717        llvm::set_linkage(new_fn, llvm::get_linkage(old_fn));
718        llvm::set_visibility(new_fn, llvm::get_visibility(old_fn));
719
720        // Replace all uses of old_fn with new_fn (RAUW)
721        unsafe {
722            llvm::LLVMReplaceAllUsesWith(old_fn, new_fn);
723        }
724        let name = llvm::get_value_name(old_fn);
725        unsafe {
726            llvm::LLVMDeleteFunction(old_fn);
727        }
728        // Now we can re-use the old name, without name collision.
729        llvm::set_value_name(new_fn, &name);
730    }
731
732    if cgcx.target_is_like_gpu
733        && config.offload.iter().any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
    config::Offload::Device(_) => true,
    _ => false,
}matches!(o, config::Offload::Device(_)))
734    {
735        let cx =
736            SimpleCx::new(module.module_llvm.llmod(), module.module_llvm.llcx, cgcx.pointer_size);
737        for func in cx.get_functions() {
738            let offload_kernel = "offload-kernel";
739            if attributes::has_string_attr(func, offload_kernel) {
740                handle_offload(&cx, func);
741            }
742            attributes::remove_string_attr_from_llfn(func, offload_kernel);
743        }
744    }
745
746    let mut llvm_profiler = prof
747        .llvm_recording_enabled()
748        .then(|| LlvmSelfProfiler::new(prof.get_self_profiler().unwrap()));
749
750    let llvm_selfprofiler =
751        llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut());
752
753    let extra_passes = if !is_lto { config.passes.join(",") } else { "".to_string() };
754
755    let llvm_plugins = config.llvm_plugins.join(",");
756
757    let enzyme_fn = if consider_ad {
758        let wrapper = llvm::EnzymeWrapper::get_instance();
759        wrapper.registerEnzymeAndPassPipeline
760    } else {
761        std::ptr::null()
762    };
763
764    let result = unsafe {
765        llvm::LLVMRustOptimize(
766            module.module_llvm.llmod(),
767            &*module.module_llvm.tm.raw(),
768            to_pass_builder_opt_level(opt_level),
769            opt_stage,
770            cgcx.use_linker_plugin_lto,
771            config.no_prepopulate_passes,
772            config.verify_llvm_ir,
773            config.lint_llvm_ir,
774            thin_lto_buffer,
775            thin_lto_summary_buffer,
776            merge_functions,
777            unroll_loops,
778            vectorize_slp,
779            vectorize_loop,
780            config.no_builtins,
781            config.emit_lifetime_markers,
782            enzyme_fn,
783            print_before_enzyme,
784            print_after_enzyme,
785            print_passes,
786            sanitizer_options.as_ref(),
787            pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
788            pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
789            config.instrument_coverage,
790            instr_profile_output_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
791            pgo_sample_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
792            config.debug_info_for_profiling,
793            llvm_selfprofiler,
794            selfprofile_before_pass_callback,
795            selfprofile_after_pass_callback,
796            passes_after_enzyme_ptr,
797            passes_after_enzyme_len,
798            extra_passes.as_c_char_ptr(),
799            extra_passes.len(),
800            llvm_plugins.as_c_char_ptr(),
801            llvm_plugins.len(),
802        )
803    };
804
805    if cgcx.target_is_like_gpu
806        && config.offload.iter().any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
    config::Offload::Device(_) => true,
    _ => false,
}matches!(o, config::Offload::Device(_)))
807    {
808        let device_path = cgcx.output_filenames.path(OutputType::Object);
809        let device_dir = device_path.parent().unwrap();
810        let device_out = device_dir.join("device.bin");
811        let device_out_c = path_to_c_string(device_out.as_path());
812        // 1) Bundle device module into offload image device.bin (device TM)
813        let ok = unsafe {
814            llvm::RustOffloadWrapper::get_instance().llvm_rust_bundle_images(
815                module.module_llvm.llmod(),
816                module.module_llvm.tm.raw(),
817                device_out_c.as_c_str(),
818            )
819        };
820        if !ok || !device_out.exists() {
821            dcx.emit_err(crate::diagnostics::OffloadBundleImagesFailed);
822        }
823    }
824
825    // This assumes that we previously compiled our kernels for a gpu target, which created a
826    // `device.bin` artifact. The user is supposed to provide us with a path to this artifact, we
827    // don't need any other artifacts from the previous run. We will embed this artifact into our
828    // LLVM-IR host module, to create a `host.o` ObjectFile, which we will write to disk.
829    // The last, not yet automated steps uses the `clang-linker-wrapper` to process `host.o`.
830    if !cgcx.target_is_like_gpu && is_final_stage {
831        if let Some(device_path) = config
832            .offload
833            .iter()
834            .find_map(|o| if let config::Offload::Host(path) = o { Some(path) } else { None })
835        {
836            let device_pathbuf = PathBuf::from(device_path);
837            if device_pathbuf.is_relative() {
838                dcx.emit_err(crate::diagnostics::OffloadWithoutAbsPath);
839            } else if device_pathbuf
840                .file_name()
841                .and_then(|n| n.to_str())
842                .is_some_and(|n| n != "device.bin")
843            {
844                dcx.emit_err(crate::diagnostics::OffloadWrongFileName);
845            } else if !device_pathbuf.exists() {
846                dcx.emit_err(crate::diagnostics::OffloadNonexistingPath);
847            }
848            let host_path = cgcx.output_filenames.path(OutputType::Object);
849            let host_dir = host_path.parent().unwrap();
850            let out_obj = host_dir.join("host.o");
851            let device_bin_c = path_to_c_string(device_pathbuf.as_path());
852
853            // 2) Finalize host: lib.bc + device.bin -> host.o (host TM)
854            // We create a full clone of our LLVM host module, since we will embed the device IR
855            // into it, and this might break caching or incremental compilation otherwise.
856            let ok = unsafe {
857                llvm::RustOffloadWrapper::get_instance().llvm_rust_offload_embed_buffer_in_module(
858                    module.module_llvm.llmod(),
859                    device_bin_c.as_c_str(),
860                )
861            };
862            if !ok {
863                dcx.emit_err(crate::diagnostics::OffloadEmbedFailed);
864            }
865            write_output_file(
866                dcx,
867                module.module_llvm.tm.raw(),
868                config.no_builtins,
869                module.module_llvm.llmod(),
870                &out_obj,
871                None,
872                llvm::FileType::ObjectFile,
873                prof,
874                true,
875            );
876            // We ignore cgcx.save_temps here and unconditionally always keep our `device.bin` artifact.
877            // Otherwise, recompiling the host code would fail since we deleted that device artifact
878            // in the previous host compilation, which would be confusing at best.
879
880            let ok = unsafe {
881                llvm::RustOffloadWrapper::get_instance().llvm_rust_offload_wrap_images(
882                    module.module_llvm.llmod(),
883                    device_bin_c.as_c_str(),
884                )
885            };
886            if !ok {
887                dcx.emit_err(crate::diagnostics::OffloadWrapImagesFailed);
888            }
889        }
890    }
891    result.into_result().unwrap_or_else(|()| llvm_err(dcx, LlvmError::RunLlvmPasses))
892}
893
894// Unsafe due to LLVM calls.
895pub(crate) fn optimize(
896    cgcx: &CodegenContext,
897    prof: &SelfProfilerRef,
898    shared_emitter: &SharedEmitter,
899    module: &mut ModuleCodegen<ModuleLlvm>,
900    config: &ModuleConfig,
901) {
902    let _timer = prof.generic_activity_with_arg("LLVM_module_optimize", &*module.name);
903
904    let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
905    let dcx = dcx.handle();
906
907    let llcx = &*module.module_llvm.llcx;
908    let _handlers =
909        DiagnosticHandlers::new(cgcx, shared_emitter, llcx, module, CodegenDiagnosticsStage::Opt);
910
911    if module.kind == ModuleKind::Regular {
912        save_temp_bitcode(cgcx, module, "no-opt");
913    }
914
915    // FIXME(ZuseZ4): support SanitizeHWAddress and prevent illegal/unsupported opts
916
917    if let Some(opt_level) = config.opt_level {
918        let opt_stage = match cgcx.lto {
919            Lto::Fat => llvm::OptStage::PreLinkFatLTO,
920            Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
921            _ if cgcx.use_linker_plugin_lto => llvm::OptStage::PreLinkThinLTO,
922            _ => llvm::OptStage::PreLinkNoLTO,
923        };
924
925        // If we know that we will later run AD, then we disable vectorization and loop unrolling.
926        // Otherwise we pretend AD is already done and run the normal opt pipeline (=PostAD).
927        let consider_ad = config.autodiff.contains(&config::AutoDiff::Enable);
928        let autodiff_stage = if consider_ad { AutodiffStage::PreAD } else { AutodiffStage::PostAD };
929        // The embedded bitcode is used to run LTO/ThinLTO.
930        // The bitcode obtained during the `codegen` phase is no longer suitable for performing LTO.
931        // It may have undergone LTO due to ThinLocal, so we need to obtain the embedded bitcode at
932        // this point.
933        let (mut thin_lto_buffer, mut thin_lto_summary_buffer) = if (module.kind
934            == ModuleKind::Regular
935            && config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full))
936            || config.emit_thin_lto_summary
937        {
938            (Some(None), config.emit_thin_lto_summary.then_some(None))
939        } else {
940            (None, None)
941        };
942        unsafe {
943            llvm_optimize(
944                cgcx,
945                prof,
946                dcx,
947                module,
948                thin_lto_buffer.as_mut(),
949                thin_lto_summary_buffer.as_mut(),
950                config,
951                opt_level,
952                opt_stage,
953                autodiff_stage,
954            )
955        };
956        if let Some(thin_lto_buffer) = thin_lto_buffer {
957            let thin_lto_buffer = thin_lto_buffer.unwrap();
958            module.thin_lto_buffer = Some(thin_lto_buffer.data().to_vec());
959            let bc_summary_out =
960                cgcx.output_filenames.temp_path_for_cgu(OutputType::ThinLinkBitcode, &module.name);
961            if let Some(thin_lto_summary_buffer) = thin_lto_summary_buffer
962                && let Some(thin_link_bitcode_filename) = bc_summary_out.file_name()
963            {
964                let thin_lto_summary_buffer = thin_lto_summary_buffer.unwrap();
965                let summary_data = thin_lto_summary_buffer.data();
966                prof.artifact_size(
967                    "llvm_bitcode_summary",
968                    thin_link_bitcode_filename.to_string_lossy(),
969                    summary_data.len() as u64,
970                );
971                let _timer = prof.generic_activity_with_arg(
972                    "LLVM_module_codegen_emit_bitcode_summary",
973                    &*module.name,
974                );
975                if let Err(err) = fs::write(&bc_summary_out, summary_data) {
976                    dcx.emit_err(WriteBytecode { path: &bc_summary_out, err });
977                }
978            }
979        }
980    }
981}
982
983pub(crate) fn codegen(
984    cgcx: &CodegenContext,
985    prof: &SelfProfilerRef,
986    shared_emitter: &SharedEmitter,
987    module: ModuleCodegen<ModuleLlvm>,
988    config: &ModuleConfig,
989) -> CompiledModule {
990    let _timer = prof.generic_activity_with_arg("LLVM_module_codegen", &*module.name);
991
992    let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
993    let dcx = dcx.handle();
994
995    {
996        let llmod = module.module_llvm.llmod();
997        let llcx = &*module.module_llvm.llcx;
998        let tm = &*module.module_llvm.tm;
999        let _handlers = DiagnosticHandlers::new(
1000            cgcx,
1001            shared_emitter,
1002            llcx,
1003            &module,
1004            CodegenDiagnosticsStage::Codegen,
1005        );
1006
1007        if cgcx.msvc_imps_needed {
1008            create_msvc_imps(cgcx, llcx, llmod);
1009        }
1010
1011        // Note that if object files are just LLVM bitcode we write bitcode,
1012        // copy it to the .o file, and delete the bitcode if it wasn't
1013        // otherwise requested.
1014
1015        let bc_out = cgcx.output_filenames.temp_path_for_cgu(OutputType::Bitcode, &module.name);
1016        let obj_out = cgcx.output_filenames.temp_path_for_cgu(OutputType::Object, &module.name);
1017
1018        if config.bitcode_needed() {
1019            if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
1020                let thin = {
1021                    let _timer = prof.generic_activity_with_arg(
1022                        "LLVM_module_codegen_make_bitcode",
1023                        &*module.name,
1024                    );
1025                    ModuleBuffer::new(llmod, cgcx.lto != Lto::Fat)
1026                };
1027                let data = thin.data();
1028                let _timer = prof
1029                    .generic_activity_with_arg("LLVM_module_codegen_emit_bitcode", &*module.name);
1030                if let Some(bitcode_filename) = bc_out.file_name() {
1031                    prof.artifact_size(
1032                        "llvm_bitcode",
1033                        bitcode_filename.to_string_lossy(),
1034                        data.len() as u64,
1035                    );
1036                }
1037                if let Err(err) = fs::write(&bc_out, data) {
1038                    dcx.emit_err(WriteBytecode { path: &bc_out, err });
1039                }
1040            }
1041
1042            if config.embed_bitcode() && module.kind == ModuleKind::Regular {
1043                let _timer = prof
1044                    .generic_activity_with_arg("LLVM_module_codegen_embed_bitcode", &*module.name);
1045                let thin_bc =
1046                    module.thin_lto_buffer.as_deref().expect("cannot find embedded bitcode");
1047                embed_bitcode(cgcx, llcx, llmod, &thin_bc);
1048            }
1049        }
1050
1051        if config.emit_ir {
1052            let _timer =
1053                prof.generic_activity_with_arg("LLVM_module_codegen_emit_ir", &*module.name);
1054            let out =
1055                cgcx.output_filenames.temp_path_for_cgu(OutputType::LlvmAssembly, &module.name);
1056            let out_c = path_to_c_string(&out);
1057
1058            extern "C" fn demangle_callback(
1059                input_ptr: *const c_char,
1060                input_len: size_t,
1061                output_ptr: *mut c_char,
1062                output_len: size_t,
1063            ) -> size_t {
1064                let input =
1065                    unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
1066
1067                let Ok(input) = str::from_utf8(input) else { return 0 };
1068
1069                let output = unsafe {
1070                    slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
1071                };
1072                let mut cursor = io::Cursor::new(output);
1073
1074                let Ok(demangled) = rustc_demangle::try_demangle(input) else { return 0 };
1075
1076                if cursor.write_fmt(format_args!("{0:#}", demangled))write!(cursor, "{demangled:#}").is_err() {
1077                    // Possible only if provided buffer is not big enough
1078                    return 0;
1079                }
1080
1081                cursor.position() as size_t
1082            }
1083
1084            let result =
1085                unsafe { llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback) };
1086
1087            if result == llvm::LLVMRustResult::Success {
1088                record_artifact_size(prof, "llvm_ir", &out);
1089            }
1090
1091            result
1092                .into_result()
1093                .unwrap_or_else(|()| llvm_err(dcx, LlvmError::WriteIr { path: &out }));
1094        }
1095
1096        if config.emit_asm {
1097            let _timer =
1098                prof.generic_activity_with_arg("LLVM_module_codegen_emit_asm", &*module.name);
1099            let path = cgcx.output_filenames.temp_path_for_cgu(OutputType::Assembly, &module.name);
1100
1101            // We can't use the same module for asm and object code output,
1102            // because that triggers various errors like invalid IR or broken
1103            // binaries. So we must clone the module to produce the asm output
1104            // if we are also producing object code.
1105            let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
1106                llvm::LLVMCloneModule(llmod)
1107            } else {
1108                llmod
1109            };
1110            write_output_file(
1111                dcx,
1112                tm.raw(),
1113                config.no_builtins,
1114                llmod,
1115                &path,
1116                None,
1117                llvm::FileType::AssemblyFile,
1118                prof,
1119                config.verify_llvm_ir,
1120            );
1121        }
1122
1123        match config.emit_obj {
1124            EmitObj::ObjectCode(_) => {
1125                let _timer =
1126                    prof.generic_activity_with_arg("LLVM_module_codegen_emit_obj", &*module.name);
1127
1128                let dwo_out = cgcx.output_filenames.temp_path_dwo_for_cgu(&module.name);
1129                let dwo_out = match (cgcx.split_debuginfo, cgcx.split_dwarf_kind) {
1130                    // Don't change how DWARF is emitted when disabled.
1131                    (SplitDebuginfo::Off, _) => None,
1132                    // Don't provide a DWARF object path if split debuginfo is enabled but this is
1133                    // a platform that doesn't support Split DWARF.
1134                    _ if !cgcx.target_can_use_split_dwarf => None,
1135                    // Don't provide a DWARF object path in single mode, sections will be written
1136                    // into the object as normal but ignored by linker.
1137                    (_, SplitDwarfKind::Single) => None,
1138                    // Emit (a subset of the) DWARF into a separate dwarf object file in split
1139                    // mode.
1140                    (_, SplitDwarfKind::Split) => Some(dwo_out.as_path()),
1141                };
1142
1143                write_output_file(
1144                    dcx,
1145                    tm.raw(),
1146                    config.no_builtins,
1147                    llmod,
1148                    &obj_out,
1149                    dwo_out,
1150                    llvm::FileType::ObjectFile,
1151                    prof,
1152                    config.verify_llvm_ir,
1153                );
1154            }
1155
1156            EmitObj::Bitcode => {
1157                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/back/write.rs:1157",
                        "rustc_codegen_llvm::back::write", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/back/write.rs"),
                        ::tracing_core::__macro_support::Option::Some(1157u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::write"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("copying bitcode {0:?} to obj {1:?}",
                                                    bc_out, obj_out) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
1158                if let Err(err) = link_or_copy(&bc_out, &obj_out) {
1159                    dcx.emit_err(CopyBitcode { err });
1160                }
1161
1162                if !config.emit_bc {
1163                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/back/write.rs:1163",
                        "rustc_codegen_llvm::back::write", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/back/write.rs"),
                        ::tracing_core::__macro_support::Option::Some(1163u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::write"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("removing_bitcode {0:?}",
                                                    bc_out) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("removing_bitcode {:?}", bc_out);
1164                    ensure_removed(dcx, &bc_out);
1165                }
1166            }
1167
1168            EmitObj::None => {}
1169        }
1170
1171        record_llvm_cgu_instructions_stats(prof, &module.name, llmod);
1172    }
1173
1174    // `.dwo` files are only emitted if:
1175    //
1176    // - Object files are being emitted (i.e. bitcode only or metadata only compilations will not
1177    //   produce dwarf objects, even if otherwise enabled)
1178    // - Target supports Split DWARF
1179    // - Split debuginfo is enabled
1180    // - Split DWARF kind is `split` (i.e. debuginfo is split into `.dwo` files, not different
1181    //   sections in the `.o` files).
1182    let dwarf_object_emitted = #[allow(non_exhaustive_omitted_patterns)] match config.emit_obj {
    EmitObj::ObjectCode(_) => true,
    _ => false,
}matches!(config.emit_obj, EmitObj::ObjectCode(_))
1183        && cgcx.target_can_use_split_dwarf
1184        && cgcx.split_debuginfo != SplitDebuginfo::Off
1185        && cgcx.split_dwarf_kind == SplitDwarfKind::Split;
1186    module.into_compiled_module(
1187        config.emit_obj != EmitObj::None,
1188        dwarf_object_emitted,
1189        config.emit_bc,
1190        config.emit_asm,
1191        config.emit_ir,
1192        &cgcx.output_filenames,
1193    )
1194}
1195
1196fn create_section_with_flags_asm(section_name: &str, section_flags: &str, data: &[u8]) -> Vec<u8> {
1197    let mut asm = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".section {0},\"{1}\"\n",
                section_name, section_flags))
    })format!(".section {section_name},\"{section_flags}\"\n").into_bytes();
1198    asm.extend_from_slice(b".ascii \"");
1199    asm.reserve(data.len());
1200    for &byte in data {
1201        if byte == b'\\' || byte == b'"' {
1202            asm.push(b'\\');
1203            asm.push(byte);
1204        } else if byte < 0x20 || byte >= 0x80 {
1205            // Avoid non UTF-8 inline assembly. Use octal escape sequence, because it is fixed
1206            // width, while hex escapes will consume following characters.
1207            asm.push(b'\\');
1208            asm.push(b'0' + ((byte >> 6) & 0x7));
1209            asm.push(b'0' + ((byte >> 3) & 0x7));
1210            asm.push(b'0' + ((byte >> 0) & 0x7));
1211        } else {
1212            asm.push(byte);
1213        }
1214    }
1215    asm.extend_from_slice(b"\"\n");
1216    asm
1217}
1218
1219pub(crate) fn bitcode_section_name(cgcx: &CodegenContext) -> &'static CStr {
1220    if cgcx.target_is_like_darwin {
1221        c"__LLVM,__bitcode"
1222    } else if cgcx.target_is_like_aix {
1223        c".ipa"
1224    } else {
1225        c".llvmbc"
1226    }
1227}
1228
1229/// Embed the bitcode of an LLVM module for LTO in the LLVM module itself.
1230fn embed_bitcode(
1231    cgcx: &CodegenContext,
1232    llcx: &llvm::Context,
1233    llmod: &llvm::Module,
1234    bitcode: &[u8],
1235) {
1236    // We're adding custom sections to the output object file, but we definitely
1237    // do not want these custom sections to make their way into the final linked
1238    // executable. The purpose of these custom sections is for tooling
1239    // surrounding object files to work with the LLVM IR, if necessary. For
1240    // example rustc's own LTO will look for LLVM IR inside of the object file
1241    // in these sections by default.
1242    //
1243    // To handle this is a bit different depending on the object file format
1244    // used by the backend, broken down into a few different categories:
1245    //
1246    // * Mach-O - this is for macOS. Inspecting the source code for the native
1247    //   linker here shows that the `.llvmbc` and `.llvmcmd` sections are
1248    //   automatically skipped by the linker. In that case there's nothing extra
1249    //   that we need to do here. We do need to make sure that the
1250    //   `__LLVM,__cmdline` section exists even though it is empty as otherwise
1251    //   ld64 rejects the object file.
1252    //
1253    // * Wasm - the native LLD linker is hard-coded to skip `.llvmbc` and
1254    //   `.llvmcmd` sections, so there's nothing extra we need to do.
1255    //
1256    // * COFF - if we don't do anything the linker will by default copy all
1257    //   these sections to the output artifact, not what we want! To subvert
1258    //   this we want to flag the sections we inserted here as
1259    //   `IMAGE_SCN_LNK_REMOVE`.
1260    //
1261    // * ELF - this is very similar to COFF above. One difference is that these
1262    //   sections are removed from the output linked artifact when
1263    //   `--gc-sections` is passed, which we pass by default. If that flag isn't
1264    //   passed though then these sections will show up in the final output.
1265    //   Additionally the flag that we need to set here is `SHF_EXCLUDE`.
1266    //
1267    // * XCOFF - AIX linker ignores content in .ipa and .info if no auxiliary
1268    //   symbol associated with these sections.
1269    //
1270    // Unfortunately, LLVM provides no way to set custom section flags. For ELF
1271    // and COFF we emit the sections using module level inline assembly for that
1272    // reason (see issue #90326 for historical background).
1273
1274    if cgcx.target_is_like_darwin
1275        || cgcx.target_is_like_aix
1276        || cgcx.target_arch == "wasm32"
1277        || cgcx.target_arch == "wasm64"
1278    {
1279        // We don't need custom section flags, create LLVM globals.
1280        let llconst = common::bytes_in_context(llcx, bitcode);
1281        let llglobal = llvm::add_global(llmod, common::val_ty(llconst), c"rustc.embedded.module");
1282        llvm::set_initializer(llglobal, llconst);
1283
1284        llvm::set_section(llglobal, bitcode_section_name(cgcx));
1285        llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage);
1286        llvm::LLVMSetGlobalConstant(llglobal, llvm::TRUE);
1287
1288        let llconst = common::bytes_in_context(llcx, &[]);
1289        let llglobal = llvm::add_global(llmod, common::val_ty(llconst), c"rustc.embedded.cmdline");
1290        llvm::set_initializer(llglobal, llconst);
1291        let section = if cgcx.target_is_like_darwin {
1292            c"__LLVM,__cmdline"
1293        } else if cgcx.target_is_like_aix {
1294            c".info"
1295        } else {
1296            c".llvmcmd"
1297        };
1298        llvm::set_section(llglobal, section);
1299        llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage);
1300    } else {
1301        // We need custom section flags, so emit module-level inline assembly.
1302        let section_flags = if cgcx.is_pe_coff { "n" } else { "e" };
1303        let asm = create_section_with_flags_asm(".llvmbc", section_flags, bitcode);
1304        llvm::append_module_inline_asm(llmod, &asm, "", "");
1305        let asm = create_section_with_flags_asm(".llvmcmd", section_flags, &[]);
1306        llvm::append_module_inline_asm(llmod, &asm, "", "");
1307    }
1308}
1309
1310// Create a `__imp_<symbol> = &symbol` global for each externally visible
1311// static data symbol, including aliases to static data.
1312// This is required to satisfy `dllimport` references to static data in .rlibs
1313// when using MSVC linker. We do this only for data, as linker can fix up
1314// code references on its own.
1315// See #26591, #27438
1316fn create_msvc_imps(cgcx: &CodegenContext, llcx: &llvm::Context, llmod: &llvm::Module) {
1317    if !cgcx.msvc_imps_needed {
1318        return;
1319    }
1320    // The x86 ABI seems to require that leading underscores are added to symbol
1321    // names, so we need an extra underscore on x86. There's also a leading
1322    // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
1323    // underscores added in front).
1324    let prefix: &[u8] = if cgcx.target_arch == "x86" { b"\x01__imp__" } else { b"\x01__imp_" };
1325
1326    let ptr_ty = llvm_type_ptr(llcx);
1327    let symbols = std::iter::chain(
1328        base::iter_globals(llmod),
1329        base::iter_global_aliases(llmod).filter(|&val| {
1330            llvm::LLVMGetTypeKind(unsafe { llvm::LLVMGlobalGetValueType(val) }).to_rust()
1331                != llvm::TypeKind::Function
1332        }),
1333    )
1334    .map(|val| (val, llvm::get_linkage(val)))
1335    .filter(|&(val, linkage)| {
1336        #[allow(non_exhaustive_omitted_patterns)] match linkage {
    llvm::Linkage::ExternalLinkage | llvm::Linkage::WeakAnyLinkage => true,
    _ => false,
}matches!(linkage, llvm::Linkage::ExternalLinkage | llvm::Linkage::WeakAnyLinkage)
1337            && !llvm::is_declaration(val)
1338    })
1339    .collect::<Vec<_>>();
1340
1341    for (val, linkage) in symbols {
1342        let name = llvm::get_value_name(val);
1343        // Exclude some symbols that we know are not Rust symbols.
1344        if ignored(&name) {
1345            continue;
1346        }
1347
1348        let mut imp_name = prefix.to_vec();
1349        imp_name.extend(name);
1350        let imp_name = CString::new(imp_name).unwrap();
1351
1352        let imp = llvm::add_global(llmod, ptr_ty, &imp_name);
1353
1354        llvm::set_initializer(imp, val);
1355        llvm::set_linkage(imp, linkage);
1356    }
1357
1358    // Use this function to exclude certain symbols from `__imp` generation.
1359    fn ignored(symbol_name: &[u8]) -> bool {
1360        // These are symbols generated by LLVM's profiling instrumentation
1361        symbol_name.starts_with(b"__llvm_profile_")
1362    }
1363}
1364
1365fn record_artifact_size(
1366    self_profiler_ref: &SelfProfilerRef,
1367    artifact_kind: &'static str,
1368    path: &Path,
1369) {
1370    // Don't stat the file if we are not going to record its size.
1371    if !self_profiler_ref.enabled() {
1372        return;
1373    }
1374
1375    if let Some(artifact_name) = path.file_name() {
1376        let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
1377        self_profiler_ref.artifact_size(artifact_kind, artifact_name.to_string_lossy(), file_size);
1378    }
1379}
1380
1381fn record_llvm_cgu_instructions_stats(prof: &SelfProfilerRef, name: &str, llmod: &llvm::Module) {
1382    if !prof.enabled() {
1383        return;
1384    }
1385
1386    let total = unsafe { llvm::LLVMRustModuleInstructionStats(llmod) };
1387    prof.artifact_size("cgu_instructions", name, total);
1388}