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