Skip to main content

rustc_codegen_llvm/
context.rs

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