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