]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/back/symbol_export.rs
Auto merge of #104535 - mikebenfield:discr-fix, r=pnkfelix
[rust.git] / compiler / rustc_codegen_ssa / src / back / symbol_export.rs
1 use std::collections::hash_map::Entry::*;
2
3 use rustc_ast::expand::allocator::ALLOCATOR_METHODS;
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_hir as hir;
6 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LOCAL_CRATE};
7 use rustc_hir::Node;
8 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
9 use rustc_middle::middle::exported_symbols::{
10     metadata_symbol_name, ExportedSymbol, SymbolExportInfo, SymbolExportKind, SymbolExportLevel,
11 };
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;
18
19 pub fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
20     crates_export_threshold(&tcx.sess.crate_types())
21 }
22
23 fn crate_export_threshold(crate_type: CrateType) -> SymbolExportLevel {
24     match crate_type {
25         CrateType::Executable | CrateType::Staticlib | CrateType::ProcMacro | CrateType::Cdylib => {
26             SymbolExportLevel::C
27         }
28         CrateType::Rlib | CrateType::Dylib => SymbolExportLevel::Rust,
29     }
30 }
31
32 pub fn crates_export_threshold(crate_types: &[CrateType]) -> SymbolExportLevel {
33     if crate_types
34         .iter()
35         .any(|&crate_type| crate_export_threshold(crate_type) == SymbolExportLevel::Rust)
36     {
37         SymbolExportLevel::Rust
38     } else {
39         SymbolExportLevel::C
40     }
41 }
42
43 fn reachable_non_generics_provider(tcx: TyCtxt<'_>, cnum: CrateNum) -> DefIdMap<SymbolExportInfo> {
44     assert_eq!(cnum, LOCAL_CRATE);
45
46     if !tcx.sess.opts.output_types.should_codegen() {
47         return Default::default();
48     }
49
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
56     // level instead.
57     let special_runtime_crate =
58         tcx.is_panic_runtime(LOCAL_CRATE) || tcx.is_compiler_builtins(LOCAL_CRATE);
59
60     let mut reachable_non_generics: DefIdMap<_> = tcx
61         .reachable_set(())
62         .iter()
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
66             // categories:
67             //
68             // 1. Those that are included statically via a static library
69             // 2. Those included otherwise (e.g., dynamically or via a framework)
70             //
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.
74             //
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)
80                 }
81
82                 // Only consider nodes that actually have exported symbols.
83                 Node::Item(&hir::Item {
84                     kind: hir::ItemKind::Static(..) | hir::ItemKind::Fn(..),
85                     ..
86                 })
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
92                         // indicator
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())
95                     {
96                         Some(def_id)
97                     } else {
98                         None
99                     }
100                 }
101
102                 _ => None,
103             }
104         })
105         .map(|def_id| {
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";
109
110             let export_level = if special_runtime_crate {
111                 SymbolExportLevel::Rust
112             } else {
113                 symbol_export_level(tcx, def_id.to_def_id())
114             };
115             let codegen_attrs = tcx.codegen_fn_attrs(def_id.to_def_id());
116             debug!(
117                 "EXPORTED SYMBOL (local): {} ({:?})",
118                 tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())),
119                 export_level
120             );
121             (def_id.to_def_id(), SymbolExportInfo {
122                 level: export_level,
123                 kind: if tcx.is_static(def_id.to_def_id()) {
124                     if codegen_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
125                         SymbolExportKind::Tls
126                     } else {
127                         SymbolExportKind::Data
128                     }
129                 } else {
130                     SymbolExportKind::Text
131                 },
132                 used: codegen_attrs.flags.contains(CodegenFnAttrFlags::USED)
133                     || codegen_attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) || used,
134             })
135         })
136         .collect();
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             },
146         );
147     }
148
149     reachable_non_generics
150 }
151
152 fn is_reachable_non_generic_provider_local(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
153     let export_threshold = threshold(tcx);
154
155     if let Some(&info) = tcx.reachable_non_generics(def_id.krate).get(&def_id) {
156         info.level.is_below_threshold(export_threshold)
157     } else {
158         false
159     }
160 }
161
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)
164 }
165
166 fn exported_symbols_provider_local<'tcx>(
167     tcx: TyCtxt<'tcx>,
168     cnum: CrateNum,
169 ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] {
170     assert_eq!(cnum, LOCAL_CRATE);
171
172     if !tcx.sess.opts.output_types.should_codegen() {
173         return &[];
174     }
175
176     let mut symbols: Vec<_> = tcx
177         .reachable_non_generics(LOCAL_CRATE)
178         .iter()
179         .map(|(&def_id, &info)| (ExportedSymbol::NonGeneric(def_id), info))
180         .collect();
181
182     if tcx.entry_fn(()).is_some() {
183         let exported_symbol =
184             ExportedSymbol::NoDefId(SymbolName::new(tcx, tcx.sess.target.entry_name.as_ref()));
185
186         symbols.push((
187             exported_symbol,
188             SymbolExportInfo {
189                 level: SymbolExportLevel::C,
190                 kind: SymbolExportKind::Text,
191                 used: false,
192             },
193         ));
194     }
195
196     if tcx.allocator_kind(()).is_some() {
197         for symbol_name in ALLOCATOR_METHODS
198             .iter()
199             .map(|method| format!("__rust_{}", method.name))
200             .chain(["__rust_alloc_error_handler".to_string(), OomStrategy::SYMBOL.to_string()])
201         {
202             let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
203
204             symbols.push((
205                 exported_symbol,
206                 SymbolExportInfo {
207                     level: SymbolExportLevel::Rust,
208                     kind: SymbolExportKind::Text,
209                     used: false,
210                 },
211             ));
212         }
213
214         symbols.push((
215             ExportedSymbol::NoDefId(SymbolName::new(tcx, OomStrategy::SYMBOL)),
216             SymbolExportInfo {
217                 level: SymbolExportLevel::Rust,
218                 kind: SymbolExportKind::Text,
219                 used: false,
220             },
221         ));
222     }
223
224     if tcx.sess.instrument_coverage() || tcx.sess.opts.cg.profile_generate.enabled() {
225         // These are weak symbols that point to the profile version and the
226         // profile name, which need to be treated as exported so LTO doesn't nix
227         // them.
228         const PROFILER_WEAK_SYMBOLS: [&str; 2] =
229             ["__llvm_profile_raw_version", "__llvm_profile_filename"];
230
231         symbols.extend(PROFILER_WEAK_SYMBOLS.iter().map(|sym| {
232             let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, sym));
233             (
234                 exported_symbol,
235                 SymbolExportInfo {
236                     level: SymbolExportLevel::C,
237                     kind: SymbolExportKind::Data,
238                     used: false,
239                 },
240             )
241         }));
242     }
243
244     if tcx.sess.opts.unstable_opts.sanitizer.contains(SanitizerSet::MEMORY) {
245         let mut msan_weak_symbols = Vec::new();
246
247         // Similar to profiling, preserve weak msan symbol during LTO.
248         if tcx.sess.opts.unstable_opts.sanitizer_recover.contains(SanitizerSet::MEMORY) {
249             msan_weak_symbols.push("__msan_keep_going");
250         }
251
252         if tcx.sess.opts.unstable_opts.sanitizer_memory_track_origins != 0 {
253             msan_weak_symbols.push("__msan_track_origins");
254         }
255
256         symbols.extend(msan_weak_symbols.into_iter().map(|sym| {
257             let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, sym));
258             (
259                 exported_symbol,
260                 SymbolExportInfo {
261                     level: SymbolExportLevel::C,
262                     kind: SymbolExportKind::Data,
263                     used: false,
264                 },
265             )
266         }));
267     }
268
269     if tcx.sess.crate_types().contains(&CrateType::Dylib)
270         || tcx.sess.crate_types().contains(&CrateType::ProcMacro)
271     {
272         let symbol_name = metadata_symbol_name(tcx);
273         let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
274
275         symbols.push((
276             exported_symbol,
277             SymbolExportInfo {
278                 level: SymbolExportLevel::C,
279                 kind: SymbolExportKind::Data,
280                 used: true,
281             },
282         ));
283     }
284
285     if tcx.sess.opts.share_generics() && tcx.local_crate_exports_generics() {
286         use rustc_middle::mir::mono::{Linkage, MonoItem, Visibility};
287         use rustc_middle::ty::InstanceDef;
288
289         // Normally, we require that shared monomorphizations are not hidden,
290         // because if we want to re-use a monomorphization from a Rust dylib, it
291         // needs to be exported.
292         // However, on platforms that don't allow for Rust dylibs, having
293         // external linkage is enough for monomorphization to be linked to.
294         let need_visibility = tcx.sess.target.dynamic_linking && !tcx.sess.target.only_cdylib;
295
296         let (_, cgus) = tcx.collect_and_partition_mono_items(());
297
298         for (mono_item, &(linkage, visibility)) in cgus.iter().flat_map(|cgu| cgu.items().iter()) {
299             if linkage != Linkage::External {
300                 // We can only re-use things with external linkage, otherwise
301                 // we'll get a linker error
302                 continue;
303             }
304
305             if need_visibility && visibility == Visibility::Hidden {
306                 // If we potentially share things from Rust dylibs, they must
307                 // not be hidden
308                 continue;
309             }
310
311             match *mono_item {
312                 MonoItem::Fn(Instance { def: InstanceDef::Item(def), substs }) => {
313                     if substs.non_erasable_generics().next().is_some() {
314                         let symbol = ExportedSymbol::Generic(def.did, substs);
315                         symbols.push((
316                             symbol,
317                             SymbolExportInfo {
318                                 level: SymbolExportLevel::Rust,
319                                 kind: SymbolExportKind::Text,
320                                 used: false,
321                             },
322                         ));
323                     }
324                 }
325                 MonoItem::Fn(Instance { def: InstanceDef::DropGlue(_, Some(ty)), substs }) => {
326                     // A little sanity-check
327                     debug_assert_eq!(
328                         substs.non_erasable_generics().next(),
329                         Some(GenericArgKind::Type(ty))
330                     );
331                     symbols.push((
332                         ExportedSymbol::DropGlue(ty),
333                         SymbolExportInfo {
334                             level: SymbolExportLevel::Rust,
335                             kind: SymbolExportKind::Text,
336                             used: false,
337                         },
338                     ));
339                 }
340                 _ => {
341                     // Any other symbols don't qualify for sharing
342                 }
343             }
344         }
345     }
346
347     // Sort so we get a stable incr. comp. hash.
348     symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
349
350     tcx.arena.alloc_from_iter(symbols)
351 }
352
353 fn upstream_monomorphizations_provider(
354     tcx: TyCtxt<'_>,
355     (): (),
356 ) -> DefIdMap<FxHashMap<SubstsRef<'_>, CrateNum>> {
357     let cnums = tcx.crates(());
358
359     let mut instances: DefIdMap<FxHashMap<_, _>> = Default::default();
360
361     let drop_in_place_fn_def_id = tcx.lang_items().drop_in_place_fn();
362
363     for &cnum in cnums.iter() {
364         for (exported_symbol, _) in tcx.exported_symbols(cnum).iter() {
365             let (def_id, substs) = match *exported_symbol {
366                 ExportedSymbol::Generic(def_id, substs) => (def_id, substs),
367                 ExportedSymbol::DropGlue(ty) => {
368                     if let Some(drop_in_place_fn_def_id) = drop_in_place_fn_def_id {
369                         (drop_in_place_fn_def_id, tcx.intern_substs(&[ty.into()]))
370                     } else {
371                         // `drop_in_place` in place does not exist, don't try
372                         // to use it.
373                         continue;
374                     }
375                 }
376                 ExportedSymbol::NonGeneric(..) | ExportedSymbol::NoDefId(..) => {
377                     // These are no monomorphizations
378                     continue;
379                 }
380             };
381
382             let substs_map = instances.entry(def_id).or_default();
383
384             match substs_map.entry(substs) {
385                 Occupied(mut e) => {
386                     // If there are multiple monomorphizations available,
387                     // we select one deterministically.
388                     let other_cnum = *e.get();
389                     if tcx.stable_crate_id(other_cnum) > tcx.stable_crate_id(cnum) {
390                         e.insert(cnum);
391                     }
392                 }
393                 Vacant(e) => {
394                     e.insert(cnum);
395                 }
396             }
397         }
398     }
399
400     instances
401 }
402
403 fn upstream_monomorphizations_for_provider(
404     tcx: TyCtxt<'_>,
405     def_id: DefId,
406 ) -> Option<&FxHashMap<SubstsRef<'_>, CrateNum>> {
407     debug_assert!(!def_id.is_local());
408     tcx.upstream_monomorphizations(()).get(&def_id)
409 }
410
411 fn upstream_drop_glue_for_provider<'tcx>(
412     tcx: TyCtxt<'tcx>,
413     substs: SubstsRef<'tcx>,
414 ) -> Option<CrateNum> {
415     if let Some(def_id) = tcx.lang_items().drop_in_place_fn() {
416         tcx.upstream_monomorphizations_for(def_id).and_then(|monos| monos.get(&substs).cloned())
417     } else {
418         None
419     }
420 }
421
422 fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
423     !tcx.reachable_set(()).contains(&def_id)
424 }
425
426 pub fn provide(providers: &mut Providers) {
427     providers.reachable_non_generics = reachable_non_generics_provider;
428     providers.is_reachable_non_generic = is_reachable_non_generic_provider_local;
429     providers.exported_symbols = exported_symbols_provider_local;
430     providers.upstream_monomorphizations = upstream_monomorphizations_provider;
431     providers.is_unreachable_local_definition = is_unreachable_local_definition_provider;
432     providers.upstream_drop_glue_for = upstream_drop_glue_for_provider;
433     providers.wasm_import_module_map = wasm_import_module_map;
434 }
435
436 pub fn provide_extern(providers: &mut ExternProviders) {
437     providers.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
438     providers.upstream_monomorphizations_for = upstream_monomorphizations_for_provider;
439 }
440
441 fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
442     // We export anything that's not mangled at the "C" layer as it probably has
443     // to do with ABI concerns. We do not, however, apply such treatment to
444     // special symbols in the standard library for various plumbing between
445     // core/std/allocators/etc. For example symbols used to hook up allocation
446     // are not considered for export
447     let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
448     let is_extern = codegen_fn_attrs.contains_extern_indicator();
449     let std_internal =
450         codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
451
452     if is_extern && !std_internal {
453         let target = &tcx.sess.target.llvm_target;
454         // WebAssembly cannot export data symbols, so reduce their export level
455         if target.contains("emscripten") {
456             if let Some(Node::Item(&hir::Item { kind: hir::ItemKind::Static(..), .. })) =
457                 tcx.hir().get_if_local(sym_def_id)
458             {
459                 return SymbolExportLevel::Rust;
460             }
461         }
462
463         SymbolExportLevel::C
464     } else {
465         SymbolExportLevel::Rust
466     }
467 }
468
469 /// This is the symbol name of the given instance instantiated in a specific crate.
470 pub fn symbol_name_for_instance_in_crate<'tcx>(
471     tcx: TyCtxt<'tcx>,
472     symbol: ExportedSymbol<'tcx>,
473     instantiating_crate: CrateNum,
474 ) -> String {
475     // If this is something instantiated in the local crate then we might
476     // already have cached the name as a query result.
477     if instantiating_crate == LOCAL_CRATE {
478         return symbol.symbol_name_for_local_instance(tcx).to_string();
479     }
480
481     // This is something instantiated in an upstream crate, so we have to use
482     // the slower (because uncached) version of computing the symbol name.
483     match symbol {
484         ExportedSymbol::NonGeneric(def_id) => {
485             rustc_symbol_mangling::symbol_name_for_instance_in_crate(
486                 tcx,
487                 Instance::mono(tcx, def_id),
488                 instantiating_crate,
489             )
490         }
491         ExportedSymbol::Generic(def_id, substs) => {
492             rustc_symbol_mangling::symbol_name_for_instance_in_crate(
493                 tcx,
494                 Instance::new(def_id, substs),
495                 instantiating_crate,
496             )
497         }
498         ExportedSymbol::DropGlue(ty) => rustc_symbol_mangling::symbol_name_for_instance_in_crate(
499             tcx,
500             Instance::resolve_drop_in_place(tcx, ty),
501             instantiating_crate,
502         ),
503         ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),
504     }
505 }
506
507 /// This is the symbol name of the given instance as seen by the linker.
508 ///
509 /// On 32-bit Windows symbols are decorated according to their calling conventions.
510 pub fn linking_symbol_name_for_instance_in_crate<'tcx>(
511     tcx: TyCtxt<'tcx>,
512     symbol: ExportedSymbol<'tcx>,
513     instantiating_crate: CrateNum,
514 ) -> String {
515     use rustc_target::abi::call::Conv;
516
517     let mut undecorated = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
518
519     let target = &tcx.sess.target;
520     if !target.is_like_windows {
521         // Mach-O has a global "_" suffix and `object` crate will handle it.
522         // ELF does not have any symbol decorations.
523         return undecorated;
524     }
525
526     let x86 = match &target.arch[..] {
527         "x86" => true,
528         "x86_64" => false,
529         // Only x86/64 use symbol decorations.
530         _ => return undecorated,
531     };
532
533     let instance = match symbol {
534         ExportedSymbol::NonGeneric(def_id) | ExportedSymbol::Generic(def_id, _)
535             if tcx.is_static(def_id) =>
536         {
537             None
538         }
539         ExportedSymbol::NonGeneric(def_id) => Some(Instance::mono(tcx, def_id)),
540         ExportedSymbol::Generic(def_id, substs) => Some(Instance::new(def_id, substs)),
541         // DropGlue always use the Rust calling convention and thus follow the target's default
542         // symbol decoration scheme.
543         ExportedSymbol::DropGlue(..) => None,
544         // NoDefId always follow the target's default symbol decoration scheme.
545         ExportedSymbol::NoDefId(..) => None,
546     };
547
548     let (conv, args) = instance
549         .map(|i| {
550             tcx.fn_abi_of_instance(ty::ParamEnv::reveal_all().and((i, ty::List::empty())))
551                 .unwrap_or_else(|_| bug!("fn_abi_of_instance({i:?}) failed"))
552         })
553         .map(|fnabi| (fnabi.conv, &fnabi.args[..]))
554         .unwrap_or((Conv::Rust, &[]));
555
556     // Decorate symbols with prefixes, suffixes and total number of bytes of arguments.
557     // Reference: https://docs.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170
558     let (prefix, suffix) = match conv {
559         Conv::X86Fastcall => ("@", "@"),
560         Conv::X86Stdcall => ("_", "@"),
561         Conv::X86VectorCall => ("", "@@"),
562         _ => {
563             if x86 {
564                 undecorated.insert(0, '_');
565             }
566             return undecorated;
567         }
568     };
569
570     let args_in_bytes: u64 = args
571         .iter()
572         .map(|abi| abi.layout.size.bytes().next_multiple_of(target.pointer_width as u64 / 8))
573         .sum();
574     format!("{prefix}{undecorated}{suffix}{args_in_bytes}")
575 }
576
577 fn wasm_import_module_map(tcx: TyCtxt<'_>, cnum: CrateNum) -> FxHashMap<DefId, String> {
578     // Build up a map from DefId to a `NativeLib` structure, where
579     // `NativeLib` internally contains information about
580     // `#[link(wasm_import_module = "...")]` for example.
581     let native_libs = tcx.native_libraries(cnum);
582
583     let def_id_to_native_lib = native_libs
584         .iter()
585         .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
586         .collect::<FxHashMap<_, _>>();
587
588     let mut ret = FxHashMap::default();
589     for (def_id, lib) in tcx.foreign_modules(cnum).iter() {
590         let module = def_id_to_native_lib.get(&def_id).and_then(|s| s.wasm_import_module);
591         let Some(module) = module else { continue };
592         ret.extend(lib.foreign_items.iter().map(|id| {
593             assert_eq!(id.krate, cnum);
594             (*id, module.to_string())
595         }));
596     }
597
598     ret
599 }