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