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