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