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