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