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::{
15 self, GenericArgKind, GenericArgsRef, Instance, ShimKind, SymbolName, Ty, TyCtxt,
16};
17use rustc_middle::util::Providers;
18use rustc_session::config::CrateType;
19use rustc_span::Span;
20use rustc_symbol_mangling::mangle_internal_symbol;
21use rustc_target::spec::{Arch, Os, TlsModel};
22use tracing::debug;
23
24use crate::SymbolExport;
25use crate::back::symbol_export;
26use crate::base::allocator_shim_contents;
27
28fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
29 crates_export_threshold(tcx.crate_types())
30}
31
32fn crate_export_threshold(crate_type: CrateType) -> SymbolExportLevel {
33 match crate_type {
34 CrateType::Executable | CrateType::StaticLib | CrateType::ProcMacro | CrateType::Cdylib => {
35 SymbolExportLevel::C
36 }
37 CrateType::Rlib | CrateType::Dylib | CrateType::Sdylib => SymbolExportLevel::Rust,
38 }
39}
40
41pub fn crates_export_threshold(crate_types: &[CrateType]) -> SymbolExportLevel {
42 if crate_types
43 .iter()
44 .any(|&crate_type| crate_export_threshold(crate_type) == SymbolExportLevel::Rust)
45 {
46 SymbolExportLevel::Rust
47 } else {
48 SymbolExportLevel::C
49 }
50}
51
52fn reachable_non_generics_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> DefIdMap<SymbolExportInfo> {
53 if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
54 return Default::default();
55 }
56
57 let is_compiler_builtins = tcx.is_compiler_builtins(LOCAL_CRATE);
58
59 let mut reachable_non_generics: DefIdMap<_> = tcx
60 .reachable_set(())
61 .items()
62 .filter_map(|&def_id| {
63 if let Some(parent_id) = tcx.opt_local_parent(def_id)
77 && let DefKind::ForeignMod = tcx.def_kind(parent_id)
78 {
79 let library = tcx.native_library(def_id)?;
80 return library.kind.is_statically_included().then_some(def_id);
81 }
82
83 match tcx.def_kind(def_id) {
85 DefKind::Fn | DefKind::Static { .. } => {}
86 DefKind::AssocFn if tcx.impl_of_assoc(def_id.to_def_id()).is_some() => {}
87 _ => return None,
88 };
89
90 let generics = tcx.generics_of(def_id);
91 if generics.requires_monomorphization(tcx) {
92 return None;
93 }
94
95 if Instance::mono(tcx, def_id.into()).def.requires_inline(tcx) {
96 return None;
97 }
98
99 if tcx.cross_crate_inlinable(def_id) { None } else { Some(def_id) }
100 })
101 .map(|def_id| {
102 let export_level = if is_compiler_builtins {
103 SymbolExportLevel::Rust
109 } else {
110 symbol_export_level(tcx, def_id.to_def_id())
111 };
112 let codegen_attrs = tcx.codegen_fn_attrs(def_id.to_def_id());
113 {
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:113",
"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(113u32),
::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!(
114 "EXPORTED SYMBOL (local): {} ({:?})",
115 tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())),
116 export_level
117 );
118 let info = SymbolExportInfo {
119 level: export_level,
120 kind: if tcx.is_static(def_id.to_def_id()) {
121 if codegen_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
122 SymbolExportKind::Tls
123 } else {
124 SymbolExportKind::Data
125 }
126 } else {
127 SymbolExportKind::Text
128 },
129 used: codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)
130 || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER),
131 rustc_std_internal_symbol: codegen_attrs
132 .flags
133 .contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
134 || codegen_attrs
135 .flags
136 .contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM),
137 };
138 (def_id.to_def_id(), info)
139 })
140 .into();
141
142 if let Some(id) = tcx.proc_macro_decls_static(()) {
143 reachable_non_generics.insert(
144 id.to_def_id(),
145 SymbolExportInfo {
146 level: SymbolExportLevel::C,
147 kind: SymbolExportKind::Data,
148 used: false,
149 rustc_std_internal_symbol: false,
150 },
151 );
152 }
153
154 reachable_non_generics
155}
156
157fn is_reachable_non_generic_provider_local(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
158 let export_threshold = threshold(tcx);
159
160 if let Some(&info) = tcx.reachable_non_generics(LOCAL_CRATE).get(&def_id.to_def_id()) {
161 info.level.is_below_threshold(export_threshold)
162 } else {
163 false
164 }
165}
166
167fn is_reachable_non_generic_provider_extern(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
168 tcx.reachable_non_generics(def_id.krate).contains_key(&def_id)
169}
170
171fn exported_non_generic_symbols_provider_local<'tcx>(
172 tcx: TyCtxt<'tcx>,
173 _: LocalCrate,
174) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
175 if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
176 return &[];
177 }
178
179 let sorted = tcx.with_stable_hashing_context(|mut hcx| {
182 tcx.reachable_non_generics(LOCAL_CRATE).to_sorted(&mut hcx, true)
183 });
184
185 let mut symbols: Vec<_> =
186 sorted.iter().map(|&(&def_id, &info)| (ExportedSymbol::NonGeneric(def_id), info)).collect();
187
188 if !tcx.sess.target.dll_tls_export {
190 symbols.extend(sorted.iter().filter_map(|&(&def_id, &info)| {
191 tcx.needs_thread_local_shim(def_id).then(|| {
192 (
193 ExportedSymbol::ThreadLocalShim(def_id),
194 SymbolExportInfo {
195 level: info.level,
196 kind: SymbolExportKind::Text,
197 used: info.used,
198 rustc_std_internal_symbol: info.rustc_std_internal_symbol,
199 },
200 )
201 })
202 }))
203 }
204
205 symbols.extend(sorted.iter().flat_map(|&(&def_id, &info)| {
206 tcx.codegen_fn_attrs(def_id).foreign_item_symbol_aliases.iter().map(
207 move |&(foreign_item, _linkage, _visibility)| {
208 (ExportedSymbol::NonGeneric(foreign_item), info)
209 },
210 )
211 }));
212
213 if tcx.entry_fn(()).is_some() {
214 let exported_symbol =
215 ExportedSymbol::NoDefId(SymbolName::new(tcx, tcx.sess.target.entry_name.as_ref()));
216
217 symbols.push((
218 exported_symbol,
219 SymbolExportInfo {
220 level: SymbolExportLevel::C,
221 kind: SymbolExportKind::Text,
222 used: false,
223 rustc_std_internal_symbol: false,
224 },
225 ));
226 }
227
228 symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
230
231 tcx.arena.alloc_from_iter(symbols)
232}
233
234fn exported_generic_symbols_provider_local<'tcx>(
235 tcx: TyCtxt<'tcx>,
236 _: LocalCrate,
237) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
238 if !tcx.sess.opts.output_types.should_codegen() && !tcx.is_sdylib_interface_build() {
239 return &[];
240 }
241
242 let mut symbols: Vec<_> = ::alloc::vec::Vec::new()vec![];
243
244 if tcx.local_crate_exports_generics() {
245 use rustc_hir::attrs::Linkage;
246 use rustc_middle::mono::{MonoItem, Visibility};
247 use rustc_middle::ty::InstanceKind;
248
249 let need_visibility = tcx.sess.target.dynamic_linking && !tcx.sess.target.only_cdylib;
255
256 let cgus = tcx.collect_and_partition_mono_items(()).codegen_units;
257
258 let reachable_set = tcx.reachable_set(());
260 let is_local_to_current_crate = |ty: Ty<'_>| {
261 let no_refs = ty.peel_refs();
262 let root_def_id = match no_refs.kind() {
263 ty::Closure(closure, _) => *closure,
264 ty::FnDef(def_id, _) => *def_id,
265 ty::Coroutine(def_id, _) => *def_id,
266 ty::CoroutineClosure(def_id, _) => *def_id,
267 ty::CoroutineWitness(def_id, _) => *def_id,
268 _ => return false,
269 };
270 let Some(root_def_id) = root_def_id.as_local() else {
271 return false;
272 };
273
274 let is_local = !reachable_set.contains(&root_def_id);
275 is_local
276 };
277
278 let is_instantiable_downstream =
279 |did: Option<DefId>, generic_args: GenericArgsRef<'tcx>| {
280 generic_args
281 .types()
282 .chain(did.into_iter().map(move |did| tcx.type_of(did).skip_binder()))
283 .all(move |arg| {
284 arg.walk().all(|ty| {
285 ty.as_type().map_or(true, |ty| !is_local_to_current_crate(ty))
286 })
287 })
288 };
289
290 #[allow(rustc::potential_query_instability)]
292 for (mono_item, data) in cgus.iter().flat_map(|cgu| cgu.items().iter()) {
293 if data.linkage != Linkage::External {
294 continue;
297 }
298
299 if need_visibility && data.visibility == Visibility::Hidden {
300 continue;
303 }
304
305 if !tcx.sess.opts.share_generics() {
306 if tcx.codegen_fn_attrs(mono_item.def_id()).inline
307 == rustc_hir::attrs::InlineAttr::Never
308 {
309 } else {
312 continue;
313 }
314 }
315
316 match *mono_item {
319 MonoItem::Fn(Instance { def: InstanceKind::Item(def), args }) => {
320 let has_generics = args.non_erasable_generics().next().is_some();
321
322 let should_export =
323 has_generics && is_instantiable_downstream(Some(def), &args);
324
325 if should_export {
326 let symbol = ExportedSymbol::Generic(def, args);
327 symbols.push((
328 symbol,
329 SymbolExportInfo {
330 level: SymbolExportLevel::Rust,
331 kind: SymbolExportKind::Text,
332 used: false,
333 rustc_std_internal_symbol: false,
334 },
335 ));
336 }
337 }
338 MonoItem::Fn(Instance {
339 def: InstanceKind::Shim(ShimKind::DropGlue(_, Some(ty))),
340 args,
341 }) => {
342 {
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)));
344
345 let should_export = match ty.kind() {
347 ty::Adt(_, args) => is_instantiable_downstream(None, args),
348 ty::Closure(_, args) => is_instantiable_downstream(None, args),
349 _ => true,
350 };
351
352 if should_export {
353 symbols.push((
354 ExportedSymbol::DropGlue(ty),
355 SymbolExportInfo {
356 level: SymbolExportLevel::Rust,
357 kind: SymbolExportKind::Text,
358 used: false,
359 rustc_std_internal_symbol: false,
360 },
361 ));
362 }
363 }
364 MonoItem::Fn(Instance {
365 def: InstanceKind::Shim(ShimKind::AsyncDropGlueCtor(_, ty)),
366 args,
367 }) => {
368 {
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)));
370 symbols.push((
371 ExportedSymbol::AsyncDropGlueCtorShim(ty),
372 SymbolExportInfo {
373 level: SymbolExportLevel::Rust,
374 kind: SymbolExportKind::Text,
375 used: false,
376 rustc_std_internal_symbol: false,
377 },
378 ));
379 }
380 MonoItem::Fn(Instance {
381 def: InstanceKind::Shim(ShimKind::AsyncDropGlue(def, ty)),
382 args: _,
383 }) => {
384 symbols.push((
385 ExportedSymbol::AsyncDropGlue(def, ty),
386 SymbolExportInfo {
387 level: SymbolExportLevel::Rust,
388 kind: SymbolExportKind::Text,
389 used: false,
390 rustc_std_internal_symbol: false,
391 },
392 ));
393 }
394 _ => {
395 }
397 }
398 }
399 }
400
401 symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
403
404 tcx.arena.alloc_from_iter(symbols)
405}
406
407fn upstream_monomorphizations_provider(
408 tcx: TyCtxt<'_>,
409 (): (),
410) -> DefIdMap<UnordMap<GenericArgsRef<'_>, CrateNum>> {
411 let cnums = tcx.crates(());
412
413 let mut instances: DefIdMap<UnordMap<_, _>> = Default::default();
414
415 let drop_glue_fn_def_id = tcx.lang_items().drop_glue_fn();
416 let async_drop_in_place_fn_def_id = tcx.lang_items().async_drop_in_place_fn();
417
418 for &cnum in cnums.iter() {
419 for (exported_symbol, _) in tcx.exported_generic_symbols(cnum).iter() {
420 let (def_id, args) = match *exported_symbol {
421 ExportedSymbol::Generic(def_id, args) => (def_id, args),
422 ExportedSymbol::DropGlue(ty) => {
423 if let Some(drop_in_place_fn_def_id) = drop_glue_fn_def_id {
424 (drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
425 } else {
426 continue;
428 }
429 }
430 ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
431 if let Some(async_drop_in_place_fn_def_id) = async_drop_in_place_fn_def_id {
432 (async_drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()]))
433 } else {
434 continue;
435 }
436 }
437 ExportedSymbol::AsyncDropGlue(def_id, ty) => (def_id, tcx.mk_args(&[ty.into()])),
438 ExportedSymbol::NonGeneric(..)
439 | ExportedSymbol::ThreadLocalShim(..)
440 | ExportedSymbol::NoDefId(..) => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("{0:?}", exported_symbol)));
}unreachable!("{exported_symbol:?}"),
441 };
442
443 let args_map = instances.entry(def_id).or_default();
444
445 match args_map.entry(args) {
446 Occupied(mut e) => {
447 let other_cnum = *e.get();
450 if tcx.stable_crate_id(other_cnum) > tcx.stable_crate_id(cnum) {
451 e.insert(cnum);
452 }
453 }
454 Vacant(e) => {
455 e.insert(cnum);
456 }
457 }
458 }
459 }
460
461 instances
462}
463
464fn upstream_monomorphizations_for_provider(
465 tcx: TyCtxt<'_>,
466 def_id: DefId,
467) -> Option<&UnordMap<GenericArgsRef<'_>, CrateNum>> {
468 if !!def_id.is_local() {
::core::panicking::panic("assertion failed: !def_id.is_local()")
};assert!(!def_id.is_local());
469 tcx.upstream_monomorphizations(()).get(&def_id)
470}
471
472fn upstream_drop_glue_for_provider<'tcx>(
473 tcx: TyCtxt<'tcx>,
474 args: GenericArgsRef<'tcx>,
475) -> Option<CrateNum> {
476 let def_id = tcx.lang_items().drop_glue_fn()?;
477 tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
478}
479
480fn upstream_async_drop_glue_for_provider<'tcx>(
481 tcx: TyCtxt<'tcx>,
482 args: GenericArgsRef<'tcx>,
483) -> Option<CrateNum> {
484 let def_id = tcx.lang_items().async_drop_in_place_fn()?;
485 tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned()
486}
487
488fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
489 !tcx.reachable_set(()).contains(&def_id)
490}
491
492pub(crate) fn provide(providers: &mut Providers) {
493 providers.queries.reachable_non_generics = reachable_non_generics_provider;
494 providers.queries.is_reachable_non_generic = is_reachable_non_generic_provider_local;
495 providers.queries.exported_non_generic_symbols = exported_non_generic_symbols_provider_local;
496 providers.queries.exported_generic_symbols = exported_generic_symbols_provider_local;
497 providers.queries.upstream_monomorphizations = upstream_monomorphizations_provider;
498 providers.queries.is_unreachable_local_definition = is_unreachable_local_definition_provider;
499 providers.queries.upstream_drop_glue_for = upstream_drop_glue_for_provider;
500 providers.queries.upstream_async_drop_glue_for = upstream_async_drop_glue_for_provider;
501 providers.queries.wasm_import_module_map = wasm_import_module_map;
502 providers.extern_queries.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
503 providers.extern_queries.upstream_monomorphizations_for =
504 upstream_monomorphizations_for_provider;
505}
506
507pub(crate) fn allocator_shim_symbols(
508 tcx: TyCtxt<'_>,
509 kind: AllocatorKind,
510) -> impl Iterator<Item = (String, SymbolExportKind)> {
511 allocator_shim_contents(tcx, kind)
512 .into_iter()
513 .map(move |method| mangle_internal_symbol(tcx, global_fn_name(method.name).as_str()))
514 .chain([mangle_internal_symbol(tcx, NO_ALLOC_SHIM_IS_UNSTABLE)])
515 .map(move |symbol_name| {
516 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
517
518 (
519 symbol_export::exporting_symbol_name_for_instance_in_crate(
520 tcx,
521 exported_symbol,
522 LOCAL_CRATE,
523 ),
524 SymbolExportKind::Text,
525 )
526 })
527}
528
529fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
530 let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
536 let is_extern = codegen_fn_attrs.contains_extern_indicator();
537 let std_internal =
538 codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
539 let eii = codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM);
540
541 if is_extern && !std_internal && !eii {
542 let target = &tcx.sess.target.llvm_target;
543 if target.contains("emscripten") {
546 if let DefKind::Static { .. } = tcx.def_kind(sym_def_id) {
547 return SymbolExportLevel::Rust;
548 }
549 }
550
551 SymbolExportLevel::C
552 } else {
553 SymbolExportLevel::Rust
554 }
555}
556
557pub(crate) fn symbol_name_for_instance_in_crate<'tcx>(
559 tcx: TyCtxt<'tcx>,
560 symbol: ExportedSymbol<'tcx>,
561 instantiating_crate: CrateNum,
562) -> String {
563 if instantiating_crate == LOCAL_CRATE {
566 return symbol.symbol_name_for_local_instance(tcx).to_string();
567 }
568
569 match symbol {
572 ExportedSymbol::NonGeneric(def_id) => {
573 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
574 tcx,
575 Instance::mono(tcx, def_id),
576 instantiating_crate,
577 )
578 }
579 ExportedSymbol::Generic(def_id, args) => {
580 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
581 tcx,
582 Instance::new_raw(def_id, args),
583 instantiating_crate,
584 )
585 }
586 ExportedSymbol::ThreadLocalShim(def_id) => {
587 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
588 tcx,
589 ty::Instance {
590 def: ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(def_id)),
591 args: ty::GenericArgs::empty(),
592 },
593 instantiating_crate,
594 )
595 }
596 ExportedSymbol::DropGlue(ty) => rustc_symbol_mangling::symbol_name_for_instance_in_crate(
597 tcx,
598 Instance::resolve_drop_glue(tcx, ty),
599 instantiating_crate,
600 ),
601 ExportedSymbol::AsyncDropGlueCtorShim(ty) => {
602 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
603 tcx,
604 Instance::resolve_async_drop_in_place(tcx, ty),
605 instantiating_crate,
606 )
607 }
608 ExportedSymbol::AsyncDropGlue(def_id, ty) => {
609 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
610 tcx,
611 Instance::resolve_async_drop_in_place_poll(tcx, def_id, ty),
612 instantiating_crate,
613 )
614 }
615 ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),
616 }
617}
618
619fn calling_convention_for_symbol<'tcx>(
620 tcx: TyCtxt<'tcx>,
621 symbol: ExportedSymbol<'tcx>,
622) -> (CanonAbi, &'tcx [rustc_target::callconv::ArgAbi<'tcx, Ty<'tcx>>]) {
623 let instance = match symbol {
624 ExportedSymbol::NonGeneric(def_id) | ExportedSymbol::Generic(def_id, _)
625 if tcx.is_static(def_id) =>
626 {
627 None
628 }
629 ExportedSymbol::NonGeneric(def_id) => Some(Instance::mono(tcx, def_id)),
630 ExportedSymbol::Generic(def_id, args) => Some(Instance::new_raw(def_id, args)),
631 ExportedSymbol::DropGlue(..) => None,
634 ExportedSymbol::AsyncDropGlueCtorShim(..) => None,
637 ExportedSymbol::AsyncDropGlue(..) => None,
638 ExportedSymbol::NoDefId(..) => None,
640 ExportedSymbol::ThreadLocalShim(..) => None,
642 };
643
644 instance
645 .map(|i| {
646 tcx.fn_abi_of_instance(
647 ty::TypingEnv::fully_monomorphized().as_query_input((i, ty::List::empty())),
648 )
649 .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"))
650 })
651 .map(|fnabi| (fnabi.conv, &fnabi.args[..]))
652 .unwrap_or((CanonAbi::Rust, &[]))
654}
655
656pub(crate) fn linking_symbol_name_for_instance_in_crate<'tcx>(
660 tcx: TyCtxt<'tcx>,
661 symbol: ExportedSymbol<'tcx>,
662 export_kind: SymbolExportKind,
663 instantiating_crate: CrateNum,
664) -> String {
665 let mut undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
666
667 if let Some(name) = maybe_emutls_symbol_name(tcx, symbol, &undecorated) {
670 return name;
671 }
672
673 let target = &tcx.sess.target;
674 if !target.is_like_windows {
675 return undecorated;
678 }
679
680 let prefix = match target.arch {
681 Arch::X86 => Some('_'),
682 Arch::X86_64 => None,
683 Arch::Arm64EC if export_kind == SymbolExportKind::Text => Some('#'),
685 _ => return undecorated,
687 };
688
689 let (callconv, args) = calling_convention_for_symbol(tcx, symbol);
690
691 let (prefix, suffix) = match callconv {
694 CanonAbi::X86(X86Call::Fastcall) => ("@", "@"),
695 CanonAbi::X86(X86Call::Stdcall) => ("_", "@"),
696 CanonAbi::X86(X86Call::Vectorcall) => ("", "@@"),
697 _ => {
698 if let Some(prefix) = prefix {
699 undecorated.insert(0, prefix);
700 }
701 return undecorated;
702 }
703 };
704
705 let args_in_bytes: u64 = args
706 .iter()
707 .map(|abi| abi.layout.size.bytes().next_multiple_of(target.pointer_width as u64 / 8))
708 .sum();
709 ::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}")
710}
711
712pub(crate) fn exporting_symbol_name_for_instance_in_crate<'tcx>(
713 tcx: TyCtxt<'tcx>,
714 symbol: ExportedSymbol<'tcx>,
715 cnum: CrateNum,
716) -> String {
717 let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, cnum);
718 maybe_emutls_symbol_name(tcx, symbol, &undecorated).unwrap_or(undecorated)
719}
720
721pub(crate) fn extend_exported_symbols<'tcx>(
725 symbols: &mut Vec<SymbolExport>,
726 tcx: TyCtxt<'tcx>,
727 symbol: ExportedSymbol<'tcx>,
728 instantiating_crate: CrateNum,
729) {
730 let (callconv, _) = calling_convention_for_symbol(tcx, symbol);
731
732 if callconv != CanonAbi::GpuKernel || tcx.sess.target.os != Os::AmdHsa {
733 return;
734 }
735
736 let undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
737
738 symbols.push(SymbolExport::new(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.kd", undecorated))
})format!("{undecorated}.kd"), SymbolExportKind::Data));
742}
743
744fn maybe_emutls_symbol_name<'tcx>(
745 tcx: TyCtxt<'tcx>,
746 symbol: ExportedSymbol<'tcx>,
747 undecorated: &str,
748) -> Option<String> {
749 if #[allow(non_exhaustive_omitted_patterns)] match tcx.sess.tls_model() {
TlsModel::Emulated => true,
_ => false,
}matches!(tcx.sess.tls_model(), TlsModel::Emulated)
750 && let ExportedSymbol::NonGeneric(def_id) = symbol
751 && tcx.is_thread_local_static(def_id)
752 {
753 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("__emutls_v.{0}", undecorated))
})format!("__emutls_v.{undecorated}"))
756 } else {
757 None
758 }
759}
760
761fn wasm_import_module_map(tcx: TyCtxt<'_>, cnum: CrateNum) -> DefIdMap<String> {
762 let native_libs = tcx.native_libraries(cnum);
766
767 let def_id_to_native_lib = native_libs
768 .iter()
769 .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
770 .collect::<DefIdMap<_>>();
771
772 let mut ret = DefIdMap::default();
773 for (def_id, lib) in tcx.foreign_modules(cnum).iter() {
774 let module = def_id_to_native_lib.get(def_id).and_then(|s| s.wasm_import_module());
775 let Some(module) = module else { continue };
776 ret.extend(lib.foreign_items.iter().map(|id| {
777 {
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);
778 (*id, module.to_string())
779 }));
780 }
781
782 ret
783}
784
785pub fn escape_symbol_name(tcx: TyCtxt<'_>, symbol: &str, span: Span) -> String {
786 use rustc_target::spec::{Arch, BinaryFormat};
788 if !symbol.is_empty()
789 && 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' | '_' | '$' | '.'))
790 {
791 return symbol.to_string();
792 }
793 if tcx.sess.target.binary_format == BinaryFormat::Xcoff {
794 tcx.sess.dcx().span_fatal(
795 span,
796 ::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!(
797 "symbol escaping is not supported for the binary format {}",
798 tcx.sess.target.binary_format
799 ),
800 );
801 }
802 if tcx.sess.target.arch == Arch::Nvptx64 {
803 tcx.sess.dcx().span_fatal(
804 span,
805 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("symbol escaping is not supported for the architecture {0}",
tcx.sess.target.arch))
})format!(
806 "symbol escaping is not supported for the architecture {}",
807 tcx.sess.target.arch
808 ),
809 );
810 }
811 let mut escaped_symbol = String::new();
812 escaped_symbol.push('\"');
813 for c in symbol.chars() {
814 match c {
815 '\n' => escaped_symbol.push_str("\\\n"),
816 '"' => escaped_symbol.push_str("\\\""),
817 '\\' => escaped_symbol.push_str("\\\\"),
818 c => escaped_symbol.push(c),
819 }
820 }
821 escaped_symbol.push('\"');
822 escaped_symbol
823}