Skip to main content

rustc_codegen_llvm/
context.rs

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