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