Skip to main content

rustc_codegen_ssa/back/
symbol_export.rs

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