1 use std::collections::hash_map::Entry::*;
3 use rustc_ast::expand::allocator::ALLOCATOR_METHODS;
4 use rustc_data_structures::fx::FxHashMap;
6 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LOCAL_CRATE};
8 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
9 use rustc_middle::middle::exported_symbols::{
10 metadata_symbol_name, ExportedSymbol, SymbolExportInfo, SymbolExportKind, SymbolExportLevel,
12 use rustc_middle::ty::query::{ExternProviders, Providers};
13 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
14 use rustc_middle::ty::Instance;
15 use rustc_middle::ty::{self, SymbolName, TyCtxt};
16 use rustc_session::config::{CrateType, OomStrategy};
17 use rustc_target::spec::SanitizerSet;
19 pub fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
20 crates_export_threshold(&tcx.sess.crate_types())
23 fn crate_export_threshold(crate_type: CrateType) -> SymbolExportLevel {
25 CrateType::Executable | CrateType::Staticlib | CrateType::ProcMacro | CrateType::Cdylib => {
28 CrateType::Rlib | CrateType::Dylib => SymbolExportLevel::Rust,
32 pub fn crates_export_threshold(crate_types: &[CrateType]) -> SymbolExportLevel {
35 .any(|&crate_type| crate_export_threshold(crate_type) == SymbolExportLevel::Rust)
37 SymbolExportLevel::Rust
43 fn reachable_non_generics_provider(tcx: TyCtxt<'_>, cnum: CrateNum) -> DefIdMap<SymbolExportInfo> {
44 assert_eq!(cnum, LOCAL_CRATE);
46 if !tcx.sess.opts.output_types.should_codegen() {
47 return Default::default();
50 // Check to see if this crate is a "special runtime crate". These
51 // crates, implementation details of the standard library, typically
52 // have a bunch of `pub extern` and `#[no_mangle]` functions as the
53 // ABI between them. We don't want their symbols to have a `C`
54 // export level, however, as they're just implementation details.
55 // Down below we'll hardwire all of the symbols to the `Rust` export
57 let special_runtime_crate =
58 tcx.is_panic_runtime(LOCAL_CRATE) || tcx.is_compiler_builtins(LOCAL_CRATE);
60 let mut reachable_non_generics: DefIdMap<_> = tcx
63 .filter_map(|&def_id| {
64 // We want to ignore some FFI functions that are not exposed from
65 // this crate. Reachable FFI functions can be lumped into two
68 // 1. Those that are included statically via a static library
69 // 2. Those included otherwise (e.g., dynamically or via a framework)
71 // Although our LLVM module is not literally emitting code for the
72 // statically included symbols, it's an export of our library which
73 // needs to be passed on to the linker and encoded in the metadata.
75 // As a result, if this id is an FFI item (foreign item) then we only
76 // let it through if it's included statically.
77 match tcx.hir().get_by_def_id(def_id) {
78 Node::ForeignItem(..) => {
79 tcx.native_library(def_id).map_or(false, |library| library.kind.is_statically_included()).then_some(def_id)
82 // Only consider nodes that actually have exported symbols.
83 Node::Item(&hir::Item {
84 kind: hir::ItemKind::Static(..) | hir::ItemKind::Fn(..),
87 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
88 let generics = tcx.generics_of(def_id);
89 if !generics.requires_monomorphization(tcx)
90 // Functions marked with #[inline] are codegened with "internal"
91 // linkage and are not exported unless marked with an extern
93 && (!Instance::mono(tcx, def_id.to_def_id()).def.generates_cgu_internal_copy(tcx)
94 || tcx.codegen_fn_attrs(def_id.to_def_id()).contains_extern_indicator())
106 // We won't link right if this symbol is stripped during LTO.
107 let name = tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())).name;
108 let used = name == "rust_eh_personality";
110 let export_level = if special_runtime_crate {
111 SymbolExportLevel::Rust
113 symbol_export_level(tcx, def_id.to_def_id())
115 let codegen_attrs = tcx.codegen_fn_attrs(def_id.to_def_id());
117 "EXPORTED SYMBOL (local): {} ({:?})",
118 tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())),
121 (def_id.to_def_id(), SymbolExportInfo {
123 kind: if tcx.is_static(def_id.to_def_id()) {
124 if codegen_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
125 SymbolExportKind::Tls
127 SymbolExportKind::Data
130 SymbolExportKind::Text
132 used: codegen_attrs.flags.contains(CodegenFnAttrFlags::USED)
133 || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) || used,
138 if let Some(id) = tcx.proc_macro_decls_static(()) {
139 reachable_non_generics.insert(
142 level: SymbolExportLevel::C,
143 kind: SymbolExportKind::Data,
149 reachable_non_generics
152 fn is_reachable_non_generic_provider_local(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
153 let export_threshold = threshold(tcx);
155 if let Some(&info) = tcx.reachable_non_generics(def_id.krate).get(&def_id) {
156 info.level.is_below_threshold(export_threshold)
162 fn is_reachable_non_generic_provider_extern(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
163 tcx.reachable_non_generics(def_id.krate).contains_key(&def_id)
166 fn exported_symbols_provider_local<'tcx>(
169 ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
170 assert_eq!(cnum, LOCAL_CRATE);
172 if !tcx.sess.opts.output_types.should_codegen() {
176 let mut symbols: Vec<_> = tcx
177 .reachable_non_generics(LOCAL_CRATE)
179 .map(|(&def_id, &info)| (ExportedSymbol::NonGeneric(def_id), info))
182 if tcx.entry_fn(()).is_some() {
183 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, "main"));
188 level: SymbolExportLevel::C,
189 kind: SymbolExportKind::Text,
195 if tcx.allocator_kind(()).is_some() {
196 for method in ALLOCATOR_METHODS {
197 let symbol_name = format!("__rust_{}", method.name);
198 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
203 level: SymbolExportLevel::Rust,
204 kind: SymbolExportKind::Text,
211 ExportedSymbol::NoDefId(SymbolName::new(tcx, OomStrategy::SYMBOL)),
213 level: SymbolExportLevel::Rust,
214 kind: SymbolExportKind::Text,
220 if tcx.sess.instrument_coverage() || tcx.sess.opts.cg.profile_generate.enabled() {
221 // These are weak symbols that point to the profile version and the
222 // profile name, which need to be treated as exported so LTO doesn't nix
224 const PROFILER_WEAK_SYMBOLS: [&str; 2] =
225 ["__llvm_profile_raw_version", "__llvm_profile_filename"];
227 symbols.extend(PROFILER_WEAK_SYMBOLS.iter().map(|sym| {
228 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, sym));
232 level: SymbolExportLevel::C,
233 kind: SymbolExportKind::Data,
240 if tcx.sess.opts.unstable_opts.sanitizer.contains(SanitizerSet::MEMORY) {
241 let mut msan_weak_symbols = Vec::new();
243 // Similar to profiling, preserve weak msan symbol during LTO.
244 if tcx.sess.opts.unstable_opts.sanitizer_recover.contains(SanitizerSet::MEMORY) {
245 msan_weak_symbols.push("__msan_keep_going");
248 if tcx.sess.opts.unstable_opts.sanitizer_memory_track_origins != 0 {
249 msan_weak_symbols.push("__msan_track_origins");
252 symbols.extend(msan_weak_symbols.into_iter().map(|sym| {
253 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, sym));
257 level: SymbolExportLevel::C,
258 kind: SymbolExportKind::Data,
265 if tcx.sess.crate_types().contains(&CrateType::Dylib)
266 || tcx.sess.crate_types().contains(&CrateType::ProcMacro)
268 let symbol_name = metadata_symbol_name(tcx);
269 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
274 level: SymbolExportLevel::C,
275 kind: SymbolExportKind::Data,
281 if tcx.sess.opts.share_generics() && tcx.local_crate_exports_generics() {
282 use rustc_middle::mir::mono::{Linkage, MonoItem, Visibility};
283 use rustc_middle::ty::InstanceDef;
285 // Normally, we require that shared monomorphizations are not hidden,
286 // because if we want to re-use a monomorphization from a Rust dylib, it
287 // needs to be exported.
288 // However, on platforms that don't allow for Rust dylibs, having
289 // external linkage is enough for monomorphization to be linked to.
290 let need_visibility = tcx.sess.target.dynamic_linking && !tcx.sess.target.only_cdylib;
292 let (_, cgus) = tcx.collect_and_partition_mono_items(());
294 for (mono_item, &(linkage, visibility)) in cgus.iter().flat_map(|cgu| cgu.items().iter()) {
295 if linkage != Linkage::External {
296 // We can only re-use things with external linkage, otherwise
297 // we'll get a linker error
301 if need_visibility && visibility == Visibility::Hidden {
302 // If we potentially share things from Rust dylibs, they must
308 MonoItem::Fn(Instance { def: InstanceDef::Item(def), substs }) => {
309 if substs.non_erasable_generics().next().is_some() {
310 let symbol = ExportedSymbol::Generic(def.did, substs);
314 level: SymbolExportLevel::Rust,
315 kind: SymbolExportKind::Text,
321 MonoItem::Fn(Instance { def: InstanceDef::DropGlue(_, Some(ty)), substs }) => {
322 // A little sanity-check
324 substs.non_erasable_generics().next(),
325 Some(GenericArgKind::Type(ty))
328 ExportedSymbol::DropGlue(ty),
330 level: SymbolExportLevel::Rust,
331 kind: SymbolExportKind::Text,
337 // Any other symbols don't qualify for sharing
343 // Sort so we get a stable incr. comp. hash.
344 symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
346 tcx.arena.alloc_from_iter(symbols)
349 fn upstream_monomorphizations_provider(
352 ) -> DefIdMap<FxHashMap<SubstsRef<'_>, CrateNum>> {
353 let cnums = tcx.crates(());
355 let mut instances: DefIdMap<FxHashMap<_, _>> = Default::default();
357 let drop_in_place_fn_def_id = tcx.lang_items().drop_in_place_fn();
359 for &cnum in cnums.iter() {
360 for (exported_symbol, _) in tcx.exported_symbols(cnum).iter() {
361 let (def_id, substs) = match *exported_symbol {
362 ExportedSymbol::Generic(def_id, substs) => (def_id, substs),
363 ExportedSymbol::DropGlue(ty) => {
364 if let Some(drop_in_place_fn_def_id) = drop_in_place_fn_def_id {
365 (drop_in_place_fn_def_id, tcx.intern_substs(&[ty.into()]))
367 // `drop_in_place` in place does not exist, don't try
372 ExportedSymbol::NonGeneric(..) | ExportedSymbol::NoDefId(..) => {
373 // These are no monomorphizations
378 let substs_map = instances.entry(def_id).or_default();
380 match substs_map.entry(substs) {
382 // If there are multiple monomorphizations available,
383 // we select one deterministically.
384 let other_cnum = *e.get();
385 if tcx.stable_crate_id(other_cnum) > tcx.stable_crate_id(cnum) {
399 fn upstream_monomorphizations_for_provider(
402 ) -> Option<&FxHashMap<SubstsRef<'_>, CrateNum>> {
403 debug_assert!(!def_id.is_local());
404 tcx.upstream_monomorphizations(()).get(&def_id)
407 fn upstream_drop_glue_for_provider<'tcx>(
409 substs: SubstsRef<'tcx>,
410 ) -> Option<CrateNum> {
411 if let Some(def_id) = tcx.lang_items().drop_in_place_fn() {
412 tcx.upstream_monomorphizations_for(def_id).and_then(|monos| monos.get(&substs).cloned())
418 fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
419 !tcx.reachable_set(()).contains(&def_id)
422 pub fn provide(providers: &mut Providers) {
423 providers.reachable_non_generics = reachable_non_generics_provider;
424 providers.is_reachable_non_generic = is_reachable_non_generic_provider_local;
425 providers.exported_symbols = exported_symbols_provider_local;
426 providers.upstream_monomorphizations = upstream_monomorphizations_provider;
427 providers.is_unreachable_local_definition = is_unreachable_local_definition_provider;
428 providers.upstream_drop_glue_for = upstream_drop_glue_for_provider;
429 providers.wasm_import_module_map = wasm_import_module_map;
432 pub fn provide_extern(providers: &mut ExternProviders) {
433 providers.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
434 providers.upstream_monomorphizations_for = upstream_monomorphizations_for_provider;
437 fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
438 // We export anything that's not mangled at the "C" layer as it probably has
439 // to do with ABI concerns. We do not, however, apply such treatment to
440 // special symbols in the standard library for various plumbing between
441 // core/std/allocators/etc. For example symbols used to hook up allocation
442 // are not considered for export
443 let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
444 let is_extern = codegen_fn_attrs.contains_extern_indicator();
446 codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
448 if is_extern && !std_internal {
449 let target = &tcx.sess.target.llvm_target;
450 // WebAssembly cannot export data symbols, so reduce their export level
451 if target.contains("emscripten") {
452 if let Some(Node::Item(&hir::Item { kind: hir::ItemKind::Static(..), .. })) =
453 tcx.hir().get_if_local(sym_def_id)
455 return SymbolExportLevel::Rust;
461 SymbolExportLevel::Rust
465 /// This is the symbol name of the given instance instantiated in a specific crate.
466 pub fn symbol_name_for_instance_in_crate<'tcx>(
468 symbol: ExportedSymbol<'tcx>,
469 instantiating_crate: CrateNum,
471 // If this is something instantiated in the local crate then we might
472 // already have cached the name as a query result.
473 if instantiating_crate == LOCAL_CRATE {
474 return symbol.symbol_name_for_local_instance(tcx).to_string();
477 // This is something instantiated in an upstream crate, so we have to use
478 // the slower (because uncached) version of computing the symbol name.
480 ExportedSymbol::NonGeneric(def_id) => {
481 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
483 Instance::mono(tcx, def_id),
487 ExportedSymbol::Generic(def_id, substs) => {
488 rustc_symbol_mangling::symbol_name_for_instance_in_crate(
490 Instance::new(def_id, substs),
494 ExportedSymbol::DropGlue(ty) => rustc_symbol_mangling::symbol_name_for_instance_in_crate(
496 Instance::resolve_drop_in_place(tcx, ty),
499 ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),
503 /// This is the symbol name of the given instance as seen by the linker.
505 /// On 32-bit Windows symbols are decorated according to their calling conventions.
506 pub fn linking_symbol_name_for_instance_in_crate<'tcx>(
508 symbol: ExportedSymbol<'tcx>,
509 instantiating_crate: CrateNum,
511 use rustc_target::abi::call::Conv;
513 let mut undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
515 let target = &tcx.sess.target;
516 if !target.is_like_windows {
517 // Mach-O has a global "_" suffix and `object` crate will handle it.
518 // ELF does not have any symbol decorations.
522 let x86 = match &target.arch[..] {
525 // Only x86/64 use symbol decorations.
526 _ => return undecorated,
529 let instance = match symbol {
530 ExportedSymbol::NonGeneric(def_id) | ExportedSymbol::Generic(def_id, _)
531 if tcx.is_static(def_id) =>
535 ExportedSymbol::NonGeneric(def_id) => Some(Instance::mono(tcx, def_id)),
536 ExportedSymbol::Generic(def_id, substs) => Some(Instance::new(def_id, substs)),
537 // DropGlue always use the Rust calling convention and thus follow the target's default
538 // symbol decoration scheme.
539 ExportedSymbol::DropGlue(..) => None,
540 // NoDefId always follow the target's default symbol decoration scheme.
541 ExportedSymbol::NoDefId(..) => None,
544 let (conv, args) = instance
546 tcx.fn_abi_of_instance(ty::ParamEnv::reveal_all().and((i, ty::List::empty())))
547 .unwrap_or_else(|_| bug!("fn_abi_of_instance({i:?}) failed"))
549 .map(|fnabi| (fnabi.conv, &fnabi.args[..]))
550 .unwrap_or((Conv::Rust, &[]));
552 // Decorate symbols with prefixes, suffixes and total number of bytes of arguments.
553 // Reference: https://docs.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170
554 let (prefix, suffix) = match conv {
555 Conv::X86Fastcall => ("@", "@"),
556 Conv::X86Stdcall => ("_", "@"),
557 Conv::X86VectorCall => ("", "@@"),
560 undecorated.insert(0, '_');
566 let args_in_bytes: u64 = args
568 .map(|abi| abi.layout.size.bytes().next_multiple_of(target.pointer_width as u64 / 8))
570 format!("{prefix}{undecorated}{suffix}{args_in_bytes}")
573 fn wasm_import_module_map(tcx: TyCtxt<'_>, cnum: CrateNum) -> FxHashMap<DefId, String> {
574 // Build up a map from DefId to a `NativeLib` structure, where
575 // `NativeLib` internally contains information about
576 // `#[link(wasm_import_module = "...")]` for example.
577 let native_libs = tcx.native_libraries(cnum);
579 let def_id_to_native_lib = native_libs
581 .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
582 .collect::<FxHashMap<_, _>>();
584 let mut ret = FxHashMap::default();
585 for (def_id, lib) in tcx.foreign_modules(cnum).iter() {
586 let module = def_id_to_native_lib.get(&def_id).and_then(|s| s.wasm_import_module);
587 let Some(module) = module else { continue };
588 ret.extend(lib.foreign_items.iter().map(|id| {
589 assert_eq!(id.krate, cnum);
590 (*id, module.to_string())