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