[go: up one dir, main page]

rustc_codegen_llvm/back/
write.rs

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