Skip to main content

rustc_codegen_llvm/
context.rs

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