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