rustc_codegen_ssa/back/
symbol_export.rs

1use std::collections::hash_map::Entry::*;
2
3use rustc_abi::{CanonAbi, X86Call};
4use rustc_ast::expand::allocator::{ALLOCATOR_METHODS, NO_ALLOC_SHIM_IS_UNSTABLE, global_fn_name};
5use rustc_data_structures::unord::UnordMap;
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE, LocalDefId};
8use rustc_middle::bug;
9use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
10use rustc_middle::middle::exported_symbols::{
11    ExportedSymbol, SymbolExportInfo, SymbolExportKind, SymbolExportLevel, metadata_symbol_name,
12};
13use rustc_middle::query::LocalCrate;
14use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, Instance, SymbolName, Ty, TyCtxt};
15use rustc_middle::util::Providers;
16use rustc_session::config::{CrateType, OomStrategy};
17use rustc_symbol_mangling::mangle_internal_symbol;
18use rustc_target::spec::{SanitizerSet, TlsModel};
19use tracing::debug;
20
21use crate::base::allocator_kind_for_codegen;
22
23fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
24    crates_export_threshold(tcx.crate_types())
25}
26
27fn crate_export_threshold(crate_type: CrateType) -> SymbolExportLevel {
28    match crate_type {
29        CrateType::Executable | CrateType::Staticlib | CrateType::ProcMacro | CrateType::Cdylib => {
30            SymbolExportLevel::C
31        }
32        CrateType::Rlib | CrateType::Dylib | CrateType::Sdylib => SymbolExportLevel::Rust,
33    }
34}
35
36pub fn crates_export_threshold(crate_types: &[CrateType]) -> SymbolExportLevel {
37    if crate_types
38        .iter()
39        .any(|&crate_type| crate_export_threshold(crate_type) == SymbolExportLevel::Rust)
40    {
41        SymbolExportLevel::Rust
42    } else {
43        SymbolExportLevel::C
44    }
45}
46
47fn reachable_non_generics_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> DefIdMap<SymbolExportInfo> {
48    if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
49        return Default::default();
50    }
51
52    // Check to see if this crate is a "special runtime crate". These
53    // crates, implementation details of the standard library, typically
54    // have a bunch of `pub extern` and `#[no_mangle]` functions as the
55    // ABI between them. We don't want their symbols to have a `C`
56    // export level, however, as they're just implementation details.
57    // Down below we'll hardwire all of the symbols to the `Rust` export
58    // level instead.
59    let special_runtime_crate =
60        tcx.is_panic_runtime(LOCAL_CRATE) || tcx.is_compiler_builtins(LOCAL_CRATE);
61
62    let mut reachable_non_generics: DefIdMap<_> = tcx
63        .reachable_set(())
64        .items()
65        .filter_map(|&def_id| {
66            // We want to ignore some FFI functions that are not exposed from
67            // this crate. Reachable FFI functions can be lumped into two
68            // categories:
69            //
70            // 1. Those that are included statically via a static library
71            // 2. Those included otherwise (e.g., dynamically or via a framework)
72            //
73            // Although our LLVM module is not literally emitting code for the
74            // statically included symbols, it's an export of our library which
75            // needs to be passed on to the linker and encoded in the metadata.
76            //
77            // As a result, if this id is an FFI item (foreign item) then we only
78            // let it through if it's included statically.
79            if let Some(parent_id) = tcx.opt_local_parent(def_id)
80                && let DefKind::ForeignMod = tcx.def_kind(parent_id)
81            {
82                let library = tcx.native_library(def_id)?;
83                return library.kind.is_statically_included().then_some(def_id);
84            }
85
86            // Only consider nodes that actually have exported symbols.
87            match tcx.def_kind(def_id) {
88                DefKind::Fn | DefKind::Static { .. } => {}
89                DefKind::AssocFn if tcx.impl_of_method(def_id.to_def_id()).is_some() => {}
90                _ => return None,
91            };
92
93            let generics = tcx.generics_of(def_id);
94            if generics.requires_monomorphization(tcx) {
95                return None;
96            }
97
98            if Instance::mono(tcx, def_id.into()).def.requires_inline(tcx) {
99                return None;
100            }
101
102            if tcx.cross_crate_inlinable(def_id) { None } else { Some(def_id) }
103        })
104        .map(|def_id| {
105            // We won't link right if this symbol is stripped during LTO.
106            let name = tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())).name;
107            let used = name == "rust_eh_personality";
108
109            let export_level = if special_runtime_crate {
110                SymbolExportLevel::Rust
111            } else {
112                symbol_export_level(tcx, def_id.to_def_id())
113            };
114            let codegen_attrs = tcx.codegen_fn_attrs(def_id.to_def_id());
115            debug!(
116                "EXPORTED SYMBOL (local): {} ({:?})",
117                tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())),
118                export_level
119            );
120            let info = SymbolExportInfo {
121                level: export_level,
122                kind: if tcx.is_static(def_id.to_def_id()) {
123                    if codegen_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
124                        SymbolExportKind::Tls
125                    } else {
126                        SymbolExportKind::Data
127                    }
128                } else {
129                    SymbolExportKind::Text
130                },
131                used: codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
132                    || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)
133                    || used,
134                rustc_std_internal_symbol: codegen_attrs
135                    .flags
136                    .contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL),
137            };
138            (def_id.to_def_id(), info)
139        })
140        .into();
141
142    if let Some(id) = tcx.proc_macro_decls_static(()) {
143        reachable_non_generics.insert(
144            id.to_def_id(),
145            SymbolExportInfo {
146                level: SymbolExportLevel::C,
147                kind: SymbolExportKind::Data,
148                used: false,
149                rustc_std_internal_symbol: false,
150            },
151        );
152    }
153
154    reachable_non_generics
155}
156
157fn is_reachable_non_generic_provider_local(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
158    let export_threshold = threshold(tcx);
159
160    if let Some(&info) = tcx.reachable_non_generics(LOCAL_CRATE).get(&def_id.to_def_id()) {
161        info.level.is_below_threshold(export_threshold)
162    } else {
163        false
164    }
165}
166
167fn is_reachable_non_generic_provider_extern(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
168    tcx.reachable_non_generics(def_id.krate).contains_key(&def_id)
169}
170
171fn exported_symbols_provider_local<'tcx>(
172    tcx: TyCtxt<'tcx>,
173    _: LocalCrate,
174) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
175    if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
176        return &[];
177    }
178
179    // FIXME: Sorting this is unnecessary since we are sorting later anyway.
180    //        Can we skip the later sorting?
181    let sorted = tcx.with_stable_hashing_context(|hcx| {
182        tcx.reachable_non_generics(LOCAL_CRATE).to_sorted(&hcx, true)
183    });
184
185    let mut symbols: Vec<_> =
186        sorted.iter().map(|&(&def_id, &info)| (ExportedSymbol::NonGeneric(def_id), info)).collect();
187
188    // Export TLS shims
189    if !tcx.sess.target.dll_tls_export {
190        symbols.extend(sorted.iter().filter_map(|&(&def_id, &info)| {
191            tcx.needs_thread_local_shim(def_id).then(|| {
192                (
193                    ExportedSymbol::ThreadLocalShim(def_id),
194                    SymbolExportInfo {
195                        level: info.level,
196                        kind: SymbolExportKind::Text,
197                        used: info.used,
198                        rustc_std_internal_symbol: info.rustc_std_internal_symbol,
199                    },
200                )
201            })
202        }))
203    }
204
205    if tcx.entry_fn(()).is_some() {
206        let exported_symbol =
207            ExportedSymbol::NoDefId(SymbolName::new(tcx, tcx.sess.target.entry_name.as_ref()));
208
209        symbols.push((
210            exported_symbol,
211            SymbolExportInfo {
212                level: SymbolExportLevel::C,
213                kind: SymbolExportKind::Text,
214                used: false,
215                rustc_std_internal_symbol: false,
216            },
217        ));
218    }
219
220    // Mark allocator shim symbols as exported only if they were generated.
221    if allocator_kind_for_codegen(tcx).is_some() {
222        for symbol_name in ALLOCATOR_METHODS
223            .iter()
224            .map(|method| mangle_internal_symbol(tcx, global_fn_name(method.name).as_str()))
225            .chain([
226                mangle_internal_symbol(tcx, "__rust_alloc_error_handler"),
227                mangle_internal_symbol(tcx, OomStrategy::SYMBOL),
228                mangle_internal_symbol(tcx, NO_ALLOC_SHIM_IS_UNSTABLE),
229            ])
230        {
231            let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
232
233            symbols.push((
234                exported_symbol,
235                SymbolExportInfo {
236                    level: SymbolExportLevel::Rust,
237                    kind: SymbolExportKind::Text,
238                    used: false,
239                    rustc_std_internal_symbol: true,
240                },
241            ));
242        }
243    }
244
245    if tcx.sess.instrument_coverage() || tcx.sess.opts.cg.profile_generate.enabled() {
246        // These are weak symbols that point to the profile version and the
247        // profile name, which need to be treated as exported so LTO doesn't nix
248        // them.
249        const PROFILER_WEAK_SYMBOLS: [&str; 2] =
250            ["__llvm_profile_raw_version", "__llvm_profile_filename"];
251
252        symbols.extend(PROFILER_WEAK_SYMBOLS.iter().map(|sym| {
253            let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, sym));
254            (
255                exported_symbol,
256                SymbolExportInfo {
257                    level: SymbolExportLevel::C,
258                    kind: SymbolExportKind::Data,
259                    used: false,
260                    rustc_std_internal_symbol: false,
261                },
262            )
263        }));
264    }
265
266    if tcx.sess.opts.unstable_opts.sanitizer.contains(SanitizerSet::MEMORY) {
267        let mut msan_weak_symbols = Vec::new();
268
269        // Similar to profiling, preserve weak msan symbol during LTO.
270        if tcx.sess.opts.unstable_opts.sanitizer_recover.contains(SanitizerSet::MEMORY) {
271            msan_weak_symbols.push("__msan_keep_going");
272        }
273
274        if tcx.sess.opts.unstable_opts.sanitizer_memory_track_origins != 0 {
275            msan_weak_symbols.push("__msan_track_origins");
276        }
277
278        symbols.extend(msan_weak_symbols.into_iter().map(|sym| {
279            let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, sym));
280            (
281                exported_symbol,
282                SymbolExportInfo {
283                    level: SymbolExportLevel::C,
284                    kind: SymbolExportKind::Data,
285                    used: false,
286                    rustc_std_internal_symbol: false,
287                },
288            )
289        }));
290    }
291
292    if tcx.crate_types().contains(&CrateType::Dylib)
293        || tcx.crate_types().contains(&CrateType::ProcMacro)
294    {
295        let symbol_name = metadata_symbol_name(tcx);
296        let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
297
298        symbols.push((
299            exported_symbol,
300            SymbolExportInfo {
301                level: SymbolExportLevel::C,
302                kind: SymbolExportKind::Data,
303                used: true,
304                rustc_std_internal_symbol: false,
305            },
306        ));
307    }
308
309    if tcx.local_crate_exports_generics() {
310        use rustc_middle::mir::mono::{Linkage, MonoItem, Visibility};
311        use rustc_middle::ty::InstanceKind;
312
313        // Normally, we require that shared monomorphizations are not hidden,
314        // because if we want to re-use a monomorphization from a Rust dylib, it
315        // needs to be exported.
316        // However, on platforms that don't allow for Rust dylibs, having
317        // external linkage is enough for monomorphization to be linked to.
318        let need_visibility = tcx.sess.target.dynamic_linking && !tcx.sess.target.only_cdylib;
319
320        let cgus = tcx.collect_and_partition_mono_items(()).codegen_units;
321
322        // Do not export symbols that cannot be instantiated by downstream crates.
323        let reachable_set = tcx.reachable_set(());
324        let is_local_to_current_crate = |ty: Ty<'_>| {
325            let no_refs = ty.peel_refs();
326            let root_def_id = match no_refs.kind() {
327                ty::Closure(closure, _) => *closure,
328                ty::FnDef(def_id, _) => *def_id,
329                ty::Coroutine(def_id, _) => *def_id,
330                ty::CoroutineClosure(def_id, _) => *def_id,
331                ty::CoroutineWitness(def_id, _) => *def_id,
332                _ => return false,
333            };
334            let Some(root_def_id) = root_def_id.as_local() else {
335                return false;
336            };
337
338            let is_local = !reachable_set.contains(&root_def_id);
339            is_local
340        };
341
342        let is_instantiable_downstream =
343            |did: Option<DefId>, generic_args: GenericArgsRef<'tcx>| {
344                generic_args
345                    .types()
346                    .chain(did.into_iter().map(move |did| tcx.type_of(did).skip_binder()))
347                    .all(move |arg| {
348                        arg.walk().all(|ty| {
349                            ty.as_type().map_or(true, |ty| !is_local_to_current_crate(ty))
350                        })
351                    })
352            };
353
354        // The symbols created in this loop are sorted below it
355        #[allow(rustc::potential_query_instability)]
356        for (mono_item, data) in cgus.iter().flat_map(|cgu| cgu.items().iter()) {
357            if data.linkage != Linkage::External {
358                // We can only re-use things with external linkage, otherwise
359                // we'll get a linker error
360                continue;
361            }
362
363            if need_visibility && data.visibility == Visibility::Hidden {
364                // If we potentially share things from Rust dylibs, they must
365                // not be hidden
366                continue;
367            }
368
369            if !tcx.sess.opts.share_generics() {
370                if tcx.codegen_fn_attrs(mono_item.def_id()).inline
371                    == rustc_attr_data_structures::InlineAttr::Never
372                {
373                    // this is OK, we explicitly allow sharing inline(never) across crates even
374                    // without share-generics.
375                } else {
376                    continue;
377                }
378            }
379
380            // Note: These all set rustc_std_internal_symbol to false as generic functions must not
381            // be marked with this attribute and we are only handling generic functions here.
382            match *mono_item {
383                MonoItem::Fn(Instance { def: InstanceKind::Item(def), args }) => {
384                    let has_generics = args.non_erasable_generics().next().is_some();
385
386                    let should_export =
387                        has_generics && is_instantiable_downstream(Some(def), &args);
388
389                    if should_export {
390                        let symbol = ExportedSymbol::Generic(def, args);
391                        symbols.push((
392                            symbol,
393                            SymbolExportInfo {
394                                level: SymbolExportLevel::Rust,
395                                kind: SymbolExportKind::Text,
396                                used: false,
397                                rustc_std_internal_symbol: false,
398                            },
399                        ));
400                    }
401                }
402                MonoItem::Fn(Instance { def: InstanceKind::DropGlue(_, Some(ty)), args }) => {
403                    // A little sanity-check
404                    assert_eq!(args.non_erasable_generics().next(), Some(GenericArgKind::Type(ty)));
405
406                    // Drop glue did is always going to be non-local outside of libcore, thus we don't need to check it's locality (which includes invoking `type_of` query).
407                    let should_export = match ty.kind() {
408                        ty::Adt(_, args) => is_instantiable_downstream(None, args),
409                        ty::Closure(_, args) => is_instantiable_downstream(None, args),
410                        _ => true,
411                    };
412
413                    if should_export {
414                        symbols.push((
415                            ExportedSymbol::DropGlue(ty),
416                            SymbolExportInfo {
417                                level: SymbolExportLevel::Rust,
418                                kind: SymbolExportKind::Text,
419                                used: false,
420                                rustc_std_internal_symbol: false,
421                            },
422                        ));
423                    }
424                }
425                MonoItem::Fn(Instance {
426                    def: InstanceKind::AsyncDropGlueCtorShim(_, ty),
427                    args,
428                }) => {
429                    // A little sanity-check
430                    assert_eq!(args.non_erasable_generics().next(), Some(GenericArgKind::Type(ty)));
431                    symbols.push((
432                        ExportedSymbol::AsyncDropGlueCtorShim(ty),
433                        SymbolExportInfo {
434                            level: SymbolExportLevel::Rust,
435                            kind: SymbolExportKind::Text,
436                            used: false,
437                            rustc_std_internal_symbol: false,
438                        },
439                    ));
440                }
441                MonoItem::Fn(Instance { def: InstanceKind::AsyncDropGlue(def, ty), args: _ }) => {
442                    symbols.push((
443                        ExportedSymbol::AsyncDropGlue(def, ty),
444                        SymbolExportInfo {
445                            level: SymbolExportLevel::Rust,
446                            kind: SymbolExportKind::Text,
447                            used: false,
448                            rustc_std_internal_symbol: false,
449                        },
450                    ));
451                }
452                _ => {
453                    // Any other symbols don't qualify for sharing
454                }
455            }
456        }
457    }
458
459    // Sort so we get a stable incr. comp. hash.
460    symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
461
462    tcx.arena.alloc_from_iter(symbols)
463}
464
465fn upstream_monomorphizations_provider(
466    tcx: TyCtxt<'_>,
467    (): (),
468) -> DefIdMap<UnordMap<GenericArgsRef<'_>, CrateNum>> {
469    let cnums = tcx.crates(());
470
471    let mut instances: DefIdMap<UnordMap<_, _>> = Default::default();
472
473    let drop_in_place_fn_def_id = tcx.lang_items().drop_in_place_fn();
474    let async_drop_in_place_fn_def_id = tcx.lang_items().async_drop_in_place_fn();
475
476    for &cnum in cnums.iter() {
477        for (exported_symbol, _) in tcx.exported_symbols(cnum).iter() {
478            let (def_id, args) = match *exported_symbol {
479                ExportedSymbol::Generic(def_id, args) => (def_id, args),
480                ExportedSymbol::DropGlue(ty) => {
481                    if let Some(drop_in_place_fn_def_id) = drop_in_place_fn_def_id {
482                        (drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
483                    } else {
484                        // `drop_in_place` in place does not exist, don't try
485                        // to use it.
486                        continue;
487                    }
488                }
489                ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
490                    if let Some(async_drop_in_place_fn_def_id) = async_drop_in_place_fn_def_id {
491                        (async_drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
492                    } else {
493                        continue;
494                    }
495                }
496                ExportedSymbol::AsyncDropGlue(def_id, ty) => (def_id, tcx.mk_args(&[ty.into()])),
497                ExportedSymbol::NonGeneric(..)
498                | ExportedSymbol::ThreadLocalShim(..)
499                | ExportedSymbol::NoDefId(..) => {
500                    // These are no monomorphizations
501                    continue;
502                }
503            };
504
505            let args_map = instances.entry(def_id).or_default();
506
507            match args_map.entry(args) {
508                Occupied(mut e) => {
509                    // If there are multiple monomorphizations available,
510                    // we select one deterministically.
511                    let other_cnum = *e.get();
512                    if tcx.stable_crate_id(other_cnum) > tcx.stable_crate_id(cnum) {
513                        e.insert(cnum);
514                    }
515                }
516                Vacant(e) => {
517                    e.insert(cnum);
518                }
519            }
520        }
521    }
522
523    instances
524}
525
526fn upstream_monomorphizations_for_provider(
527    tcx: TyCtxt<'_>,
528    def_id: DefId,
529) -> Option<&UnordMap<GenericArgsRef<'_>, CrateNum>> {
530    assert!(!def_id.is_local());
531    tcx.upstream_monomorphizations(()).get(&def_id)
532}
533
534fn upstream_drop_glue_for_provider<'tcx>(
535    tcx: TyCtxt<'tcx>,
536    args: GenericArgsRef<'tcx>,
537) -> Option<CrateNum> {
538    let def_id = tcx.lang_items().drop_in_place_fn()?;
539    tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
540}
541
542fn upstream_async_drop_glue_for_provider<'tcx>(
543    tcx: TyCtxt<'tcx>,
544    args: GenericArgsRef<'tcx>,
545) -> Option<CrateNum> {
546    let def_id = tcx.lang_items().async_drop_in_place_fn()?;
547    tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
548}
549
550fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
551    !tcx.reachable_set(()).contains(&def_id)
552}
553
554pub(crate) fn provide(providers: &mut Providers) {
555    providers.reachable_non_generics = reachable_non_generics_provider;
556    providers.is_reachable_non_generic = is_reachable_non_generic_provider_local;
557    providers.exported_symbols = exported_symbols_provider_local;
558    providers.upstream_monomorphizations = upstream_monomorphizations_provider;
559    providers.is_unreachable_local_definition = is_unreachable_local_definition_provider;
560    providers.upstream_drop_glue_for = upstream_drop_glue_for_provider;
561    providers.upstream_async_drop_glue_for = upstream_async_drop_glue_for_provider;
562    providers.wasm_import_module_map = wasm_import_module_map;
563    providers.extern_queries.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
564    providers.extern_queries.upstream_monomorphizations_for =
565        upstream_monomorphizations_for_provider;
566}
567
568fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
569    // We export anything that's not mangled at the "C" layer as it probably has
570    // to do with ABI concerns. We do not, however, apply such treatment to
571    // special symbols in the standard library for various plumbing between
572    // core/std/allocators/etc. For example symbols used to hook up allocation
573    // are not considered for export
574    let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
575    let is_extern = codegen_fn_attrs.contains_extern_indicator();
576    let std_internal =
577        codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
578
579    if is_extern && !std_internal {
580        let target = &tcx.sess.target.llvm_target;
581        // WebAssembly cannot export data symbols, so reduce their export level
582        if target.contains("emscripten") {
583            if let DefKind::Static { .. } = tcx.def_kind(sym_def_id) {
584                return SymbolExportLevel::Rust;
585            }
586        }
587
588        SymbolExportLevel::C
589    } else {
590        SymbolExportLevel::Rust
591    }
592}
593
594/// This is the symbol name of the given instance instantiated in a specific crate.
595pub(crate) fn symbol_name_for_instance_in_crate<'tcx>(
596    tcx: TyCtxt<'tcx>,
597    symbol: ExportedSymbol<'tcx>,
598    instantiating_crate: CrateNum,
599) -> String {
600    // If this is something instantiated in the local crate then we might
601    // already have cached the name as a query result.
602    if instantiating_crate == LOCAL_CRATE {
603        return symbol.symbol_name_for_local_instance(tcx).to_string();
604    }
605
606    // This is something instantiated in an upstream crate, so we have to use
607    // the slower (because uncached) version of computing the symbol name.
608    match symbol {
609        ExportedSymbol::NonGeneric(def_id) => {
610            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
611                tcx,
612                Instance::mono(tcx, def_id),
613                instantiating_crate,
614            )
615        }
616        ExportedSymbol::Generic(def_id, args) => {
617            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
618                tcx,
619                Instance::new_raw(def_id, args),
620                instantiating_crate,
621            )
622        }
623        ExportedSymbol::ThreadLocalShim(def_id) => {
624            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
625                tcx,
626                ty::Instance {
627                    def: ty::InstanceKind::ThreadLocalShim(def_id),
628                    args: ty::GenericArgs::empty(),
629                },
630                instantiating_crate,
631            )
632        }
633        ExportedSymbol::DropGlue(ty) => rustc_symbol_mangling::symbol_name_for_instance_in_crate(
634            tcx,
635            Instance::resolve_drop_in_place(tcx, ty),
636            instantiating_crate,
637        ),
638        ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
639            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
640                tcx,
641                Instance::resolve_async_drop_in_place(tcx, ty),
642                instantiating_crate,
643            )
644        }
645        ExportedSymbol::AsyncDropGlue(def_id, ty) => {
646            rustc_symbol_mangling::symbol_name_for_instance_in_crate(
647                tcx,
648                Instance::resolve_async_drop_in_place_poll(tcx, def_id, ty),
649                instantiating_crate,
650            )
651        }
652        ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),
653    }
654}
655
656fn calling_convention_for_symbol<'tcx>(
657    tcx: TyCtxt<'tcx>,
658    symbol: ExportedSymbol<'tcx>,
659) -> (CanonAbi, &'tcx [rustc_target::callconv::ArgAbi<'tcx, Ty<'tcx>>]) {
660    let instance = match symbol {
661        ExportedSymbol::NonGeneric(def_id) | ExportedSymbol::Generic(def_id, _)
662            if tcx.is_static(def_id) =>
663        {
664            None
665        }
666        ExportedSymbol::NonGeneric(def_id) => Some(Instance::mono(tcx, def_id)),
667        ExportedSymbol::Generic(def_id, args) => Some(Instance::new_raw(def_id, args)),
668        // DropGlue always use the Rust calling convention and thus follow the target's default
669        // symbol decoration scheme.
670        ExportedSymbol::DropGlue(..) => None,
671        // AsyncDropGlueCtorShim always use the Rust calling convention and thus follow the
672        // target's default symbol decoration scheme.
673        ExportedSymbol::AsyncDropGlueCtorShim(..) => None,
674        ExportedSymbol::AsyncDropGlue(..) => None,
675        // NoDefId always follow the target's default symbol decoration scheme.
676        ExportedSymbol::NoDefId(..) => None,
677        // ThreadLocalShim always follow the target's default symbol decoration scheme.
678        ExportedSymbol::ThreadLocalShim(..) => None,
679    };
680
681    instance
682        .map(|i| {
683            tcx.fn_abi_of_instance(
684                ty::TypingEnv::fully_monomorphized().as_query_input((i, ty::List::empty())),
685            )
686            .unwrap_or_else(|_| bug!("fn_abi_of_instance({i:?}) failed"))
687        })
688        .map(|fnabi| (fnabi.conv, &fnabi.args[..]))
689        // FIXME(workingjubilee): why don't we know the convention here?
690        .unwrap_or((CanonAbi::Rust, &[]))
691}
692
693/// This is the symbol name of the given instance as seen by the linker.
694///
695/// On 32-bit Windows symbols are decorated according to their calling conventions.
696pub(crate) fn linking_symbol_name_for_instance_in_crate<'tcx>(
697    tcx: TyCtxt<'tcx>,
698    symbol: ExportedSymbol<'tcx>,
699    export_kind: SymbolExportKind,
700    instantiating_crate: CrateNum,
701) -> String {
702    let mut undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
703
704    // thread local will not be a function call,
705    // so it is safe to return before windows symbol decoration check.
706    if let Some(name) = maybe_emutls_symbol_name(tcx, symbol, &undecorated) {
707        return name;
708    }
709
710    let target = &tcx.sess.target;
711    if !target.is_like_windows {
712        // Mach-O has a global "_" suffix and `object` crate will handle it.
713        // ELF does not have any symbol decorations.
714        return undecorated;
715    }
716
717    let prefix = match &target.arch[..] {
718        "x86" => Some('_'),
719        "x86_64" => None,
720        // Only functions are decorated for arm64ec.
721        "arm64ec" if export_kind == SymbolExportKind::Text => Some('#'),
722        // Only x86/64 and arm64ec use symbol decorations.
723        _ => return undecorated,
724    };
725
726    let (callconv, args) = calling_convention_for_symbol(tcx, symbol);
727
728    // Decorate symbols with prefixes, suffixes and total number of bytes of arguments.
729    // Reference: https://docs.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170
730    let (prefix, suffix) = match callconv {
731        CanonAbi::X86(X86Call::Fastcall) => ("@", "@"),
732        CanonAbi::X86(X86Call::Stdcall) => ("_", "@"),
733        CanonAbi::X86(X86Call::Vectorcall) => ("", "@@"),
734        _ => {
735            if let Some(prefix) = prefix {
736                undecorated.insert(0, prefix);
737            }
738            return undecorated;
739        }
740    };
741
742    let args_in_bytes: u64 = args
743        .iter()
744        .map(|abi| abi.layout.size.bytes().next_multiple_of(target.pointer_width as u64 / 8))
745        .sum();
746    format!("{prefix}{undecorated}{suffix}{args_in_bytes}")
747}
748
749pub(crate) fn exporting_symbol_name_for_instance_in_crate<'tcx>(
750    tcx: TyCtxt<'tcx>,
751    symbol: ExportedSymbol<'tcx>,
752    cnum: CrateNum,
753) -> String {
754    let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, cnum);
755    maybe_emutls_symbol_name(tcx, symbol, &undecorated).unwrap_or(undecorated)
756}
757
758/// On amdhsa, `gpu-kernel` functions have an associated metadata object with a `.kd` suffix.
759/// Add it to the symbols list for all kernel functions, so that it is exported in the linked
760/// object.
761pub(crate) fn extend_exported_symbols<'tcx>(
762    symbols: &mut Vec<(String, SymbolExportKind)>,
763    tcx: TyCtxt<'tcx>,
764    symbol: ExportedSymbol<'tcx>,
765    instantiating_crate: CrateNum,
766) {
767    let (callconv, _) = calling_convention_for_symbol(tcx, symbol);
768
769    if callconv != CanonAbi::GpuKernel || tcx.sess.target.os != "amdhsa" {
770        return;
771    }
772
773    let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
774
775    // Add the symbol for the kernel descriptor (with .kd suffix)
776    // Per https://llvm.org/docs/AMDGPUUsage.html#symbols these will always be `STT_OBJECT` so
777    // export as data.
778    symbols.push((format!("{undecorated}.kd"), SymbolExportKind::Data));
779}
780
781fn maybe_emutls_symbol_name<'tcx>(
782    tcx: TyCtxt<'tcx>,
783    symbol: ExportedSymbol<'tcx>,
784    undecorated: &str,
785) -> Option<String> {
786    if matches!(tcx.sess.tls_model(), TlsModel::Emulated)
787        && let ExportedSymbol::NonGeneric(def_id) = symbol
788        && tcx.is_thread_local_static(def_id)
789    {
790        // When using emutls, LLVM will add the `__emutls_v.` prefix to thread local symbols,
791        // and exported symbol name need to match this.
792        Some(format!("__emutls_v.{undecorated}"))
793    } else {
794        None
795    }
796}
797
798fn wasm_import_module_map(tcx: TyCtxt<'_>, cnum: CrateNum) -> DefIdMap<String> {
799    // Build up a map from DefId to a `NativeLib` structure, where
800    // `NativeLib` internally contains information about
801    // `#[link(wasm_import_module = "...")]` for example.
802    let native_libs = tcx.native_libraries(cnum);
803
804    let def_id_to_native_lib = native_libs
805        .iter()
806        .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
807        .collect::<DefIdMap<_>>();
808
809    let mut ret = DefIdMap::default();
810    for (def_id, lib) in tcx.foreign_modules(cnum).iter() {
811        let module = def_id_to_native_lib.get(def_id).and_then(|s| s.wasm_import_module());
812        let Some(module) = module else { continue };
813        ret.extend(lib.foreign_items.iter().map(|id| {
814            assert_eq!(id.krate, cnum);
815            (*id, module.to_string())
816        }));
817    }
818
819    ret
820}