rustc_codegen_llvm/
context.rs

1use std::borrow::{Borrow, Cow};
2use std::cell::{Cell, RefCell};
3use std::ffi::{CStr, c_char, c_uint};
4use std::marker::PhantomData;
5use std::ops::{Deref, DerefMut};
6use std::str;
7
8use rustc_abi::{HasDataLayout, Size, TargetDataLayout, VariantIdx};
9use rustc_codegen_ssa::back::versioned_llvm_target;
10use rustc_codegen_ssa::base::{wants_msvc_seh, wants_wasm_eh};
11use rustc_codegen_ssa::common::TypeKind;
12use rustc_codegen_ssa::errors as ssa_errors;
13use rustc_codegen_ssa::traits::*;
14use rustc_data_structures::base_n::{ALPHANUMERIC_ONLY, ToBaseN};
15use rustc_data_structures::fx::FxHashMap;
16use rustc_data_structures::small_c_str::SmallCStr;
17use rustc_hir::def_id::DefId;
18use rustc_middle::middle::codegen_fn_attrs::PatchableFunctionEntry;
19use rustc_middle::mir::mono::CodegenUnit;
20use rustc_middle::ty::layout::{
21    FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers,
22};
23use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
24use rustc_middle::{bug, span_bug};
25use rustc_session::Session;
26use rustc_session::config::{
27    BranchProtection, CFGuard, CFProtection, CrateType, DebugInfo, FunctionReturn, PAuthKey, PacRet,
28};
29use rustc_span::source_map::Spanned;
30use rustc_span::{DUMMY_SP, Span};
31use rustc_symbol_mangling::mangle_internal_symbol;
32use rustc_target::spec::{HasTargetSpec, RelocModel, SmallDataThresholdSupport, Target, TlsModel};
33use smallvec::SmallVec;
34
35use crate::back::write::to_llvm_code_model;
36use crate::callee::get_fn;
37use crate::debuginfo::metadata::apply_vcall_visibility_metadata;
38use crate::llvm::Metadata;
39use crate::type_::Type;
40use crate::value::Value;
41use crate::{attributes, common, 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
79impl<'ll, T: Borrow<SCx<'ll>>> DerefMut for GenericCx<'ll, T> {
80    #[inline]
81    fn deref_mut(&mut self) -> &mut Self::Target {
82        &mut self.0
83    }
84}
85
86pub(crate) type SimpleCx<'ll> = GenericCx<'ll, SCx<'ll>>;
87
88/// There is one `CodegenCx` per codegen unit. Each one has its own LLVM
89/// `llvm::Context` so that several codegen units may be processed in parallel.
90/// All other LLVM data structures in the `CodegenCx` are tied to that `llvm::Context`.
91pub(crate) type CodegenCx<'ll, 'tcx> = GenericCx<'ll, FullCx<'ll, 'tcx>>;
92
93pub(crate) struct FullCx<'ll, 'tcx> {
94    pub tcx: TyCtxt<'tcx>,
95    pub scx: SimpleCx<'ll>,
96    pub use_dll_storage_attrs: bool,
97    pub tls_model: llvm::ThreadLocalMode,
98
99    pub codegen_unit: &'tcx CodegenUnit<'tcx>,
100
101    /// Cache instances of monomorphic and polymorphic items
102    pub instances: RefCell<FxHashMap<Instance<'tcx>, &'ll Value>>,
103    /// Cache generated vtables
104    pub vtables: RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>>,
105    /// Cache of constant strings,
106    pub const_str_cache: RefCell<FxHashMap<String, &'ll Value>>,
107
108    /// Cache of emitted const globals (value -> global)
109    pub const_globals: RefCell<FxHashMap<&'ll Value, &'ll Value>>,
110
111    /// List of globals for static variables which need to be passed to the
112    /// LLVM function ReplaceAllUsesWith (RAUW) when codegen is complete.
113    /// (We have to make sure we don't invalidate any Values referring
114    /// to constants.)
115    pub statics_to_rauw: RefCell<Vec<(&'ll Value, &'ll Value)>>,
116
117    /// Statics that will be placed in the llvm.used variable
118    /// See <https://llvm.org/docs/LangRef.html#the-llvm-used-global-variable> for details
119    pub used_statics: Vec<&'ll Value>,
120
121    /// Statics that will be placed in the llvm.compiler.used variable
122    /// See <https://llvm.org/docs/LangRef.html#the-llvm-compiler-used-global-variable> for details
123    pub compiler_used_statics: Vec<&'ll Value>,
124
125    /// Mapping of non-scalar types to llvm types.
126    pub type_lowering: RefCell<FxHashMap<(Ty<'tcx>, Option<VariantIdx>), &'ll Type>>,
127
128    /// Mapping of scalar types to llvm types.
129    pub scalar_lltypes: RefCell<FxHashMap<Ty<'tcx>, &'ll Type>>,
130
131    /// Extra per-CGU codegen state needed when coverage instrumentation is enabled.
132    pub coverage_cx: Option<coverageinfo::CguCoverageContext<'ll, 'tcx>>,
133    pub dbg_cx: Option<debuginfo::CodegenUnitDebugContext<'ll, 'tcx>>,
134
135    eh_personality: Cell<Option<&'ll Value>>,
136    eh_catch_typeinfo: Cell<Option<&'ll Value>>,
137    pub rust_try_fn: Cell<Option<(&'ll Type, &'ll Value)>>,
138
139    intrinsics:
140        RefCell<FxHashMap<(Cow<'static, str>, SmallVec<[&'ll Type; 2]>), (&'ll Type, &'ll Value)>>,
141
142    /// A counter that is used for generating local symbol names
143    local_gen_sym_counter: Cell<usize>,
144
145    /// `codegen_static` will sometimes create a second global variable with a
146    /// different type and clear the symbol name of the original global.
147    /// `global_asm!` needs to be able to find this new global so that it can
148    /// compute the correct mangled symbol name to insert into the asm.
149    pub renamed_statics: RefCell<FxHashMap<DefId, &'ll Value>>,
150}
151
152fn to_llvm_tls_model(tls_model: TlsModel) -> llvm::ThreadLocalMode {
153    match tls_model {
154        TlsModel::GeneralDynamic => llvm::ThreadLocalMode::GeneralDynamic,
155        TlsModel::LocalDynamic => llvm::ThreadLocalMode::LocalDynamic,
156        TlsModel::InitialExec => llvm::ThreadLocalMode::InitialExec,
157        TlsModel::LocalExec => llvm::ThreadLocalMode::LocalExec,
158        TlsModel::Emulated => llvm::ThreadLocalMode::GeneralDynamic,
159    }
160}
161
162pub(crate) unsafe fn create_module<'ll>(
163    tcx: TyCtxt<'_>,
164    llcx: &'ll llvm::Context,
165    mod_name: &str,
166) -> &'ll llvm::Module {
167    let sess = tcx.sess;
168    let mod_name = SmallCStr::new(mod_name);
169    let llmod = unsafe { llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx) };
170
171    let cx = SimpleCx::new(llmod, llcx, tcx.data_layout.pointer_size());
172
173    let mut target_data_layout = sess.target.data_layout.to_string();
174    let llvm_version = llvm_util::get_version();
175
176    if llvm_version < (20, 0, 0) {
177        if sess.target.arch == "aarch64" || sess.target.arch.starts_with("arm64") {
178            // LLVM 20 defines three additional address spaces for alternate
179            // pointer kinds used in Windows.
180            // See https://github.com/llvm/llvm-project/pull/111879
181            target_data_layout =
182                target_data_layout.replace("-p270:32:32-p271:32:32-p272:64:64", "");
183        }
184        if sess.target.arch.starts_with("sparc") {
185            // LLVM 20 updates the sparc layout to correctly align 128 bit integers to 128 bit.
186            // See https://github.com/llvm/llvm-project/pull/106951
187            target_data_layout = target_data_layout.replace("-i128:128", "");
188        }
189        if sess.target.arch.starts_with("mips64") {
190            // LLVM 20 updates the mips64 layout to correctly align 128 bit integers to 128 bit.
191            // See https://github.com/llvm/llvm-project/pull/112084
192            target_data_layout = target_data_layout.replace("-i128:128", "");
193        }
194        if sess.target.arch.starts_with("powerpc64") {
195            // LLVM 20 updates the powerpc64 layout to correctly align 128 bit integers to 128 bit.
196            // See https://github.com/llvm/llvm-project/pull/118004
197            target_data_layout = target_data_layout.replace("-i128:128", "");
198        }
199        if sess.target.arch.starts_with("wasm32") || sess.target.arch.starts_with("wasm64") {
200            // LLVM 20 updates the wasm(32|64) layout to correctly align 128 bit integers to 128 bit.
201            // See https://github.com/llvm/llvm-project/pull/119204
202            target_data_layout = target_data_layout.replace("-i128:128", "");
203        }
204    }
205    if llvm_version < (21, 0, 0) {
206        if sess.target.arch == "nvptx64" {
207            // LLVM 21 updated the default layout on nvptx: https://github.com/llvm/llvm-project/pull/124961
208            target_data_layout = target_data_layout.replace("e-p6:32:32-i64", "e-i64");
209        }
210    }
211
212    // Ensure the data-layout values hardcoded remain the defaults.
213    {
214        let tm = crate::back::write::create_informational_target_machine(tcx.sess, false);
215        unsafe {
216            llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm.raw());
217        }
218
219        let llvm_data_layout = unsafe { llvm::LLVMGetDataLayoutStr(llmod) };
220        let llvm_data_layout =
221            str::from_utf8(unsafe { CStr::from_ptr(llvm_data_layout) }.to_bytes())
222                .expect("got a non-UTF8 data-layout from LLVM");
223
224        if target_data_layout != llvm_data_layout {
225            tcx.dcx().emit_err(crate::errors::MismatchedDataLayout {
226                rustc_target: sess.opts.target_triple.to_string().as_str(),
227                rustc_layout: target_data_layout.as_str(),
228                llvm_target: sess.target.llvm_target.borrow(),
229                llvm_layout: llvm_data_layout,
230            });
231        }
232    }
233
234    let data_layout = SmallCStr::new(&target_data_layout);
235    unsafe {
236        llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
237    }
238
239    let llvm_target = SmallCStr::new(&versioned_llvm_target(sess));
240    unsafe {
241        llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
242    }
243
244    let reloc_model = sess.relocation_model();
245    if matches!(reloc_model, RelocModel::Pic | RelocModel::Pie) {
246        unsafe {
247            llvm::LLVMRustSetModulePICLevel(llmod);
248        }
249        // PIE is potentially more effective than PIC, but can only be used in executables.
250        // If all our outputs are executables, then we can relax PIC to PIE.
251        if reloc_model == RelocModel::Pie
252            || tcx.crate_types().iter().all(|ty| *ty == CrateType::Executable)
253        {
254            unsafe {
255                llvm::LLVMRustSetModulePIELevel(llmod);
256            }
257        }
258    }
259
260    // Linking object files with different code models is undefined behavior
261    // because the compiler would have to generate additional code (to span
262    // longer jumps) if a larger code model is used with a smaller one.
263    //
264    // See https://reviews.llvm.org/D52322 and https://reviews.llvm.org/D52323.
265    unsafe {
266        llvm::LLVMRustSetModuleCodeModel(llmod, to_llvm_code_model(sess.code_model()));
267    }
268
269    // If skipping the PLT is enabled, we need to add some module metadata
270    // to ensure intrinsic calls don't use it.
271    if !sess.needs_plt() {
272        llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "RtLibUseGOT", 1);
273    }
274
275    // Enable canonical jump tables if CFI is enabled. (See https://reviews.llvm.org/D65629.)
276    if sess.is_sanitizer_cfi_canonical_jump_tables_enabled() && sess.is_sanitizer_cfi_enabled() {
277        llvm::add_module_flag_u32(
278            llmod,
279            llvm::ModuleFlagMergeBehavior::Override,
280            "CFI Canonical Jump Tables",
281            1,
282        );
283    }
284
285    // If we're normalizing integers with CFI, ensure LLVM generated functions do the same.
286    // See https://github.com/llvm/llvm-project/pull/104826
287    if sess.is_sanitizer_cfi_normalize_integers_enabled() {
288        llvm::add_module_flag_u32(
289            llmod,
290            llvm::ModuleFlagMergeBehavior::Override,
291            "cfi-normalize-integers",
292            1,
293        );
294    }
295
296    // Enable LTO unit splitting if specified or if CFI is enabled. (See
297    // https://reviews.llvm.org/D53891.)
298    if sess.is_split_lto_unit_enabled() || sess.is_sanitizer_cfi_enabled() {
299        llvm::add_module_flag_u32(
300            llmod,
301            llvm::ModuleFlagMergeBehavior::Override,
302            "EnableSplitLTOUnit",
303            1,
304        );
305    }
306
307    // Add "kcfi" module flag if KCFI is enabled. (See https://reviews.llvm.org/D119296.)
308    if sess.is_sanitizer_kcfi_enabled() {
309        llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Override, "kcfi", 1);
310
311        // Add "kcfi-offset" module flag with -Z patchable-function-entry (See
312        // https://reviews.llvm.org/D141172).
313        let pfe =
314            PatchableFunctionEntry::from_config(sess.opts.unstable_opts.patchable_function_entry);
315        if pfe.prefix() > 0 {
316            llvm::add_module_flag_u32(
317                llmod,
318                llvm::ModuleFlagMergeBehavior::Override,
319                "kcfi-offset",
320                pfe.prefix().into(),
321            );
322        }
323
324        // Add "kcfi-arity" module flag if KCFI arity indicator is enabled. (See
325        // https://github.com/llvm/llvm-project/pull/117121.)
326        if sess.is_sanitizer_kcfi_arity_enabled() {
327            // KCFI arity indicator requires LLVM 21.0.0 or later.
328            if llvm_version < (21, 0, 0) {
329                tcx.dcx().emit_err(crate::errors::SanitizerKcfiArityRequiresLLVM2100);
330            }
331
332            llvm::add_module_flag_u32(
333                llmod,
334                llvm::ModuleFlagMergeBehavior::Override,
335                "kcfi-arity",
336                1,
337            );
338        }
339    }
340
341    // Control Flow Guard is currently only supported by MSVC and LLVM on Windows.
342    if sess.target.is_like_msvc
343        || (sess.target.options.os == "windows"
344            && sess.target.options.env == "gnu"
345            && sess.target.options.abi == "llvm")
346    {
347        match sess.opts.cg.control_flow_guard {
348            CFGuard::Disabled => {}
349            CFGuard::NoChecks => {
350                // Set `cfguard=1` module flag to emit metadata only.
351                llvm::add_module_flag_u32(
352                    llmod,
353                    llvm::ModuleFlagMergeBehavior::Warning,
354                    "cfguard",
355                    1,
356                );
357            }
358            CFGuard::Checks => {
359                // Set `cfguard=2` module flag to emit metadata and checks.
360                llvm::add_module_flag_u32(
361                    llmod,
362                    llvm::ModuleFlagMergeBehavior::Warning,
363                    "cfguard",
364                    2,
365                );
366            }
367        }
368    }
369
370    if let Some(BranchProtection { bti, pac_ret }) = sess.opts.unstable_opts.branch_protection {
371        if sess.target.arch == "aarch64" {
372            llvm::add_module_flag_u32(
373                llmod,
374                llvm::ModuleFlagMergeBehavior::Min,
375                "branch-target-enforcement",
376                bti.into(),
377            );
378            llvm::add_module_flag_u32(
379                llmod,
380                llvm::ModuleFlagMergeBehavior::Min,
381                "sign-return-address",
382                pac_ret.is_some().into(),
383            );
384            let pac_opts = pac_ret.unwrap_or(PacRet { leaf: false, pc: false, key: PAuthKey::A });
385            llvm::add_module_flag_u32(
386                llmod,
387                llvm::ModuleFlagMergeBehavior::Min,
388                "branch-protection-pauth-lr",
389                pac_opts.pc.into(),
390            );
391            llvm::add_module_flag_u32(
392                llmod,
393                llvm::ModuleFlagMergeBehavior::Min,
394                "sign-return-address-all",
395                pac_opts.leaf.into(),
396            );
397            llvm::add_module_flag_u32(
398                llmod,
399                llvm::ModuleFlagMergeBehavior::Min,
400                "sign-return-address-with-bkey",
401                u32::from(pac_opts.key == PAuthKey::B),
402            );
403        } else {
404            bug!(
405                "branch-protection used on non-AArch64 target; \
406                  this should be checked in rustc_session."
407            );
408        }
409    }
410
411    // Pass on the control-flow protection flags to LLVM (equivalent to `-fcf-protection` in Clang).
412    if let CFProtection::Branch | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
413        llvm::add_module_flag_u32(
414            llmod,
415            llvm::ModuleFlagMergeBehavior::Override,
416            "cf-protection-branch",
417            1,
418        );
419    }
420    if let CFProtection::Return | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
421        llvm::add_module_flag_u32(
422            llmod,
423            llvm::ModuleFlagMergeBehavior::Override,
424            "cf-protection-return",
425            1,
426        );
427    }
428
429    if sess.opts.unstable_opts.virtual_function_elimination {
430        llvm::add_module_flag_u32(
431            llmod,
432            llvm::ModuleFlagMergeBehavior::Error,
433            "Virtual Function Elim",
434            1,
435        );
436    }
437
438    // Set module flag to enable Windows EHCont Guard (/guard:ehcont).
439    if sess.opts.unstable_opts.ehcont_guard {
440        llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "ehcontguard", 1);
441    }
442
443    match sess.opts.unstable_opts.function_return {
444        FunctionReturn::Keep => {}
445        FunctionReturn::ThunkExtern => {
446            llvm::add_module_flag_u32(
447                llmod,
448                llvm::ModuleFlagMergeBehavior::Override,
449                "function_return_thunk_extern",
450                1,
451            );
452        }
453    }
454
455    match (sess.opts.unstable_opts.small_data_threshold, sess.target.small_data_threshold_support())
456    {
457        // Set up the small-data optimization limit for architectures that use
458        // an LLVM module flag to control this.
459        (Some(threshold), SmallDataThresholdSupport::LlvmModuleFlag(flag)) => {
460            llvm::add_module_flag_u32(
461                llmod,
462                llvm::ModuleFlagMergeBehavior::Error,
463                &flag,
464                threshold as u32,
465            );
466        }
467        _ => (),
468    };
469
470    // Insert `llvm.ident` metadata.
471    //
472    // On the wasm targets it will get hooked up to the "producer" sections
473    // `processed-by` information.
474    #[allow(clippy::option_env_unwrap)]
475    let rustc_producer =
476        format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"));
477
478    let name_metadata = cx.create_metadata(rustc_producer.as_bytes());
479
480    unsafe {
481        llvm::LLVMAddNamedMetadataOperand(
482            llmod,
483            c"llvm.ident".as_ptr(),
484            &cx.get_metadata_value(llvm::LLVMMDNodeInContext2(llcx, &name_metadata, 1)),
485        );
486    }
487
488    // Emit RISC-V specific target-abi metadata
489    // to workaround lld as the LTO plugin not
490    // correctly setting target-abi for the LTO object
491    // FIXME: https://github.com/llvm/llvm-project/issues/50591
492    // If llvm_abiname is empty, emit nothing.
493    let llvm_abiname = &sess.target.options.llvm_abiname;
494    if matches!(sess.target.arch.as_ref(), "riscv32" | "riscv64") && !llvm_abiname.is_empty() {
495        llvm::add_module_flag_str(
496            llmod,
497            llvm::ModuleFlagMergeBehavior::Error,
498            "target-abi",
499            llvm_abiname,
500        );
501    }
502
503    // Add module flags specified via -Z llvm_module_flag
504    for (key, value, merge_behavior) in &sess.opts.unstable_opts.llvm_module_flag {
505        let merge_behavior = match merge_behavior.as_str() {
506            "error" => llvm::ModuleFlagMergeBehavior::Error,
507            "warning" => llvm::ModuleFlagMergeBehavior::Warning,
508            "require" => llvm::ModuleFlagMergeBehavior::Require,
509            "override" => llvm::ModuleFlagMergeBehavior::Override,
510            "append" => llvm::ModuleFlagMergeBehavior::Append,
511            "appendunique" => llvm::ModuleFlagMergeBehavior::AppendUnique,
512            "max" => llvm::ModuleFlagMergeBehavior::Max,
513            "min" => llvm::ModuleFlagMergeBehavior::Min,
514            // We already checked this during option parsing
515            _ => unreachable!(),
516        };
517        llvm::add_module_flag_u32(llmod, merge_behavior, key, *value);
518    }
519
520    llmod
521}
522
523impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
524    pub(crate) fn new(
525        tcx: TyCtxt<'tcx>,
526        codegen_unit: &'tcx CodegenUnit<'tcx>,
527        llvm_module: &'ll crate::ModuleLlvm,
528    ) -> Self {
529        // An interesting part of Windows which MSVC forces our hand on (and
530        // apparently MinGW didn't) is the usage of `dllimport` and `dllexport`
531        // attributes in LLVM IR as well as native dependencies (in C these
532        // correspond to `__declspec(dllimport)`).
533        //
534        // LD (BFD) in MinGW mode can often correctly guess `dllexport` but
535        // relying on that can result in issues like #50176.
536        // LLD won't support that and expects symbols with proper attributes.
537        // Because of that we make MinGW target emit dllexport just like MSVC.
538        // When it comes to dllimport we use it for constants but for functions
539        // rely on the linker to do the right thing. Opposed to dllexport this
540        // task is easy for them (both LD and LLD) and allows us to easily use
541        // symbols from static libraries in shared libraries.
542        //
543        // Whenever a dynamic library is built on Windows it must have its public
544        // interface specified by functions tagged with `dllexport` or otherwise
545        // they're not available to be linked against. This poses a few problems
546        // for the compiler, some of which are somewhat fundamental, but we use
547        // the `use_dll_storage_attrs` variable below to attach the `dllexport`
548        // attribute to all LLVM functions that are exported e.g., they're
549        // already tagged with external linkage). This is suboptimal for a few
550        // reasons:
551        //
552        // * If an object file will never be included in a dynamic library,
553        //   there's no need to attach the dllexport attribute. Most object
554        //   files in Rust are not destined to become part of a dll as binaries
555        //   are statically linked by default.
556        // * If the compiler is emitting both an rlib and a dylib, the same
557        //   source object file is currently used but with MSVC this may be less
558        //   feasible. The compiler may be able to get around this, but it may
559        //   involve some invasive changes to deal with this.
560        //
561        // The flip side of this situation is that whenever you link to a dll and
562        // you import a function from it, the import should be tagged with
563        // `dllimport`. At this time, however, the compiler does not emit
564        // `dllimport` for any declarations other than constants (where it is
565        // required), which is again suboptimal for even more reasons!
566        //
567        // * Calling a function imported from another dll without using
568        //   `dllimport` causes the linker/compiler to have extra overhead (one
569        //   `jmp` instruction on x86) when calling the function.
570        // * The same object file may be used in different circumstances, so a
571        //   function may be imported from a dll if the object is linked into a
572        //   dll, but it may be just linked against if linked into an rlib.
573        // * The compiler has no knowledge about whether native functions should
574        //   be tagged dllimport or not.
575        //
576        // For now the compiler takes the perf hit (I do not have any numbers to
577        // this effect) by marking very little as `dllimport` and praying the
578        // linker will take care of everything. Fixing this problem will likely
579        // require adding a few attributes to Rust itself (feature gated at the
580        // start) and then strongly recommending static linkage on Windows!
581        let use_dll_storage_attrs = tcx.sess.target.is_like_windows;
582
583        let tls_model = to_llvm_tls_model(tcx.sess.tls_model());
584
585        let (llcx, llmod) = (&*llvm_module.llcx, llvm_module.llmod());
586
587        let coverage_cx =
588            tcx.sess.instrument_coverage().then(coverageinfo::CguCoverageContext::new);
589
590        let dbg_cx = if tcx.sess.opts.debuginfo != DebugInfo::None {
591            let dctx = debuginfo::CodegenUnitDebugContext::new(llmod);
592            debuginfo::metadata::build_compile_unit_di_node(
593                tcx,
594                codegen_unit.name().as_str(),
595                &dctx,
596            );
597            Some(dctx)
598        } else {
599            None
600        };
601
602        GenericCx(
603            FullCx {
604                tcx,
605                scx: SimpleCx::new(llmod, llcx, tcx.data_layout.pointer_size()),
606                use_dll_storage_attrs,
607                tls_model,
608                codegen_unit,
609                instances: Default::default(),
610                vtables: Default::default(),
611                const_str_cache: Default::default(),
612                const_globals: Default::default(),
613                statics_to_rauw: RefCell::new(Vec::new()),
614                used_statics: Vec::new(),
615                compiler_used_statics: Vec::new(),
616                type_lowering: Default::default(),
617                scalar_lltypes: Default::default(),
618                coverage_cx,
619                dbg_cx,
620                eh_personality: Cell::new(None),
621                eh_catch_typeinfo: Cell::new(None),
622                rust_try_fn: Cell::new(None),
623                intrinsics: Default::default(),
624                local_gen_sym_counter: Cell::new(0),
625                renamed_statics: Default::default(),
626            },
627            PhantomData,
628        )
629    }
630
631    pub(crate) fn statics_to_rauw(&self) -> &RefCell<Vec<(&'ll Value, &'ll Value)>> {
632        &self.statics_to_rauw
633    }
634
635    /// Extra state that is only available when coverage instrumentation is enabled.
636    #[inline]
637    #[track_caller]
638    pub(crate) fn coverage_cx(&self) -> &coverageinfo::CguCoverageContext<'ll, 'tcx> {
639        self.coverage_cx.as_ref().expect("only called when coverage instrumentation is enabled")
640    }
641
642    pub(crate) fn create_used_variable_impl(&self, name: &'static CStr, values: &[&'ll Value]) {
643        let array = self.const_array(self.type_ptr(), values);
644
645        let g = llvm::add_global(self.llmod, self.val_ty(array), name);
646        llvm::set_initializer(g, array);
647        llvm::set_linkage(g, llvm::Linkage::AppendingLinkage);
648        llvm::set_section(g, c"llvm.metadata");
649    }
650}
651impl<'ll> SimpleCx<'ll> {
652    pub(crate) fn get_return_type(&self, ty: &'ll Type) -> &'ll Type {
653        assert_eq!(self.type_kind(ty), TypeKind::Function);
654        unsafe { llvm::LLVMGetReturnType(ty) }
655    }
656    pub(crate) fn get_type_of_global(&self, val: &'ll Value) -> &'ll Type {
657        unsafe { llvm::LLVMGlobalGetValueType(val) }
658    }
659    pub(crate) fn val_ty(&self, v: &'ll Value) -> &'ll Type {
660        common::val_ty(v)
661    }
662}
663impl<'ll> SimpleCx<'ll> {
664    pub(crate) fn new(
665        llmod: &'ll llvm::Module,
666        llcx: &'ll llvm::Context,
667        pointer_size: Size,
668    ) -> Self {
669        let isize_ty = llvm::Type::ix_llcx(llcx, pointer_size.bits());
670        Self(SCx { llmod, llcx, isize_ty }, PhantomData)
671    }
672}
673
674impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
675    pub(crate) fn get_metadata_value(&self, metadata: &'ll Metadata) -> &'ll Value {
676        llvm::LLVMMetadataAsValue(self.llcx(), metadata)
677    }
678
679    pub(crate) fn get_const_int(&self, ty: &'ll Type, val: u64) -> &'ll Value {
680        unsafe { llvm::LLVMConstInt(ty, val, llvm::False) }
681    }
682
683    pub(crate) fn get_function(&self, name: &str) -> Option<&'ll Value> {
684        let name = SmallCStr::new(name);
685        unsafe { llvm::LLVMGetNamedFunction((**self).borrow().llmod, name.as_ptr()) }
686    }
687
688    pub(crate) fn get_md_kind_id(&self, name: &str) -> llvm::MetadataKindId {
689        unsafe {
690            llvm::LLVMGetMDKindIDInContext(
691                self.llcx(),
692                name.as_ptr() as *const c_char,
693                name.len() as c_uint,
694            )
695        }
696    }
697
698    pub(crate) fn create_metadata(&self, name: &[u8]) -> &'ll Metadata {
699        unsafe {
700            llvm::LLVMMDStringInContext2(self.llcx(), name.as_ptr() as *const c_char, name.len())
701        }
702    }
703
704    pub(crate) fn get_functions(&self) -> Vec<&'ll Value> {
705        let mut functions = vec![];
706        let mut func = unsafe { llvm::LLVMGetFirstFunction(self.llmod()) };
707        while let Some(f) = func {
708            functions.push(f);
709            func = unsafe { llvm::LLVMGetNextFunction(f) }
710        }
711        functions
712    }
713}
714
715impl<'ll, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
716    fn vtables(
717        &self,
718    ) -> &RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>> {
719        &self.vtables
720    }
721
722    fn apply_vcall_visibility_metadata(
723        &self,
724        ty: Ty<'tcx>,
725        poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
726        vtable: &'ll Value,
727    ) {
728        apply_vcall_visibility_metadata(self, ty, poly_trait_ref, vtable);
729    }
730
731    fn get_fn(&self, instance: Instance<'tcx>) -> &'ll Value {
732        get_fn(self, instance)
733    }
734
735    fn get_fn_addr(&self, instance: Instance<'tcx>) -> &'ll Value {
736        get_fn(self, instance)
737    }
738
739    fn eh_personality(&self) -> &'ll Value {
740        // The exception handling personality function.
741        //
742        // If our compilation unit has the `eh_personality` lang item somewhere
743        // within it, then we just need to codegen that. Otherwise, we're
744        // building an rlib which will depend on some upstream implementation of
745        // this function, so we just codegen a generic reference to it. We don't
746        // specify any of the types for the function, we just make it a symbol
747        // that LLVM can later use.
748        //
749        // Note that MSVC is a little special here in that we don't use the
750        // `eh_personality` lang item at all. Currently LLVM has support for
751        // both Dwarf and SEH unwind mechanisms for MSVC targets and uses the
752        // *name of the personality function* to decide what kind of unwind side
753        // tables/landing pads to emit. It looks like Dwarf is used by default,
754        // injecting a dependency on the `_Unwind_Resume` symbol for resuming
755        // an "exception", but for MSVC we want to force SEH. This means that we
756        // can't actually have the personality function be our standard
757        // `rust_eh_personality` function, but rather we wired it up to the
758        // CRT's custom personality function, which forces LLVM to consider
759        // landing pads as "landing pads for SEH".
760        if let Some(llpersonality) = self.eh_personality.get() {
761            return llpersonality;
762        }
763
764        let name = if wants_msvc_seh(self.sess()) {
765            Some("__CxxFrameHandler3")
766        } else if wants_wasm_eh(self.sess()) {
767            // LLVM specifically tests for the name of the personality function
768            // There is no need for this function to exist anywhere, it will
769            // not be called. However, its name has to be "__gxx_wasm_personality_v0"
770            // for native wasm exceptions.
771            Some("__gxx_wasm_personality_v0")
772        } else {
773            None
774        };
775
776        let tcx = self.tcx;
777        let llfn = match tcx.lang_items().eh_personality() {
778            Some(def_id) if name.is_none() => self.get_fn_addr(ty::Instance::expect_resolve(
779                tcx,
780                self.typing_env(),
781                def_id,
782                ty::List::empty(),
783                DUMMY_SP,
784            )),
785            _ => {
786                let name = name.unwrap_or("rust_eh_personality");
787                if let Some(llfn) = self.get_declared_value(name) {
788                    llfn
789                } else {
790                    let fty = self.type_variadic_func(&[], self.type_i32());
791                    let llfn = self.declare_cfn(name, llvm::UnnamedAddr::Global, fty);
792                    let target_cpu = attributes::target_cpu_attr(self);
793                    attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[target_cpu]);
794                    llfn
795                }
796            }
797        };
798        self.eh_personality.set(Some(llfn));
799        llfn
800    }
801
802    fn sess(&self) -> &Session {
803        self.tcx.sess
804    }
805
806    fn set_frame_pointer_type(&self, llfn: &'ll Value) {
807        if let Some(attr) = attributes::frame_pointer_type_attr(self) {
808            attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[attr]);
809        }
810    }
811
812    fn apply_target_cpu_attr(&self, llfn: &'ll Value) {
813        let mut attrs = SmallVec::<[_; 2]>::new();
814        attrs.push(attributes::target_cpu_attr(self));
815        attrs.extend(attributes::tune_cpu_attr(self));
816        attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &attrs);
817    }
818
819    fn declare_c_main(&self, fn_type: Self::Type) -> Option<Self::Function> {
820        let entry_name = self.sess().target.entry_name.as_ref();
821        if self.get_declared_value(entry_name).is_none() {
822            Some(self.declare_entry_fn(
823                entry_name,
824                llvm::CallConv::from_conv(
825                    self.sess().target.entry_abi,
826                    self.sess().target.arch.borrow(),
827                ),
828                llvm::UnnamedAddr::Global,
829                fn_type,
830            ))
831        } else {
832            // If the symbol already exists, it is an error: for example, the user wrote
833            // #[no_mangle] extern "C" fn main(..) {..}
834            None
835        }
836    }
837}
838
839impl<'ll> CodegenCx<'ll, '_> {
840    pub(crate) fn get_intrinsic(
841        &self,
842        base_name: Cow<'static, str>,
843        type_params: &[&'ll Type],
844    ) -> (&'ll Type, &'ll Value) {
845        *self
846            .intrinsics
847            .borrow_mut()
848            .entry((base_name, SmallVec::from_slice(type_params)))
849            .or_insert_with_key(|(base_name, type_params)| {
850                self.declare_intrinsic(base_name, type_params)
851            })
852    }
853
854    fn declare_intrinsic(
855        &self,
856        base_name: &str,
857        type_params: &[&'ll Type],
858    ) -> (&'ll Type, &'ll Value) {
859        // This isn't an "LLVM intrinsic", but LLVM's optimization passes
860        // recognize it like one (including turning it into `bcmp` sometimes)
861        // and we use it to implement intrinsics like `raw_eq` and `compare_bytes`
862        if base_name == "memcmp" {
863            let fn_ty = self
864                .type_func(&[self.type_ptr(), self.type_ptr(), self.type_isize()], self.type_int());
865            let f = self.declare_cfn("memcmp", llvm::UnnamedAddr::No, fn_ty);
866
867            return (fn_ty, f);
868        }
869
870        let intrinsic = llvm::Intrinsic::lookup(base_name.as_bytes())
871            .unwrap_or_else(|| bug!("Unknown intrinsic: `{base_name}`"));
872        let f = intrinsic.get_declaration(self.llmod, &type_params);
873
874        (self.get_type_of_global(f), f)
875    }
876
877    pub(crate) fn eh_catch_typeinfo(&self) -> &'ll Value {
878        if let Some(eh_catch_typeinfo) = self.eh_catch_typeinfo.get() {
879            return eh_catch_typeinfo;
880        }
881        let tcx = self.tcx;
882        assert!(self.sess().target.os == "emscripten");
883        let eh_catch_typeinfo = match tcx.lang_items().eh_catch_typeinfo() {
884            Some(def_id) => self.get_static(def_id),
885            _ => {
886                let ty = self.type_struct(&[self.type_ptr(), self.type_ptr()], false);
887                self.declare_global(&mangle_internal_symbol(self.tcx, "rust_eh_catch_typeinfo"), ty)
888            }
889        };
890        self.eh_catch_typeinfo.set(Some(eh_catch_typeinfo));
891        eh_catch_typeinfo
892    }
893}
894
895impl CodegenCx<'_, '_> {
896    /// Generates a new symbol name with the given prefix. This symbol name must
897    /// only be used for definitions with `internal` or `private` linkage.
898    pub(crate) fn generate_local_symbol_name(&self, prefix: &str) -> String {
899        let idx = self.local_gen_sym_counter.get();
900        self.local_gen_sym_counter.set(idx + 1);
901        // Include a '.' character, so there can be no accidental conflicts with
902        // user defined names
903        let mut name = String::with_capacity(prefix.len() + 6);
904        name.push_str(prefix);
905        name.push('.');
906        name.push_str(&(idx as u64).to_base(ALPHANUMERIC_ONLY));
907        name
908    }
909}
910
911impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
912    /// A wrapper for [`llvm::LLVMSetMetadata`], but it takes `Metadata` as a parameter instead of `Value`.
913    pub(crate) fn set_metadata<'a>(
914        &self,
915        val: &'a Value,
916        kind_id: impl Into<llvm::MetadataKindId>,
917        md: &'ll Metadata,
918    ) {
919        let node = self.get_metadata_value(md);
920        llvm::LLVMSetMetadata(val, kind_id.into(), node);
921    }
922}
923
924impl HasDataLayout for CodegenCx<'_, '_> {
925    #[inline]
926    fn data_layout(&self) -> &TargetDataLayout {
927        &self.tcx.data_layout
928    }
929}
930
931impl HasTargetSpec for CodegenCx<'_, '_> {
932    #[inline]
933    fn target_spec(&self) -> &Target {
934        &self.tcx.sess.target
935    }
936}
937
938impl<'tcx> ty::layout::HasTyCtxt<'tcx> for CodegenCx<'_, 'tcx> {
939    #[inline]
940    fn tcx(&self) -> TyCtxt<'tcx> {
941        self.tcx
942    }
943}
944
945impl<'tcx, 'll> HasTypingEnv<'tcx> for CodegenCx<'ll, 'tcx> {
946    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
947        ty::TypingEnv::fully_monomorphized()
948    }
949}
950
951impl<'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
952    #[inline]
953    fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
954        if let LayoutError::SizeOverflow(_) | LayoutError::ReferencesError(_) = err {
955            self.tcx.dcx().emit_fatal(Spanned { span, node: err.into_diagnostic() })
956        } else {
957            self.tcx.dcx().emit_fatal(ssa_errors::FailedToGetLayout { span, ty, err })
958        }
959    }
960}
961
962impl<'tcx> FnAbiOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
963    #[inline]
964    fn handle_fn_abi_err(
965        &self,
966        err: FnAbiError<'tcx>,
967        span: Span,
968        fn_abi_request: FnAbiRequest<'tcx>,
969    ) -> ! {
970        match err {
971            FnAbiError::Layout(LayoutError::SizeOverflow(_) | LayoutError::Cycle(_)) => {
972                self.tcx.dcx().emit_fatal(Spanned { span, node: err });
973            }
974            _ => match fn_abi_request {
975                FnAbiRequest::OfFnPtr { sig, extra_args } => {
976                    span_bug!(span, "`fn_abi_of_fn_ptr({sig}, {extra_args:?})` failed: {err:?}",);
977                }
978                FnAbiRequest::OfInstance { instance, extra_args } => {
979                    span_bug!(
980                        span,
981                        "`fn_abi_of_instance({instance}, {extra_args:?})` failed: {err:?}",
982                    );
983                }
984            },
985        }
986    }
987}