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