rustc_codegen_llvm/
context.rs

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