Skip to main content

rustc_codegen_ssa/back/
symbol_export.rs

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