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