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