]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/back/symbol_export.rs
Rollup merge of #82683 - jturner314:int-div-rem-doc-panic, r=nikomatsakis
[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::fingerprint::Fingerprint;
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_hir as hir;
7 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, CRATE_DEF_INDEX, LOCAL_CRATE};
8 use rustc_hir::Node;
9 use rustc_index::vec::IndexVec;
10 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
11 use rustc_middle::middle::exported_symbols::{
12     metadata_symbol_name, ExportedSymbol, SymbolExportLevel,
13 };
14 use rustc_middle::ty::query::Providers;
15 use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
16 use rustc_middle::ty::Instance;
17 use rustc_middle::ty::{SymbolName, TyCtxt};
18 use rustc_session::config::{CrateType, SanitizerSet};
19
20 pub fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
21     crates_export_threshold(&tcx.sess.crate_types())
22 }
23
24 fn crate_export_threshold(crate_type: CrateType) -> SymbolExportLevel {
25     match crate_type {
26         CrateType::Executable | CrateType::Staticlib | CrateType::ProcMacro | CrateType::Cdylib => {
27             SymbolExportLevel::C
28         }
29         CrateType::Rlib | CrateType::Dylib => SymbolExportLevel::Rust,
30     }
31 }
32
33 pub fn crates_export_threshold(crate_types: &[CrateType]) -> SymbolExportLevel {
34     if crate_types
35         .iter()
36         .any(|&crate_type| crate_export_threshold(crate_type) == SymbolExportLevel::Rust)
37     {
38         SymbolExportLevel::Rust
39     } else {
40         SymbolExportLevel::C
41     }
42 }
43
44 fn reachable_non_generics_provider(tcx: TyCtxt<'_>, cnum: CrateNum) -> DefIdMap<SymbolExportLevel> {
45     assert_eq!(cnum, LOCAL_CRATE);
46
47     if !tcx.sess.opts.output_types.should_codegen() {
48         return Default::default();
49     }
50
51     // Check to see if this crate is a "special runtime crate". These
52     // crates, implementation details of the standard library, typically
53     // have a bunch of `pub extern` and `#[no_mangle]` functions as the
54     // ABI between them. We don't want their symbols to have a `C`
55     // export level, however, as they're just implementation details.
56     // Down below we'll hardwire all of the symbols to the `Rust` export
57     // level instead.
58     let special_runtime_crate =
59         tcx.is_panic_runtime(LOCAL_CRATE) || tcx.is_compiler_builtins(LOCAL_CRATE);
60
61     let mut reachable_non_generics: DefIdMap<_> = tcx
62         .reachable_set(LOCAL_CRATE)
63         .iter()
64         .filter_map(|&def_id| {
65             // We want to ignore some FFI functions that are not exposed from
66             // this crate. Reachable FFI functions can be lumped into two
67             // categories:
68             //
69             // 1. Those that are included statically via a static library
70             // 2. Those included otherwise (e.g., dynamically or via a framework)
71             //
72             // Although our LLVM module is not literally emitting code for the
73             // statically included symbols, it's an export of our library which
74             // needs to be passed on to the linker and encoded in the metadata.
75             //
76             // As a result, if this id is an FFI item (foreign item) then we only
77             // let it through if it's included statically.
78             match tcx.hir().get(tcx.hir().local_def_id_to_hir_id(def_id)) {
79                 Node::ForeignItem(..) => {
80                     tcx.is_statically_included_foreign_item(def_id).then_some(def_id)
81                 }
82
83                 // Only consider nodes that actually have exported symbols.
84                 Node::Item(&hir::Item {
85                     kind: hir::ItemKind::Static(..) | hir::ItemKind::Fn(..),
86                     ..
87                 })
88                 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => {
89                     let generics = tcx.generics_of(def_id);
90                     if !generics.requires_monomorphization(tcx)
91                         // Functions marked with #[inline] are codegened with "internal"
92                         // linkage and are not exported unless marked with an extern
93                         // inidicator
94                         && (!Instance::mono(tcx, def_id.to_def_id()).def.generates_cgu_internal_copy(tcx)
95                             || tcx.codegen_fn_attrs(def_id.to_def_id()).contains_extern_indicator())
96                     {
97                         Some(def_id)
98                     } else {
99                         None
100                     }
101                 }
102
103                 _ => None,
104             }
105         })
106         .map(|def_id| {
107             let export_level = if special_runtime_crate {
108                 let name = tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())).name;
109                 // We can probably do better here by just ensuring that
110                 // it has hidden visibility rather than public
111                 // visibility, as this is primarily here to ensure it's
112                 // not stripped during LTO.
113                 //
114                 // In general though we won't link right if these
115                 // symbols are stripped, and LTO currently strips them.
116                 match name {
117                     "rust_eh_personality"
118                     | "rust_eh_register_frames"
119                     | "rust_eh_unregister_frames" =>
120                         SymbolExportLevel::C,
121                     _ => SymbolExportLevel::Rust,
122                 }
123             } else {
124                 symbol_export_level(tcx, def_id.to_def_id())
125             };
126             debug!(
127                 "EXPORTED SYMBOL (local): {} ({:?})",
128                 tcx.symbol_name(Instance::mono(tcx, def_id.to_def_id())),
129                 export_level
130             );
131             (def_id.to_def_id(), export_level)
132         })
133         .collect();
134
135     if let Some(id) = tcx.proc_macro_decls_static(LOCAL_CRATE) {
136         reachable_non_generics.insert(id, SymbolExportLevel::C);
137     }
138
139     if let Some(id) = tcx.plugin_registrar_fn(LOCAL_CRATE) {
140         reachable_non_generics.insert(id, SymbolExportLevel::C);
141     }
142
143     reachable_non_generics
144 }
145
146 fn is_reachable_non_generic_provider_local(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
147     let export_threshold = threshold(tcx);
148
149     if let Some(&level) = tcx.reachable_non_generics(def_id.krate).get(&def_id) {
150         level.is_below_threshold(export_threshold)
151     } else {
152         false
153     }
154 }
155
156 fn is_reachable_non_generic_provider_extern(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
157     tcx.reachable_non_generics(def_id.krate).contains_key(&def_id)
158 }
159
160 fn exported_symbols_provider_local(
161     tcx: TyCtxt<'tcx>,
162     cnum: CrateNum,
163 ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportLevel)] {
164     assert_eq!(cnum, LOCAL_CRATE);
165
166     if !tcx.sess.opts.output_types.should_codegen() {
167         return &[];
168     }
169
170     let mut symbols: Vec<_> = tcx
171         .reachable_non_generics(LOCAL_CRATE)
172         .iter()
173         .map(|(&def_id, &level)| (ExportedSymbol::NonGeneric(def_id), level))
174         .collect();
175
176     if tcx.entry_fn(LOCAL_CRATE).is_some() {
177         let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, "main"));
178
179         symbols.push((exported_symbol, SymbolExportLevel::C));
180     }
181
182     if tcx.allocator_kind().is_some() {
183         for method in ALLOCATOR_METHODS {
184             let symbol_name = format!("__rust_{}", method.name);
185             let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
186
187             symbols.push((exported_symbol, SymbolExportLevel::Rust));
188         }
189     }
190
191     if tcx.sess.opts.debugging_opts.instrument_coverage
192         || tcx.sess.opts.cg.profile_generate.enabled()
193     {
194         // These are weak symbols that point to the profile version and the
195         // profile name, which need to be treated as exported so LTO doesn't nix
196         // them.
197         const PROFILER_WEAK_SYMBOLS: [&str; 2] =
198             ["__llvm_profile_raw_version", "__llvm_profile_filename"];
199
200         symbols.extend(PROFILER_WEAK_SYMBOLS.iter().map(|sym| {
201             let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, sym));
202             (exported_symbol, SymbolExportLevel::C)
203         }));
204     }
205
206     if tcx.sess.opts.debugging_opts.sanitizer.contains(SanitizerSet::MEMORY) {
207         // Similar to profiling, preserve weak msan symbol during LTO.
208         const MSAN_WEAK_SYMBOLS: [&str; 2] = ["__msan_track_origins", "__msan_keep_going"];
209
210         symbols.extend(MSAN_WEAK_SYMBOLS.iter().map(|sym| {
211             let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, sym));
212             (exported_symbol, SymbolExportLevel::C)
213         }));
214     }
215
216     if tcx.sess.crate_types().contains(&CrateType::Dylib) {
217         let symbol_name = metadata_symbol_name(tcx);
218         let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &symbol_name));
219
220         symbols.push((exported_symbol, SymbolExportLevel::Rust));
221     }
222
223     if tcx.sess.opts.share_generics() && tcx.local_crate_exports_generics() {
224         use rustc_middle::mir::mono::{Linkage, MonoItem, Visibility};
225         use rustc_middle::ty::InstanceDef;
226
227         // Normally, we require that shared monomorphizations are not hidden,
228         // because if we want to re-use a monomorphization from a Rust dylib, it
229         // needs to be exported.
230         // However, on platforms that don't allow for Rust dylibs, having
231         // external linkage is enough for monomorphization to be linked to.
232         let need_visibility = tcx.sess.target.dynamic_linking && !tcx.sess.target.only_cdylib;
233
234         let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
235
236         for (mono_item, &(linkage, visibility)) in cgus.iter().flat_map(|cgu| cgu.items().iter()) {
237             if linkage != Linkage::External {
238                 // We can only re-use things with external linkage, otherwise
239                 // we'll get a linker error
240                 continue;
241             }
242
243             if need_visibility && visibility == Visibility::Hidden {
244                 // If we potentially share things from Rust dylibs, they must
245                 // not be hidden
246                 continue;
247             }
248
249             match *mono_item {
250                 MonoItem::Fn(Instance { def: InstanceDef::Item(def), substs }) => {
251                     if substs.non_erasable_generics().next().is_some() {
252                         let symbol = ExportedSymbol::Generic(def.did, substs);
253                         symbols.push((symbol, SymbolExportLevel::Rust));
254                     }
255                 }
256                 MonoItem::Fn(Instance { def: InstanceDef::DropGlue(_, Some(ty)), substs }) => {
257                     // A little sanity-check
258                     debug_assert_eq!(
259                         substs.non_erasable_generics().next(),
260                         Some(GenericArgKind::Type(ty))
261                     );
262                     symbols.push((ExportedSymbol::DropGlue(ty), SymbolExportLevel::Rust));
263                 }
264                 _ => {
265                     // Any other symbols don't qualify for sharing
266                 }
267             }
268         }
269     }
270
271     // Sort so we get a stable incr. comp. hash.
272     symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
273
274     tcx.arena.alloc_from_iter(symbols)
275 }
276
277 fn upstream_monomorphizations_provider(
278     tcx: TyCtxt<'_>,
279     cnum: CrateNum,
280 ) -> DefIdMap<FxHashMap<SubstsRef<'_>, CrateNum>> {
281     debug_assert!(cnum == LOCAL_CRATE);
282
283     let cnums = tcx.all_crate_nums(LOCAL_CRATE);
284
285     let mut instances: DefIdMap<FxHashMap<_, _>> = Default::default();
286
287     let cnum_stable_ids: IndexVec<CrateNum, Fingerprint> = {
288         let mut cnum_stable_ids = IndexVec::from_elem_n(Fingerprint::ZERO, cnums.len() + 1);
289
290         for &cnum in cnums.iter() {
291             cnum_stable_ids[cnum] =
292                 tcx.def_path_hash(DefId { krate: cnum, index: CRATE_DEF_INDEX }).0;
293         }
294
295         cnum_stable_ids
296     };
297
298     let drop_in_place_fn_def_id = tcx.lang_items().drop_in_place_fn();
299
300     for &cnum in cnums.iter() {
301         for (exported_symbol, _) in tcx.exported_symbols(cnum).iter() {
302             let (def_id, substs) = match *exported_symbol {
303                 ExportedSymbol::Generic(def_id, substs) => (def_id, substs),
304                 ExportedSymbol::DropGlue(ty) => {
305                     if let Some(drop_in_place_fn_def_id) = drop_in_place_fn_def_id {
306                         (drop_in_place_fn_def_id, tcx.intern_substs(&[ty.into()]))
307                     } else {
308                         // `drop_in_place` in place does not exist, don't try
309                         // to use it.
310                         continue;
311                     }
312                 }
313                 ExportedSymbol::NonGeneric(..) | ExportedSymbol::NoDefId(..) => {
314                     // These are no monomorphizations
315                     continue;
316                 }
317             };
318
319             let substs_map = instances.entry(def_id).or_default();
320
321             match substs_map.entry(substs) {
322                 Occupied(mut e) => {
323                     // If there are multiple monomorphizations available,
324                     // we select one deterministically.
325                     let other_cnum = *e.get();
326                     if cnum_stable_ids[other_cnum] > cnum_stable_ids[cnum] {
327                         e.insert(cnum);
328                     }
329                 }
330                 Vacant(e) => {
331                     e.insert(cnum);
332                 }
333             }
334         }
335     }
336
337     instances
338 }
339
340 fn upstream_monomorphizations_for_provider(
341     tcx: TyCtxt<'_>,
342     def_id: DefId,
343 ) -> Option<&FxHashMap<SubstsRef<'_>, CrateNum>> {
344     debug_assert!(!def_id.is_local());
345     tcx.upstream_monomorphizations(LOCAL_CRATE).get(&def_id)
346 }
347
348 fn upstream_drop_glue_for_provider<'tcx>(
349     tcx: TyCtxt<'tcx>,
350     substs: SubstsRef<'tcx>,
351 ) -> Option<CrateNum> {
352     if let Some(def_id) = tcx.lang_items().drop_in_place_fn() {
353         tcx.upstream_monomorphizations_for(def_id).and_then(|monos| monos.get(&substs).cloned())
354     } else {
355         None
356     }
357 }
358
359 fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
360     if let Some(def_id) = def_id.as_local() {
361         !tcx.reachable_set(LOCAL_CRATE).contains(&def_id)
362     } else {
363         bug!("is_unreachable_local_definition called with non-local DefId: {:?}", def_id)
364     }
365 }
366
367 pub fn provide(providers: &mut Providers) {
368     providers.reachable_non_generics = reachable_non_generics_provider;
369     providers.is_reachable_non_generic = is_reachable_non_generic_provider_local;
370     providers.exported_symbols = exported_symbols_provider_local;
371     providers.upstream_monomorphizations = upstream_monomorphizations_provider;
372     providers.is_unreachable_local_definition = is_unreachable_local_definition_provider;
373     providers.upstream_drop_glue_for = upstream_drop_glue_for_provider;
374 }
375
376 pub fn provide_extern(providers: &mut Providers) {
377     providers.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
378     providers.upstream_monomorphizations_for = upstream_monomorphizations_for_provider;
379 }
380
381 fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
382     // We export anything that's not mangled at the "C" layer as it probably has
383     // to do with ABI concerns. We do not, however, apply such treatment to
384     // special symbols in the standard library for various plumbing between
385     // core/std/allocators/etc. For example symbols used to hook up allocation
386     // are not considered for export
387     let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
388     let is_extern = codegen_fn_attrs.contains_extern_indicator();
389     let std_internal =
390         codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
391
392     if is_extern && !std_internal {
393         let target = &tcx.sess.target.llvm_target;
394         // WebAssembly cannot export data symbols, so reduce their export level
395         if target.contains("emscripten") {
396             if let Some(Node::Item(&hir::Item { kind: hir::ItemKind::Static(..), .. })) =
397                 tcx.hir().get_if_local(sym_def_id)
398             {
399                 return SymbolExportLevel::Rust;
400             }
401         }
402
403         SymbolExportLevel::C
404     } else {
405         SymbolExportLevel::Rust
406     }
407 }
408
409 /// This is the symbol name of the given instance instantiated in a specific crate.
410 pub fn symbol_name_for_instance_in_crate<'tcx>(
411     tcx: TyCtxt<'tcx>,
412     symbol: ExportedSymbol<'tcx>,
413     instantiating_crate: CrateNum,
414 ) -> String {
415     // If this is something instantiated in the local crate then we might
416     // already have cached the name as a query result.
417     if instantiating_crate == LOCAL_CRATE {
418         return symbol.symbol_name_for_local_instance(tcx).to_string();
419     }
420
421     // This is something instantiated in an upstream crate, so we have to use
422     // the slower (because uncached) version of computing the symbol name.
423     match symbol {
424         ExportedSymbol::NonGeneric(def_id) => {
425             rustc_symbol_mangling::symbol_name_for_instance_in_crate(
426                 tcx,
427                 Instance::mono(tcx, def_id),
428                 instantiating_crate,
429             )
430         }
431         ExportedSymbol::Generic(def_id, substs) => {
432             rustc_symbol_mangling::symbol_name_for_instance_in_crate(
433                 tcx,
434                 Instance::new(def_id, substs),
435                 instantiating_crate,
436             )
437         }
438         ExportedSymbol::DropGlue(ty) => rustc_symbol_mangling::symbol_name_for_instance_in_crate(
439             tcx,
440             Instance::resolve_drop_in_place(tcx, ty),
441             instantiating_crate,
442         ),
443         ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),
444     }
445 }