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