Skip to main content

rustc_codegen_llvm/
context.rs

1use std::borrow::{Borrow, Cow};
2use std::cell::{Cell, RefCell};
3use std::ffi::{CStr, c_uint};
4use std::marker::PhantomData;
5use std::ops::{Deref, DerefMut};
6use std::str;
7
8use rustc_abi::{HasDataLayout, Size, TargetDataLayout, VariantIdx};
9use rustc_codegen_ssa::back::versioned_llvm_target;
10use rustc_codegen_ssa::base::{wants_msvc_seh, wants_wasm_eh};
11use rustc_codegen_ssa::diagnostics as ssa_errors;
12use rustc_codegen_ssa::traits::*;
13use rustc_data_structures::base_n::{ALPHANUMERIC_ONLY, ToBaseN};
14use rustc_data_structures::fx::FxHashMap;
15use rustc_data_structures::small_c_str::SmallCStr;
16use rustc_hir::def_id::DefId;
17use rustc_middle::mono::CodegenUnit;
18use rustc_middle::ty::layout::{
19    FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers,
20    codegen_handle_fn_abi_err,
21};
22use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
23use rustc_sanitizers::ignorelist::{SanitizerIgnoreList, typename_for_ignore_list};
24use rustc_session::config::{
25    BranchProtection, CFGuard, CFProtection, DebugInfo, FunctionReturn, PAuthKey, PacRet,
26};
27use rustc_session::{PointerAuthSchema, Session};
28use rustc_span::{DUMMY_SP, Span, Symbol, bug, sym};
29use rustc_structures::CrateType;
30use rustc_target::spec::{
31    Arch, CfgAbi, Env, FramePointer, HasTargetSpec, Os, RelocModel, SmallDataThresholdSupport,
32    Target, TlsModel,
33};
34use smallvec::SmallVec;
35
36use crate::abi::to_llvm_calling_convention;
37use crate::back::llvm_backend::ModuleRefs;
38use crate::back::write::to_llvm_code_model;
39use crate::builder::gpu_offload::{OffloadGlobals, OffloadKernelGlobals};
40use crate::callee::get_fn;
41use crate::debuginfo::metadata::apply_vcall_visibility_metadata;
42use crate::llvm::{self, Metadata, MetadataKindId, Module, Type, Value};
43use crate::{attributes, common, coverageinfo, debuginfo, llvm_util};
44
45/// `TyCtxt` (and related cache datastructures) can't be move between threads.
46/// However, there are various cx related functions which we want to be available to the builder and
47/// other compiler pieces. Here we define a small subset which has enough information and can be
48/// moved around more freely.
49pub(crate) struct SCx<'ll> {
50    pub llmod: &'ll llvm::Module,
51    pub llcx: &'ll llvm::Context,
52    pub isize_ty: &'ll Type,
53}
54
55impl<'ll> Borrow<SCx<'ll>> for FullCx<'ll, '_> {
56    fn borrow(&self) -> &SCx<'ll> {
57        &self.scx
58    }
59}
60
61impl<'ll, 'tcx> Deref for FullCx<'ll, 'tcx> {
62    type Target = SimpleCx<'ll>;
63
64    #[inline]
65    fn deref(&self) -> &Self::Target {
66        &self.scx
67    }
68}
69
70pub(crate) struct GenericCx<'ll, T: Borrow<SCx<'ll>>>(T, PhantomData<SCx<'ll>>);
71
72impl<'ll, T: Borrow<SCx<'ll>>> Deref for GenericCx<'ll, T> {
73    type Target = T;
74
75    #[inline]
76    fn deref(&self) -> &Self::Target {
77        &self.0
78    }
79}
80
81impl<'ll, T: Borrow<SCx<'ll>>> DerefMut for GenericCx<'ll, T> {
82    #[inline]
83    fn deref_mut(&mut self) -> &mut Self::Target {
84        &mut self.0
85    }
86}
87
88pub(crate) type SimpleCx<'ll> = GenericCx<'ll, SCx<'ll>>;
89
90/// There is one `CodegenCx` per codegen unit. Each one has its own LLVM
91/// `llvm::Context` so that several codegen units may be processed in parallel.
92/// All other LLVM data structures in the `CodegenCx` are tied to that `llvm::Context`.
93pub(crate) type CodegenCx<'ll, 'tcx> = GenericCx<'ll, FullCx<'ll, 'tcx>>;
94
95pub(crate) struct FullCx<'ll, 'tcx> {
96    pub tcx: TyCtxt<'tcx>,
97    pub bitcode_needed: bool,
98    pub scx: SimpleCx<'ll>,
99    pub use_dll_storage_attrs: bool,
100    pub tls_model: llvm::ThreadLocalMode,
101
102    pub codegen_unit: &'tcx CodegenUnit<'tcx>,
103
104    /// Cache instances of monomorphic and polymorphic items
105    pub instances: RefCell<FxHashMap<Instance<'tcx>, &'ll Value>>,
106    /// Cache instances of intrinsics
107    pub intrinsic_instances: RefCell<FxHashMap<Instance<'tcx>, &'ll Value>>,
108    /// Cache generated vtables
109    pub vtables: RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>>,
110    /// Cache of constant strings,
111    pub const_str_cache: RefCell<FxHashMap<String, &'ll Value>>,
112
113    /// Cache of emitted const globals (value -> global)
114    pub const_globals: RefCell<FxHashMap<&'ll Value, &'ll Value>>,
115
116    /// List of globals for static variables which need to be passed to the
117    /// LLVM function ReplaceAllUsesWith (RAUW) when codegen is complete.
118    /// (We have to make sure we don't invalidate any Values referring
119    /// to constants.)
120    pub statics_to_rauw: RefCell<Vec<(&'ll Value, &'ll Value)>>,
121
122    /// Statics that will be placed in the llvm.used variable
123    /// See <https://llvm.org/docs/LangRef.html#the-llvm-used-global-variable> for details
124    pub used_statics: Vec<&'ll Value>,
125
126    /// Statics that will be placed in the llvm.compiler.used variable
127    /// See <https://llvm.org/docs/LangRef.html#the-llvm-compiler-used-global-variable> for details
128    pub compiler_used_statics: RefCell<Vec<&'ll Value>>,
129
130    /// Mapping of non-scalar types to llvm types.
131    pub type_lowering: RefCell<FxHashMap<(Ty<'tcx>, Option<VariantIdx>), &'ll Type>>,
132
133    /// Mapping of scalar types to llvm types.
134    pub scalar_lltypes: RefCell<FxHashMap<Ty<'tcx>, &'ll Type>>,
135
136    /// Extra per-CGU codegen state needed when coverage instrumentation is enabled.
137    pub coverage_cx: Option<coverageinfo::CguCoverageContext<'ll, 'tcx>>,
138    pub dbg_cx: Option<debuginfo::CodegenUnitDebugContext<'ll, 'tcx>>,
139    pub sanitizer_ignorelist: Option<SanitizerIgnoreList>,
140
141    eh_personality: Cell<Option<&'ll Value>>,
142    pub rust_try_fn: Cell<Option<(&'ll Type, &'ll Value)>>,
143
144    intrinsics:
145        RefCell<FxHashMap<(Cow<'static, str>, SmallVec<[&'ll Type; 2]>), (&'ll Type, &'ll Value)>>,
146
147    /// A counter that is used for generating local symbol names
148    local_gen_sym_counter: Cell<usize>,
149
150    /// A counter that is used for generating global symbol names
151    global_gen_sym_counter: Cell<usize>,
152
153    /// `codegen_static` will sometimes create a second global variable with a
154    /// different type and clear the symbol name of the original global.
155    /// `global_asm!` needs to be able to find this new global so that it can
156    /// compute the correct mangled symbol name to insert into the asm.
157    pub renamed_statics: RefCell<FxHashMap<DefId, &'ll Value>>,
158
159    /// Cached Objective-C class type
160    pub objc_class_t: Cell<Option<&'ll Type>>,
161
162    /// Cache of Objective-C class references
163    pub objc_classrefs: RefCell<FxHashMap<Symbol, &'ll Value>>,
164
165    /// Cache of Objective-C selector references
166    pub objc_selrefs: RefCell<FxHashMap<Symbol, &'ll Value>>,
167
168    /// Globals shared by the offloading runtime
169    pub offload_globals: RefCell<Option<OffloadGlobals<'ll>>>,
170
171    /// Cache of kernel-specific globals
172    pub offload_kernel_cache: RefCell<FxHashMap<String, OffloadKernelGlobals<'ll>>>,
173}
174
175fn to_llvm_tls_model(tls_model: TlsModel) -> llvm::ThreadLocalMode {
176    match tls_model {
177        TlsModel::GeneralDynamic => llvm::ThreadLocalMode::GeneralDynamic,
178        TlsModel::LocalDynamic => llvm::ThreadLocalMode::LocalDynamic,
179        TlsModel::InitialExec => llvm::ThreadLocalMode::InitialExec,
180        TlsModel::LocalExec => llvm::ThreadLocalMode::LocalExec,
181        TlsModel::Emulated => llvm::ThreadLocalMode::GeneralDynamic,
182    }
183}
184
185pub(crate) unsafe fn create_module<'ll>(
186    tcx: TyCtxt<'_>,
187    llcx: &'ll llvm::Context,
188    mod_name: &str,
189) -> *const llvm::Module {
190    let mod_name_cstr = SmallCStr::new(mod_name);
191    let llmod_raw =
192        unsafe { llvm::LLVMModuleCreateWithNameInContext(mod_name_cstr.as_ptr(), llcx) };
193    init_module(tcx, llcx, unsafe { &*llmod_raw });
194    llmod_raw
195}
196
197fn init_module<'ll, 'tcx>(tcx: TyCtxt<'tcx>, llcx: &'ll llvm::Context, llmod: &'ll llvm::Module) {
198    let sess = tcx.sess;
199    let cx = SimpleCx::new(llmod, llcx, tcx.data_layout.pointer_size());
200
201    let mut target_data_layout = sess.target.data_layout.to_string();
202    let llvm_version = llvm_util::get_version();
203
204    if llvm_version < (23, 0, 0) {
205        if sess.target.arch == Arch::S390x {
206            // LLVM 23 updated the s390x layout to specify the stack alignment: https://github.com/llvm/llvm-project/pull/176041
207            target_data_layout = target_data_layout.replace("-S64", "");
208        }
209    }
210
211    // Ensure the data-layout values hardcoded remain the defaults.
212    {
213        let tm = crate::back::write::create_informational_target_machine(sess);
214        unsafe {
215            llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm.raw());
216        }
217
218        let llvm_data_layout = unsafe { llvm::LLVMGetDataLayoutStr(llmod) };
219        let llvm_data_layout =
220            str::from_utf8(unsafe { CStr::from_ptr(llvm_data_layout) }.to_bytes())
221                .expect("got a non-UTF8 data-layout from LLVM");
222
223        if target_data_layout != llvm_data_layout {
224            tcx.dcx().emit_err(crate::diagnostics::MismatchedDataLayout {
225                rustc_target: sess.opts.target_triple.to_string().as_str(),
226                rustc_layout: target_data_layout.as_str(),
227                llvm_target: sess.target.llvm_target.borrow(),
228                llvm_layout: llvm_data_layout,
229            });
230        }
231    }
232
233    let data_layout = SmallCStr::new(&target_data_layout);
234    unsafe {
235        llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
236    }
237
238    let llvm_target = SmallCStr::new(&versioned_llvm_target(sess));
239    unsafe {
240        llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
241    }
242
243    let reloc_model = sess.relocation_model();
244    if #[allow(non_exhaustive_omitted_patterns)] match reloc_model {
    RelocModel::Pic | RelocModel::Pie => true,
    _ => false,
}matches!(reloc_model, RelocModel::Pic | RelocModel::Pie) {
245        unsafe {
246            llvm::LLVMRustSetModulePICLevel(llmod);
247        }
248        // PIE is potentially more effective than PIC, but can only be used in executables.
249        // If all our outputs are executables, then we can relax PIC to PIE.
250        if reloc_model == RelocModel::Pie
251            || tcx.crate_types().iter().all(|ty| *ty == CrateType::Executable)
252        {
253            unsafe {
254                llvm::LLVMRustSetModulePIELevel(llmod);
255            }
256        }
257    }
258
259    // Linking object files with different code models is undefined behavior
260    // because the compiler would have to generate additional code (to span
261    // longer jumps) if a larger code model is used with a smaller one.
262    //
263    // See https://reviews.llvm.org/D52322 and https://reviews.llvm.org/D52323.
264    unsafe {
265        llvm::LLVMRustSetModuleCodeModel(llmod, to_llvm_code_model(sess.code_model()));
266    }
267
268    if let Some(large_data_threshold) = sess.opts.unstable_opts.large_data_threshold {
269        unsafe {
270            llvm::LLVMRustSetModuleLargeDataThreshold(llmod, large_data_threshold);
271        }
272    }
273
274    // If skipping the PLT is enabled, we need to add some module metadata
275    // to ensure intrinsic calls don't use it.
276    if !sess.needs_plt() {
277        llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "RtLibUseGOT", 1);
278    }
279
280    // Enable canonical jump tables if CFI is enabled. (See https://reviews.llvm.org/D65629.)
281    if sess.is_sanitizer_cfi_canonical_jump_tables_enabled() && sess.is_sanitizer_cfi_enabled() {
282        llvm::add_module_flag_u32(
283            llmod,
284            llvm::ModuleFlagMergeBehavior::Override,
285            "CFI Canonical Jump Tables",
286            1,
287        );
288    }
289
290    // If we're normalizing integers with CFI, ensure LLVM generated functions do the same.
291    // See https://github.com/llvm/llvm-project/pull/104826
292    if sess.is_sanitizer_cfi_normalize_integers_enabled() {
293        llvm::add_module_flag_u32(
294            llmod,
295            llvm::ModuleFlagMergeBehavior::Override,
296            "cfi-normalize-integers",
297            1,
298        );
299    }
300
301    // Enable LTO unit splitting if specified or if CFI is enabled. (See
302    // https://reviews.llvm.org/D53891.)
303    if sess.is_split_lto_unit_enabled() || sess.is_sanitizer_cfi_enabled() {
304        llvm::add_module_flag_u32(
305            llmod,
306            llvm::ModuleFlagMergeBehavior::Override,
307            "EnableSplitLTOUnit",
308            1,
309        );
310    }
311
312    if sess.must_emit_unwind_tables() {
313        // This assertion checks that Max is the correct merge behavior.
314        // Async unwind tables are strictly more useful than sync uwtables.
315        const {
316            if !((llvm::UWTableKind::None as u32) < (llvm::UWTableKind::Sync as u32)) {
    ::core::panicking::panic("assertion failed: (llvm::UWTableKind::None as u32) < (llvm::UWTableKind::Sync as u32)")
};assert!((llvm::UWTableKind::None as u32) < (llvm::UWTableKind::Sync as u32));
317            if !((llvm::UWTableKind::Sync as u32) < (llvm::UWTableKind::Async as u32)) {
    ::core::panicking::panic("assertion failed: (llvm::UWTableKind::Sync as u32) < (llvm::UWTableKind::Async as u32)")
};assert!((llvm::UWTableKind::Sync as u32) < (llvm::UWTableKind::Async as u32));
318        }
319
320        llvm::add_module_flag_u32(
321            llmod,
322            llvm::ModuleFlagMergeBehavior::Max,
323            "uwtable",
324            match sess.opts.unstable_opts.use_sync_unwind {
325                Some(true) => llvm::UWTableKind::Sync as u32,
326                Some(false) | None => llvm::UWTableKind::Async as u32,
327            },
328        );
329    }
330
331    // Add "kcfi" module flag if KCFI is enabled. (See https://reviews.llvm.org/D119296.)
332    if sess.is_sanitizer_kcfi_enabled() {
333        llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Override, "kcfi", 1);
334
335        // Add "kcfi-offset" module flag with -Z patchable-function-entry (See
336        // https://reviews.llvm.org/D141172).
337        let patchable_prefix_nops = sess.opts.unstable_opts.patchable_function_entry.prefix();
338        if patchable_prefix_nops > 0 {
339            llvm::add_module_flag_u32(
340                llmod,
341                llvm::ModuleFlagMergeBehavior::Override,
342                "kcfi-offset",
343                patchable_prefix_nops.into(),
344            );
345        }
346
347        // Add "kcfi-arity" module flag if KCFI arity indicator is enabled. (See
348        // https://github.com/llvm/llvm-project/pull/117121.)
349        if sess.is_sanitizer_kcfi_arity_enabled() {
350            llvm::add_module_flag_u32(
351                llmod,
352                llvm::ModuleFlagMergeBehavior::Override,
353                "kcfi-arity",
354                1,
355            );
356        }
357    }
358
359    // Control Flow Guard is currently only supported by MSVC and LLVM on Windows.
360    if sess.target.is_like_msvc
361        || (sess.target.options.os == Os::Windows
362            && sess.target.options.env == Env::Gnu
363            && sess.target.options.cfg_abi == CfgAbi::Llvm)
364    {
365        match sess.opts.cg.control_flow_guard {
366            CFGuard::Disabled => {}
367            CFGuard::NoChecks => {
368                // Set `cfguard=1` module flag to emit metadata only.
369                llvm::add_module_flag_u32(
370                    llmod,
371                    llvm::ModuleFlagMergeBehavior::Warning,
372                    "cfguard",
373                    1,
374                );
375            }
376            CFGuard::Checks => {
377                // Set `cfguard=2` module flag to emit metadata and checks.
378                llvm::add_module_flag_u32(
379                    llmod,
380                    llvm::ModuleFlagMergeBehavior::Warning,
381                    "cfguard",
382                    2,
383                );
384            }
385        }
386    }
387
388    if let Some(regparm_count) = sess.opts.unstable_opts.regparm {
389        llvm::add_module_flag_u32(
390            llmod,
391            llvm::ModuleFlagMergeBehavior::Error,
392            "NumRegisterParameters",
393            regparm_count,
394        );
395    }
396
397    if let Some(BranchProtection { bti, pac_ret, gcs }) = sess.branch_protection() {
398        if sess.target.arch == Arch::AArch64 {
399            llvm::add_module_flag_u32(
400                llmod,
401                llvm::ModuleFlagMergeBehavior::Min,
402                "branch-target-enforcement",
403                bti.into(),
404            );
405            llvm::add_module_flag_u32(
406                llmod,
407                llvm::ModuleFlagMergeBehavior::Min,
408                "sign-return-address",
409                pac_ret.is_some().into(),
410            );
411            let pac_opts = pac_ret.unwrap_or_else(|| {
412                // Windows on Arm only supports PAC key B.
413                let key = if sess.target.os == Os::Windows { PAuthKey::B } else { PAuthKey::A };
414                PacRet { leaf: false, pc: false, key }
415            });
416            llvm::add_module_flag_u32(
417                llmod,
418                llvm::ModuleFlagMergeBehavior::Min,
419                "branch-protection-pauth-lr",
420                pac_opts.pc.into(),
421            );
422            llvm::add_module_flag_u32(
423                llmod,
424                llvm::ModuleFlagMergeBehavior::Min,
425                "sign-return-address-all",
426                pac_opts.leaf.into(),
427            );
428            llvm::add_module_flag_u32(
429                llmod,
430                llvm::ModuleFlagMergeBehavior::Min,
431                "sign-return-address-with-bkey",
432                u32::from(pac_opts.key == PAuthKey::B),
433            );
434            llvm::add_module_flag_u32(
435                llmod,
436                llvm::ModuleFlagMergeBehavior::Min,
437                "guarded-control-stack",
438                gcs.into(),
439            );
440        } else {
441            ::rustc_span::macros::bug_impl(None,
    format_args!("branch-protection used on non-AArch64 target; this should be checked in rustc_session."),
    Location::caller());bug!(
442                "branch-protection used on non-AArch64 target; \
443                  this should be checked in rustc_session."
444            );
445        }
446    }
447
448    // Pass on the control-flow protection flags to LLVM (equivalent to `-fcf-protection` in Clang).
449    if let CFProtection::Branch | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
450        llvm::add_module_flag_u32(
451            llmod,
452            llvm::ModuleFlagMergeBehavior::Override,
453            "cf-protection-branch",
454            1,
455        );
456    }
457    if let CFProtection::Return | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
458        llvm::add_module_flag_u32(
459            llmod,
460            llvm::ModuleFlagMergeBehavior::Override,
461            "cf-protection-return",
462            1,
463        );
464    }
465
466    if sess.opts.unstable_opts.virtual_function_elimination {
467        llvm::add_module_flag_u32(
468            llmod,
469            llvm::ModuleFlagMergeBehavior::Error,
470            "Virtual Function Elim",
471            1,
472        );
473    }
474
475    // Set module flag to enable Windows EHCont Guard (/guard:ehcont).
476    if sess.opts.unstable_opts.ehcont_guard {
477        llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "ehcontguard", 1);
478    }
479
480    match sess.opts.unstable_opts.function_return {
481        FunctionReturn::Keep => {}
482        FunctionReturn::ThunkExtern => {
483            llvm::add_module_flag_u32(
484                llmod,
485                llvm::ModuleFlagMergeBehavior::Override,
486                "function_return_thunk_extern",
487                1,
488            );
489        }
490    }
491
492    let fp = attributes::frame_pointer(sess);
493    if fp != FramePointer::MayOmit {
494        llvm::add_module_flag_u32(
495            llmod,
496            llvm::ModuleFlagMergeBehavior::Max,
497            "frame-pointer",
498            match fp {
499                FramePointer::Always => llvm::FramePointerKind::All as u32,
500                FramePointer::NonLeaf => llvm::FramePointerKind::NonLeaf as u32,
501                FramePointer::MayOmit => llvm::FramePointerKind::None as u32,
502            },
503        );
504    }
505
506    if sess.opts.unstable_opts.indirect_branch_cs_prefix {
507        llvm::add_module_flag_u32(
508            llmod,
509            llvm::ModuleFlagMergeBehavior::Override,
510            "indirect_branch_cs_prefix",
511            1,
512        );
513    }
514
515    match (sess.opts.unstable_opts.small_data_threshold, sess.target.small_data_threshold_support())
516    {
517        // Set up the small-data optimization limit for architectures that use
518        // an LLVM module flag to control this.
519        (Some(threshold), SmallDataThresholdSupport::LlvmModuleFlag(flag)) => {
520            llvm::add_module_flag_u32(
521                llmod,
522                llvm::ModuleFlagMergeBehavior::Error,
523                &flag,
524                threshold as u32,
525            );
526        }
527        _ => (),
528    };
529
530    // Insert `llvm.ident` metadata.
531    //
532    // On the wasm targets it will get hooked up to the "producer" sections
533    // `processed-by` information.
534    #[allow(clippy::option_env_unwrap)]
535    let rustc_producer =
536        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("rustc version {0}",
                ::core::option::Option::Some("1.101.0-nightly (12433c307 2026-10-24)").expect("CFG_VERSION")))
    })format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"));
537
538    let name_metadata = cx.create_metadata(rustc_producer.as_bytes());
539    cx.module_add_named_metadata_node(llmod, c"llvm.ident", &[name_metadata]);
540
541    // Emit the target-abi module flag for LoongArch and RISC-V to pass the ABI to LTO.
542    let llvm_abiname = &sess.target.options.llvm_abiname;
543    if #[allow(non_exhaustive_omitted_patterns)] match sess.target.arch {
    Arch::LoongArch32 | Arch::LoongArch64 | Arch::RiscV32 | Arch::RiscV64 =>
        true,
    _ => false,
}matches!(
544        sess.target.arch,
545        Arch::LoongArch32 | Arch::LoongArch64 | Arch::RiscV32 | Arch::RiscV64
546    ) {
547        llvm::add_module_flag_str(
548            llmod,
549            llvm::ModuleFlagMergeBehavior::Error,
550            "target-abi",
551            llvm_abiname.desc(),
552        );
553    }
554
555    if llvm_version >= (24, 0, 0)
556        && let Some(floatabi) = sess.target.llvm_floatabi
557    {
558        llvm::add_module_flag_str(
559            llmod,
560            llvm::ModuleFlagMergeBehavior::Error,
561            "float-abi",
562            floatabi.desc(),
563        );
564    }
565
566    if llvm_version >= (24, 0, 0) {
567        if sess.target.singlethread(&sess.internal_target_features) {
568            llvm::add_module_flag_str(
569                llmod,
570                llvm::ModuleFlagMergeBehavior::Error,
571                "thread-model",
572                "single",
573            );
574        }
575        if wants_wasm_eh(&sess.target) {
576            llvm::add_module_flag_str(
577                llmod,
578                llvm::ModuleFlagMergeBehavior::Error,
579                "exception-model",
580                "wasm",
581            );
582        }
583    }
584
585    // Add module flags specified via -Z llvm_module_flag
586    for (key, value, merge_behavior) in &sess.opts.unstable_opts.llvm_module_flag {
587        let merge_behavior = match merge_behavior.as_str() {
588            "error" => llvm::ModuleFlagMergeBehavior::Error,
589            "warning" => llvm::ModuleFlagMergeBehavior::Warning,
590            "require" => llvm::ModuleFlagMergeBehavior::Require,
591            "override" => llvm::ModuleFlagMergeBehavior::Override,
592            "append" => llvm::ModuleFlagMergeBehavior::Append,
593            "appendunique" => llvm::ModuleFlagMergeBehavior::AppendUnique,
594            "max" => llvm::ModuleFlagMergeBehavior::Max,
595            "min" => llvm::ModuleFlagMergeBehavior::Min,
596            // We already checked this during option parsing
597            _ => ::core::panicking::unreachable_default_msg()unreachable!(),
598        };
599        llvm::add_module_flag_u32(llmod, merge_behavior, key, *value);
600    }
601}
602
603impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
604    pub(crate) fn new(
605        tcx: TyCtxt<'tcx>,
606        codegen_unit: &'tcx CodegenUnit<'tcx>,
607        module_refs: ModuleRefs<'ll>,
608        bitcode_needed: bool,
609    ) -> Self {
610        // An interesting part of Windows which MSVC forces our hand on (and
611        // apparently MinGW didn't) is the usage of `dllimport` and `dllexport`
612        // attributes in LLVM IR as well as native dependencies (in C these
613        // correspond to `__declspec(dllimport)`).
614        //
615        // LD (BFD) in MinGW mode can often correctly guess `dllexport` but
616        // relying on that can result in issues like #50176.
617        // LLD won't support that and expects symbols with proper attributes.
618        // Because of that we make MinGW target emit dllexport just like MSVC.
619        // When it comes to dllimport we use it for constants but for functions
620        // rely on the linker to do the right thing. Opposed to dllexport this
621        // task is easy for them (both LD and LLD) and allows us to easily use
622        // symbols from static libraries in shared libraries.
623        //
624        // Whenever a dynamic library is built on Windows it must have its public
625        // interface specified by functions tagged with `dllexport` or otherwise
626        // they're not available to be linked against. This poses a few problems
627        // for the compiler, some of which are somewhat fundamental, but we use
628        // the `use_dll_storage_attrs` variable below to attach the `dllexport`
629        // attribute to all LLVM functions that are exported e.g., they're
630        // already tagged with external linkage). This is suboptimal for a few
631        // reasons:
632        //
633        // * If an object file will never be included in a dynamic library,
634        //   there's no need to attach the dllexport attribute. Most object
635        //   files in Rust are not destined to become part of a dll as binaries
636        //   are statically linked by default.
637        // * If the compiler is emitting both an rlib and a dylib, the same
638        //   source object file is currently used but with MSVC this may be less
639        //   feasible. The compiler may be able to get around this, but it may
640        //   involve some invasive changes to deal with this.
641        //
642        // The flip side of this situation is that whenever you link to a dll and
643        // you import a function from it, the import should be tagged with
644        // `dllimport`. At this time, however, the compiler does not emit
645        // `dllimport` for any declarations other than constants (where it is
646        // required), which is again suboptimal for even more reasons!
647        //
648        // * Calling a function imported from another dll without using
649        //   `dllimport` causes the linker/compiler to have extra overhead (one
650        //   `jmp` instruction on x86) when calling the function.
651        // * The same object file may be used in different circumstances, so a
652        //   function may be imported from a dll if the object is linked into a
653        //   dll, but it may be just linked against if linked into an rlib.
654        // * The compiler has no knowledge about whether native functions should
655        //   be tagged dllimport or not.
656        //
657        // For now the compiler takes the perf hit (I do not have any numbers to
658        // this effect) by marking very little as `dllimport` and praying the
659        // linker will take care of everything. Fixing this problem will likely
660        // require adding a few attributes to Rust itself (feature gated at the
661        // start) and then strongly recommending static linkage on Windows!
662        let use_dll_storage_attrs = tcx.sess.target.is_like_windows;
663
664        let tls_model = to_llvm_tls_model(tcx.sess.tls_model());
665
666        let ModuleRefs { llcx, llmod, .. } = module_refs;
667
668        let coverage_cx =
669            tcx.sess.instrument_coverage().then(coverageinfo::CguCoverageContext::new);
670
671        let dbg_cx = if tcx.sess.opts.debuginfo != DebugInfo::None {
672            let dctx = debuginfo::CodegenUnitDebugContext::new(llmod, tcx.sess);
673            debuginfo::metadata::build_compile_unit_di_node(
674                tcx,
675                codegen_unit.name().as_str(),
676                &dctx,
677            );
678            Some(dctx)
679        } else {
680            None
681        };
682
683        // FIXME: This parses the ignorelist files for each CGU, which adds a performance overhead.
684        // Clang parses it once per frontend invocation. LLVM's `SpecialCaseList::inSection`
685        // mutates an internal `LazyInit` cache and is not thread-safe. We either need to wrap
686        // the queries in a lock or wait for LLVM to expose a thread-safe way to query it.
687        let sanitizer_ignorelist = if !tcx.sess.opts.unstable_opts.sanitizer_ignorelist.is_empty() {
688            for path in &tcx.sess.opts.unstable_opts.sanitizer_ignorelist {
689                let _ = tcx.sess.source_map().load_file(std::path::Path::new(path));
690            }
691            match SanitizerIgnoreList::new(&tcx.sess.opts.unstable_opts.sanitizer_ignorelist) {
692                Ok(list) => Some(list),
693                Err(err) => {
694                    tcx.dcx().fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to parse sanitizer ignorelist: {0}",
                err))
    })format!("failed to parse sanitizer ignorelist: {}", err));
695                }
696            }
697        } else {
698            None
699        };
700
701        GenericCx(
702            FullCx {
703                tcx,
704                bitcode_needed,
705                scx: SimpleCx::new(llmod, llcx, tcx.data_layout.pointer_size()),
706                use_dll_storage_attrs,
707                tls_model,
708                codegen_unit,
709                instances: Default::default(),
710                intrinsic_instances: Default::default(),
711                vtables: Default::default(),
712                const_str_cache: Default::default(),
713                const_globals: Default::default(),
714                statics_to_rauw: RefCell::new(Vec::new()),
715                used_statics: Vec::new(),
716                compiler_used_statics: Default::default(),
717                type_lowering: Default::default(),
718                scalar_lltypes: Default::default(),
719                coverage_cx,
720                dbg_cx,
721                sanitizer_ignorelist,
722                eh_personality: Cell::new(None),
723                rust_try_fn: Cell::new(None),
724                intrinsics: Default::default(),
725                local_gen_sym_counter: Cell::new(0),
726                global_gen_sym_counter: Cell::new(0),
727                renamed_statics: Default::default(),
728                objc_class_t: Cell::new(None),
729                objc_classrefs: Default::default(),
730                objc_selrefs: Default::default(),
731                offload_globals: Default::default(),
732                offload_kernel_cache: Default::default(),
733            },
734            PhantomData,
735        )
736    }
737
738    pub(crate) fn statics_to_rauw(&self) -> &RefCell<Vec<(&'ll Value, &'ll Value)>> {
739        &self.statics_to_rauw
740    }
741
742    /// Extra state that is only available when coverage instrumentation is enabled.
743    #[inline]
744    #[track_caller]
745    pub(crate) fn coverage_cx(&self) -> &coverageinfo::CguCoverageContext<'ll, 'tcx> {
746        self.coverage_cx.as_ref().expect("only called when coverage instrumentation is enabled")
747    }
748
749    pub(crate) fn create_used_variable_impl(&self, name: &'static CStr, values: &[&'ll Value]) {
750        let array = self.const_array(self.type_ptr(), values);
751
752        let g = llvm::add_global(self.llmod, self.val_ty(array), name);
753        llvm::set_initializer(g, array);
754        llvm::set_linkage(g, llvm::Linkage::AppendingLinkage);
755        llvm::set_section(g, c"llvm.metadata");
756    }
757
758    /// The Objective-C ABI that is used.
759    ///
760    /// This corresponds to the `-fobjc-abi-version=` flag in Clang / GCC.
761    pub(crate) fn objc_abi_version(&self) -> u32 {
762        if !self.tcx.sess.target.is_like_darwin {
    ::core::panicking::panic("assertion failed: self.tcx.sess.target.is_like_darwin")
};assert!(self.tcx.sess.target.is_like_darwin);
763        if self.tcx.sess.target.arch == Arch::X86 && self.tcx.sess.target.os == Os::MacOs {
764            // 32-bit x86 macOS uses ABI version 1 (a.k.a. the "fragile ABI").
765            1
766        } else {
767            // All other Darwin-like targets we support use ABI version 2
768            // (a.k.a the "non-fragile ABI").
769            2
770        }
771    }
772
773    pub(crate) fn add_ptrauth_elf_got_flag(&self) {
774        llvm::add_module_flag_u32(
775            self.llmod,
776            llvm::ModuleFlagMergeBehavior::Error,
777            "ptrauth-elf-got",
778            1,
779        );
780    }
781
782    pub(crate) fn add_ptrauth_sign_personality_flag(&self) {
783        llvm::add_module_flag_u32(
784            self.llmod,
785            llvm::ModuleFlagMergeBehavior::Error,
786            "ptrauth-sign-personality",
787            1,
788        );
789    }
790
791    pub(crate) fn add_ptrauth_pauthabi_version_and_platform_flags(
792        &self,
793        aarch64_elf_pauthabi_version: u32,
794    ) {
795        // NOTE: This must correspond to llvm's AARCH64_PAUTH_PLATFORM_LLVM_LINUX, as defined in
796        // <llvm_root>/llvm/include/llvm/BinaryFormat/ELF.h.
797        // FIXME (jchlanda) extend possible values once we start supporting other platforms (for
798        // example: AARCH64_PAUTH_PLATFORM_BAREMETAL = 0x1);
799        const AARCH64_PAUTH_PLATFORM_LLVM_LINUX: u32 = 0x10000002;
800        llvm::add_module_flag_u32(
801            self.llmod,
802            llvm::ModuleFlagMergeBehavior::Error,
803            "aarch64-elf-pauthabi-platform",
804            AARCH64_PAUTH_PLATFORM_LLVM_LINUX,
805        );
806        llvm::add_module_flag_u32(
807            self.llmod,
808            llvm::ModuleFlagMergeBehavior::Error,
809            "aarch64-elf-pauthabi-version",
810            aarch64_elf_pauthabi_version,
811        );
812    }
813
814    // We do our best here to match what Clang does when compiling Objective-C natively.
815    // See Clang's `CGObjCCommonMac::EmitImageInfo`:
816    // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5085
817    pub(crate) fn add_objc_module_flags(&self) {
818        let abi_version = self.objc_abi_version();
819
820        llvm::add_module_flag_u32(
821            self.llmod,
822            llvm::ModuleFlagMergeBehavior::Error,
823            "Objective-C Version",
824            abi_version,
825        );
826
827        llvm::add_module_flag_u32(
828            self.llmod,
829            llvm::ModuleFlagMergeBehavior::Error,
830            "Objective-C Image Info Version",
831            0,
832        );
833
834        llvm::add_module_flag_str(
835            self.llmod,
836            llvm::ModuleFlagMergeBehavior::Error,
837            "Objective-C Image Info Section",
838            match abi_version {
839                1 => "__OBJC,__image_info,regular",
840                2 => "__DATA,__objc_imageinfo,regular,no_dead_strip",
841                _ => ::core::panicking::unreachable_default_msg()unreachable!(),
842            },
843        );
844
845        if self.tcx.sess.target.env == Env::Sim {
846            llvm::add_module_flag_u32(
847                self.llmod,
848                llvm::ModuleFlagMergeBehavior::Error,
849                "Objective-C Is Simulated",
850                1 << 5,
851            );
852        }
853
854        llvm::add_module_flag_u32(
855            self.llmod,
856            llvm::ModuleFlagMergeBehavior::Error,
857            "Objective-C Class Properties",
858            1 << 6,
859        );
860    }
861
862    pub(crate) fn is_sanitizer_type_ignored(
863        &self,
864        sanitizer: &std::ffi::CStr,
865        fn_abi: &rustc_target::callconv::FnAbi<'tcx, Ty<'tcx>>,
866    ) -> bool {
867        self.sanitizer_ignorelist.as_ref().is_some_and(|ignorelist| {
868            let type_name = typename_for_ignore_list(self.tcx, fn_abi);
869            ignorelist.contains_prefix(sanitizer, c"type", &type_name)
870        })
871    }
872}
873impl<'ll> SimpleCx<'ll> {
874    pub(crate) fn get_type_of_global(&self, val: &'ll Value) -> &'ll Type {
875        unsafe { llvm::LLVMGlobalGetValueType(val) }
876    }
877    pub(crate) fn val_ty(&self, v: &'ll Value) -> &'ll Type {
878        common::val_ty(v)
879    }
880}
881impl<'ll> SimpleCx<'ll> {
882    pub(crate) fn new(
883        llmod: &'ll llvm::Module,
884        llcx: &'ll llvm::Context,
885        pointer_size: Size,
886    ) -> Self {
887        let isize_ty = llvm::LLVMIntTypeInContext(llcx, pointer_size.bits() as c_uint);
888        Self(SCx { llmod, llcx, isize_ty }, PhantomData)
889    }
890}
891
892impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
893    pub(crate) fn get_metadata_value(&self, metadata: &'ll Metadata) -> &'ll Value {
894        llvm::LLVMMetadataAsValue(self.llcx(), metadata)
895    }
896
897    pub(crate) fn get_const_int(&self, ty: &'ll Type, val: u64) -> &'ll Value {
898        unsafe { llvm::LLVMConstInt(ty, val, llvm::FALSE) }
899    }
900
901    pub(crate) fn get_const_i64(&self, n: u64) -> &'ll Value {
902        self.get_const_int(self.type_i64(), n)
903    }
904
905    pub(crate) fn get_const_i32(&self, n: u64) -> &'ll Value {
906        self.get_const_int(self.type_i32(), n)
907    }
908
909    pub(crate) fn get_const_i16(&self, n: u64) -> &'ll Value {
910        self.get_const_int(self.type_i16(), n)
911    }
912
913    pub(crate) fn get_const_i8(&self, n: u64) -> &'ll Value {
914        self.get_const_int(self.type_i8(), n)
915    }
916
917    pub(crate) fn get_md_kind_id(&self, name: &str) -> llvm::MetadataKindId {
918        unsafe { llvm::LLVMGetMDKindIDInContext(self.llcx(), name.as_ptr(), name.len() as c_uint) }
919    }
920
921    pub(crate) fn create_metadata(&self, name: &[u8]) -> &'ll Metadata {
922        unsafe { llvm::LLVMMDStringInContext2(self.llcx(), name.as_ptr(), name.len()) }
923    }
924
925    pub(crate) fn get_functions(&self) -> Vec<&'ll Value> {
926        let mut functions = ::alloc::vec::Vec::new()vec![];
927        let mut func = unsafe { llvm::LLVMGetFirstFunction(self.llmod()) };
928        while let Some(f) = func {
929            functions.push(f);
930            func = unsafe { llvm::LLVMGetNextFunction(f) }
931        }
932        functions
933    }
934}
935
936impl<'ll, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
937    fn vtables(
938        &self,
939    ) -> &RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>> {
940        &self.vtables
941    }
942
943    fn apply_vcall_visibility_metadata(
944        &self,
945        ty: Ty<'tcx>,
946        poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
947        vtable: &'ll Value,
948    ) {
949        apply_vcall_visibility_metadata(self, ty, poly_trait_ref, vtable);
950    }
951
952    fn get_fn(&self, instance: Instance<'tcx>) -> &'ll Value {
953        get_fn(self, instance)
954    }
955
956    fn get_fn_addr(
957        &self,
958        instance: Instance<'tcx>,
959        pointer_auth_schema: Option<&PointerAuthSchema>,
960    ) -> &'ll Value {
961        // When pointer authentication metadata is provided, `get_fn_addr` will
962        // attempt to sign the pointer using LLVM's `ConstPtrAuth` constant
963        // expression.
964        //
965        // FIXME(jchlanda) Currently, all function addresses requested from
966        // within LLVM codegen are signed. This behavior is too broad, resulting
967        // in the logic being applied to function values, not just pointers
968        // (addresses).
969        //
970        // See the discussion in the rust-lang issue:
971        // <https://github.com/rust-lang/rust/issues/152532>, and comment in
972        // builder's `ptrauth_operand_bundle`.
973        let llfn = get_fn(self, instance);
974        match pointer_auth_schema {
975            Some(schema) => common::maybe_sign_fn_ptr(self, instance, llfn, schema),
976            None => llfn,
977        }
978    }
979
980    fn eh_personality(&self) -> &'ll Value {
981        // The exception handling personality function.
982        //
983        // If our compilation unit has the `eh_personality` lang item somewhere
984        // within it, then we just need to codegen that. Otherwise, we're
985        // building an rlib which will depend on some upstream implementation of
986        // this function, so we just codegen a generic reference to it. We don't
987        // specify any of the types for the function, we just make it a symbol
988        // that LLVM can later use.
989        //
990        // Note that MSVC is a little special here in that we don't use the
991        // `eh_personality` lang item at all. Currently LLVM has support for
992        // both Dwarf and SEH unwind mechanisms for MSVC targets and uses the
993        // *name of the personality function* to decide what kind of unwind side
994        // tables/landing pads to emit. It looks like Dwarf is used by default,
995        // injecting a dependency on the `_Unwind_Resume` symbol for resuming
996        // an "exception", but for MSVC we want to force SEH. This means that we
997        // can't actually have the personality function be our standard
998        // `rust_eh_personality` function, but rather we wired it up to the
999        // CRT's custom personality function, which forces LLVM to consider
1000        // landing pads as "landing pads for SEH".
1001        if let Some(llpersonality) = self.eh_personality.get() {
1002            return llpersonality;
1003        }
1004
1005        let name = if wants_msvc_seh(&self.sess().target) {
1006            Some("__CxxFrameHandler3")
1007        } else if wants_wasm_eh(&self.sess().target) {
1008            // LLVM specifically tests for the name of the personality function
1009            // There is no need for this function to exist anywhere, it will
1010            // not be called. However, its name has to be "__gxx_wasm_personality_v0"
1011            // for native wasm exceptions.
1012            Some("__gxx_wasm_personality_v0")
1013        } else {
1014            None
1015        };
1016
1017        let tcx = self.tcx;
1018        let llfn = match tcx.lang_items().eh_personality() {
1019            Some(def_id) if name.is_none() => self.get_fn_addr(
1020                ty::Instance::expect_resolve(
1021                    tcx,
1022                    self.typing_env(),
1023                    def_id,
1024                    ty::List::empty(),
1025                    DUMMY_SP,
1026                ),
1027                tcx.sess.pointer_authentication_functions(),
1028            ),
1029            _ => {
1030                let mangled_symbol;
1031                let name = match name {
1032                    Some(name) => name,
1033                    None => {
1034                        mangled_symbol = rustc_symbol_mangling::eh_personality_symbol(tcx);
1035                        mangled_symbol.as_str()
1036                    }
1037                };
1038                if let Some(llfn) = self.get_declared_value(name) {
1039                    llfn
1040                } else {
1041                    let fty = self.type_variadic_func(&[], self.type_i32());
1042                    let llfn = self.declare_cfn(name, llvm::UnnamedAddr::Global, fty);
1043                    let target_cpu = attributes::target_cpu_attr(self, self.sess());
1044                    attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[target_cpu]);
1045                    llfn
1046                }
1047            }
1048        };
1049        self.eh_personality.set(Some(llfn));
1050        llfn
1051    }
1052
1053    fn sess(&self) -> &Session {
1054        self.tcx.sess
1055    }
1056
1057    fn set_frame_pointer_type(&self, llfn: &'ll Value) {
1058        if let Some(attr) = attributes::frame_pointer_type_attr(self, self.sess()) {
1059            attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[attr]);
1060        }
1061    }
1062
1063    fn apply_target_cpu_attr(&self, llfn: &'ll Value) {
1064        let mut attrs = SmallVec::<[_; 2]>::new();
1065        attrs.push(attributes::target_cpu_attr(self, self.sess()));
1066        attrs.extend(attributes::tune_cpu_attr(self, self.sess()));
1067        attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &attrs);
1068    }
1069
1070    fn declare_c_main(&self, fn_type: Self::Type) -> Option<Self::Function> {
1071        let entry_name = self.sess().target.entry_name.as_ref();
1072        if self.get_declared_value(entry_name).is_none() {
1073            let llfn = self.declare_entry_fn(
1074                entry_name,
1075                to_llvm_calling_convention(self.sess(), self.sess().target.entry_abi),
1076                llvm::UnnamedAddr::Global,
1077                fn_type,
1078            );
1079            attributes::apply_to_llfn(
1080                llfn,
1081                llvm::AttributePlace::Function,
1082                attributes::target_features_attr(self, self.tcx, ::alloc::vec::Vec::new()vec![]).as_slice(),
1083            );
1084            Some(llfn)
1085        } else {
1086            // If the symbol already exists, it is an error: for example, the user wrote
1087            // #[no_mangle] extern "C" fn main(..) {..}
1088            None
1089        }
1090    }
1091
1092    fn intrinsic_call_expects_place_always(&self, name: Symbol) -> bool {
1093        #[allow(non_exhaustive_omitted_patterns)] match name {
    sym::black_box => true,
    _ => false,
}matches!(name, sym::black_box)
1094    }
1095}
1096
1097impl<'ll> CodegenCx<'ll, '_> {
1098    pub(crate) fn get_intrinsic(
1099        &self,
1100        base_name: Cow<'static, str>,
1101        type_params: &[&'ll Type],
1102    ) -> (&'ll Type, &'ll Value) {
1103        *self
1104            .intrinsics
1105            .borrow_mut()
1106            .entry((base_name, SmallVec::from_slice(type_params)))
1107            .or_insert_with_key(|(base_name, type_params)| {
1108                self.declare_intrinsic(base_name, type_params)
1109            })
1110    }
1111
1112    fn declare_intrinsic(
1113        &self,
1114        base_name: &str,
1115        type_params: &[&'ll Type],
1116    ) -> (&'ll Type, &'ll Value) {
1117        match base_name {
1118            // This isn't an "LLVM intrinsic", but LLVM's optimization passes
1119            // recognize it like one (including turning it into `bcmp` sometimes)
1120            // and we use it to implement intrinsics like `raw_eq` and `compare_bytes`
1121            "memcmp" => {
1122                let fn_ty = self.type_func(
1123                    &[self.type_ptr(), self.type_ptr(), self.type_isize()],
1124                    self.type_int(),
1125                );
1126                let f = self.declare_cfn("memcmp", llvm::UnnamedAddr::No, fn_ty);
1127
1128                (fn_ty, f)
1129            }
1130            // Experimental retag intrinsics.
1131            // This form is used to retag a pointer that has already been stored in a register. It receives
1132            // the pointer and returns an alias with the same address, but different provenance.
1133            "__rust_retag_reg" => {
1134                let fn_ty = self.type_func(type_params, self.type_ptr());
1135                let llfn = self.declare_cfn(base_name, llvm::UnnamedAddr::No, fn_ty);
1136                let nounwind = llvm::AttributeKind::NoUnwind.create_attr(self.llcx);
1137                attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[nounwind]);
1138                (fn_ty, llfn)
1139            }
1140            // This form is used to retag a pointer that is stored in another place. It receives a pointer to the
1141            // place and returns `void`. This communicates the indirection  without requiring an explicit load and
1142            // store. If we used the `reg` form instead, then we would need to load the place, retag it, and then
1143            // store the result back, which would be undefined behavior for `readonly` places.
1144            "__rust_retag_mem" => {
1145                let fn_ty = self.type_func(type_params, self.type_void());
1146                let llfn = self.declare_cfn(base_name, llvm::UnnamedAddr::No, fn_ty);
1147                let nounwind = llvm::AttributeKind::NoUnwind.create_attr(self.llcx);
1148                attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[nounwind]);
1149                (fn_ty, llfn)
1150            }
1151            _ => {
1152                let intrinsic = llvm::Intrinsic::lookup(base_name.as_bytes())
1153                    .unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
    format_args!("Unknown intrinsic: `{0}`", base_name), Location::caller())bug!("Unknown intrinsic: `{base_name}`"));
1154                let f = intrinsic.get_declaration(self.llmod, &type_params);
1155                (self.get_type_of_global(f), f)
1156            }
1157        }
1158    }
1159}
1160
1161impl CodegenCx<'_, '_> {
1162    /// Generates a new symbol name with the given prefix. This symbol name must
1163    /// only be used for definitions with `internal` or `private` linkage.
1164    pub(crate) fn generate_local_symbol_name(&self, prefix: &str) -> String {
1165        let idx = self.local_gen_sym_counter.get();
1166        self.local_gen_sym_counter.set(idx + 1);
1167        // Include a '.' character, so there can be no accidental conflicts with
1168        // user defined names
1169        let mut name = String::with_capacity(prefix.len() + 6);
1170        name.push_str(prefix);
1171        name.push('.');
1172        name.push_str(&(idx as u64).to_base(ALPHANUMERIC_ONLY));
1173        name
1174    }
1175
1176    /// Generates a new global symbol name with the given prefix.
1177    pub(crate) fn generate_global_symbol_name(&self) -> String {
1178        let idx = self.global_gen_sym_counter.get();
1179        self.global_gen_sym_counter.set(idx + 1);
1180
1181        let sym = self.codegen_unit.symbol_name();
1182        let prefix = sym.as_str();
1183        let mut name = String::with_capacity(prefix.len() + 6);
1184        name.push_str(prefix);
1185        name.push('.');
1186        name.push_str(&(idx as u64).to_base(ALPHANUMERIC_ONLY));
1187        name
1188    }
1189}
1190
1191impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
1192    /// Wrapper for `LLVMMDNodeInContext2`, i.e. `llvm::MDNode::get`.
1193    pub(crate) fn md_node_in_context(&self, md_list: &[&'ll Metadata]) -> &'ll Metadata {
1194        unsafe { llvm::LLVMMDNodeInContext2(self.llcx(), md_list.as_ptr(), md_list.len()) }
1195    }
1196
1197    /// A wrapper for [`llvm::LLVMSetMetadata`], but it takes `Metadata` as a parameter instead of `Value`.
1198    pub(crate) fn set_metadata<'a>(
1199        &self,
1200        val: &'a Value,
1201        kind_id: MetadataKindId,
1202        md: &'ll Metadata,
1203    ) {
1204        let node = self.get_metadata_value(md);
1205        llvm::LLVMSetMetadata(val, kind_id, node);
1206    }
1207
1208    /// Helper method for the sequence of calls:
1209    /// - `LLVMMDNodeInContext2` (to create an `llvm::MDNode` from a list of metadata)
1210    /// - `LLVMMetadataAsValue` (to adapt that node to an `llvm::Value`)
1211    /// - `LLVMSetMetadata` (to set that node as metadata of `kind_id` for `instruction`)
1212    pub(crate) fn set_metadata_node(
1213        &self,
1214        instruction: &'ll Value,
1215        kind_id: MetadataKindId,
1216        md_list: &[&'ll Metadata],
1217    ) -> &'ll Metadata {
1218        let md = self.md_node_in_context(md_list);
1219        self.set_metadata(instruction, kind_id, md);
1220        md
1221    }
1222
1223    /// Helper method for the sequence of calls:
1224    /// - `LLVMMDNodeInContext2` (to create an `llvm::MDNode` from a list of metadata)
1225    /// - `LLVMMetadataAsValue` (to adapt that node to an `llvm::Value`)
1226    /// - `LLVMAddNamedMetadataOperand` (to set that node as metadata of `kind_name` for `module`)
1227    pub(crate) fn module_add_named_metadata_node(
1228        &self,
1229        module: &'ll Module,
1230        kind_name: &CStr,
1231        md_list: &[&'ll Metadata],
1232    ) {
1233        let md = self.md_node_in_context(md_list);
1234        let md_as_val = self.get_metadata_value(md);
1235        unsafe { llvm::LLVMAddNamedMetadataOperand(module, kind_name.as_ptr(), md_as_val) };
1236    }
1237
1238    /// Helper method for the sequence of calls:
1239    /// - `LLVMMDNodeInContext2` (to create an `llvm::MDNode` from a list of metadata)
1240    /// - `LLVMGlobalAddMetadata` (to set that node as metadata of `kind_id` for `global`)
1241    pub(crate) fn global_add_metadata_node(
1242        &self,
1243        global: &'ll Value,
1244        kind_id: MetadataKindId,
1245        md_list: &[&'ll Metadata],
1246    ) {
1247        let md = self.md_node_in_context(md_list);
1248        unsafe { llvm::LLVMGlobalAddMetadata(global, kind_id, md) };
1249    }
1250
1251    /// Helper method for the sequence of calls:
1252    /// - `LLVMMDNodeInContext2` (to create an `llvm::MDNode` from a list of metadata)
1253    /// - `LLVMGlobalSetMetadata` (to set that node as metadata of `kind_id` for `global`)
1254    pub(crate) fn global_set_metadata_node(
1255        &self,
1256        global: &'ll Value,
1257        kind_id: MetadataKindId,
1258        md_list: &[&'ll Metadata],
1259    ) {
1260        let md = self.md_node_in_context(md_list);
1261        unsafe { llvm::LLVMGlobalSetMetadata(global, kind_id, md) };
1262    }
1263}
1264
1265impl HasDataLayout for CodegenCx<'_, '_> {
1266    #[inline]
1267    fn data_layout(&self) -> &TargetDataLayout {
1268        &self.tcx.data_layout
1269    }
1270}
1271
1272impl HasTargetSpec for CodegenCx<'_, '_> {
1273    #[inline]
1274    fn target_spec(&self) -> &Target {
1275        &self.tcx.sess.target
1276    }
1277}
1278
1279impl<'tcx> ty::layout::HasTyCtxt<'tcx> for CodegenCx<'_, 'tcx> {
1280    #[inline]
1281    fn tcx(&self) -> TyCtxt<'tcx> {
1282        self.tcx
1283    }
1284}
1285
1286impl<'tcx, 'll> HasTypingEnv<'tcx> for CodegenCx<'ll, 'tcx> {
1287    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
1288        ty::TypingEnv::fully_monomorphized()
1289    }
1290}
1291
1292impl<'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
1293    #[inline]
1294    fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
1295        if let LayoutError::SizeOverflow(_)
1296        | LayoutError::ReferencesError(_)
1297        | LayoutError::InvalidSimd { .. } = err
1298        {
1299            self.tcx.dcx().span_fatal(span, err.to_string())
1300        } else {
1301            self.tcx.dcx().emit_fatal(ssa_errors::FailedToGetLayout { span, ty, err })
1302        }
1303    }
1304}
1305
1306impl<'tcx> FnAbiOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
1307    #[inline]
1308    fn handle_fn_abi_err(
1309        &self,
1310        err: FnAbiError<'tcx>,
1311        span: Span,
1312        fn_abi_request: FnAbiRequest<'tcx>,
1313    ) -> ! {
1314        codegen_handle_fn_abi_err(self.tcx, err, span, fn_abi_request).raise_fatal()
1315    }
1316}