1 use std::collections::hash_map::Entry::*;
4 use rustc::ty::Instance;
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_index::vec::IndexVec;
17 use syntax::expand::allocator::ALLOCATOR_METHODS;
19 pub type ExportedSymbols = FxHashMap<
21 Arc<Vec<(String, SymbolExportLevel)>>,
24 pub fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
25 crates_export_threshold(&tcx.sess.crate_types.borrow())
28 fn crate_export_threshold(crate_type: config::CrateType) -> SymbolExportLevel {
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,
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)
43 SymbolExportLevel::Rust
49 fn reachable_non_generics_provider(
52 ) -> &DefIdMap<SymbolExportLevel> {
53 assert_eq!(cnum, LOCAL_CRATE);
55 if !tcx.sess.opts.output_types.should_codegen() {
56 return tcx.arena.alloc(Default::default());
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
66 let special_runtime_crate = tcx.is_panic_runtime(LOCAL_CRATE) ||
67 tcx.is_compiler_builtins(LOCAL_CRATE);
69 let mut reachable_non_generics: DefIdMap<_> = tcx.reachable_set(LOCAL_CRATE).0
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
76 // 1. Those that are included statically via a static library
77 // 2. Those included otherwise (e.g., dynamically or via a framework)
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.
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 tcx.is_statically_included_foreign_item(def_id).then_some(def_id)
91 // Only consider nodes that actually have exported symbols.
92 Node::Item(&hir::Item {
93 kind: hir::ItemKind::Static(..),
96 Node::Item(&hir::Item {
97 kind: hir::ItemKind::Fn(..), ..
99 Node::ImplItem(&hir::ImplItem {
100 kind: hir::ImplItemKind::Method(..),
103 let def_id = tcx.hir().local_def_id(hir_id);
104 let generics = tcx.generics_of(def_id);
105 if !generics.requires_monomorphization(tcx) &&
106 // Functions marked with #[inline] are only ever codegened
107 // with "internal" linkage and are never exported.
108 !Instance::mono(tcx, def_id).def.requires_local(tcx) {
119 let export_level = if special_runtime_crate {
120 let name = tcx.symbol_name(Instance::mono(tcx, def_id)).name.as_str();
121 // We can probably do better here by just ensuring that
122 // it has hidden visibility rather than public
123 // visibility, as this is primarily here to ensure it's
124 // not stripped during LTO.
126 // In general though we won't link right if these
127 // symbols are stripped, and LTO currently strips them.
128 if name == "rust_eh_personality" ||
129 name == "rust_eh_register_frames" ||
130 name == "rust_eh_unregister_frames" {
133 SymbolExportLevel::Rust
136 symbol_export_level(tcx, def_id)
138 debug!("EXPORTED SYMBOL (local): {} ({:?})",
139 tcx.symbol_name(Instance::mono(tcx, def_id)),
141 (def_id, export_level)
145 if let Some(id) = tcx.proc_macro_decls_static(LOCAL_CRATE) {
146 reachable_non_generics.insert(id, SymbolExportLevel::C);
149 if let Some(id) = tcx.plugin_registrar_fn(LOCAL_CRATE) {
150 reachable_non_generics.insert(id, SymbolExportLevel::C);
153 tcx.arena.alloc(reachable_non_generics)
156 fn is_reachable_non_generic_provider_local(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
157 let export_threshold = threshold(tcx);
159 if let Some(&level) = tcx.reachable_non_generics(def_id.krate).get(&def_id) {
160 level.is_below_threshold(export_threshold)
166 fn is_reachable_non_generic_provider_extern(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
167 tcx.reachable_non_generics(def_id.krate).contains_key(&def_id)
170 fn exported_symbols_provider_local(
173 ) -> Arc<Vec<(ExportedSymbol<'_>, SymbolExportLevel)>> {
174 assert_eq!(cnum, LOCAL_CRATE);
176 if !tcx.sess.opts.output_types.should_codegen() {
177 return Arc::new(vec![])
180 let mut symbols: Vec<_> = tcx.reachable_non_generics(LOCAL_CRATE)
182 .map(|(&def_id, &level)| {
183 (ExportedSymbol::NonGeneric(def_id), level)
187 if tcx.entry_fn(LOCAL_CRATE).is_some() {
188 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new("main"));
190 symbols.push((exported_symbol, SymbolExportLevel::C));
193 if tcx.allocator_kind().is_some() {
194 for method in ALLOCATOR_METHODS {
195 let symbol_name = format!("__rust_{}", method.name);
196 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(&symbol_name));
198 symbols.push((exported_symbol, SymbolExportLevel::Rust));
202 if tcx.sess.opts.cg.profile_generate.enabled() {
203 // These are weak symbols that point to the profile version and the
204 // profile name, which need to be treated as exported so LTO doesn't nix
206 const PROFILER_WEAK_SYMBOLS: [&str; 2] = [
207 "__llvm_profile_raw_version",
208 "__llvm_profile_filename",
211 symbols.extend(PROFILER_WEAK_SYMBOLS.iter().map(|sym| {
212 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(sym));
213 (exported_symbol, SymbolExportLevel::C)
217 if tcx.sess.crate_types.borrow().contains(&config::CrateType::Dylib) {
218 let symbol_name = metadata_symbol_name(tcx);
219 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(&symbol_name));
221 symbols.push((exported_symbol, SymbolExportLevel::Rust));
224 if tcx.sess.opts.share_generics() && tcx.local_crate_exports_generics() {
225 use rustc::mir::mono::{Linkage, Visibility, MonoItem};
226 use rustc::ty::InstanceDef;
228 // Normally, we require that shared monomorphizations are not hidden,
229 // because if we want to re-use a monomorphization from a Rust dylib, it
230 // needs to be exported.
231 // However, on platforms that don't allow for Rust dylibs, having
232 // external linkage is enough for monomorphization to be linked to.
233 let need_visibility = tcx.sess.target.target.options.dynamic_linking &&
234 !tcx.sess.target.target.options.only_cdylib;
236 let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
238 for (mono_item, &(linkage, visibility)) in cgus.iter()
239 .flat_map(|cgu| cgu.items().iter()) {
240 if linkage != Linkage::External {
241 // We can only re-use things with external linkage, otherwise
242 // we'll get a linker error
246 if need_visibility && visibility == Visibility::Hidden {
247 // If we potentially share things from Rust dylibs, they must
252 if let &MonoItem::Fn(Instance {
253 def: InstanceDef::Item(def_id),
256 if substs.non_erasable_generics().next().is_some() {
257 symbols.push((ExportedSymbol::Generic(def_id, substs),
258 SymbolExportLevel::Rust));
264 // Sort so we get a stable incr. comp. hash.
265 symbols.sort_unstable_by(|&(ref symbol1, ..), &(ref symbol2, ..)| {
266 symbol1.compare_stable(tcx, symbol2)
272 fn upstream_monomorphizations_provider(
275 ) -> &DefIdMap<FxHashMap<SubstsRef<'_>, CrateNum>> {
276 debug_assert!(cnum == LOCAL_CRATE);
278 let cnums = tcx.all_crate_nums(LOCAL_CRATE);
280 let mut instances: DefIdMap<FxHashMap<_, _>> = Default::default();
282 let cnum_stable_ids: IndexVec<CrateNum, Fingerprint> = {
283 let mut cnum_stable_ids = IndexVec::from_elem_n(Fingerprint::ZERO,
286 for &cnum in cnums.iter() {
287 cnum_stable_ids[cnum] = tcx.def_path_hash(DefId {
289 index: CRATE_DEF_INDEX,
296 for &cnum in cnums.iter() {
297 for (exported_symbol, _) in tcx.exported_symbols(cnum).iter() {
298 if let &ExportedSymbol::Generic(def_id, substs) = exported_symbol {
299 let substs_map = instances.entry(def_id).or_default();
301 match substs_map.entry(substs) {
303 // If there are multiple monomorphizations available,
304 // we select one deterministically.
305 let other_cnum = *e.get();
306 if cnum_stable_ids[other_cnum] > cnum_stable_ids[cnum] {
318 tcx.arena.alloc(instances)
321 fn upstream_monomorphizations_for_provider(
324 ) -> Option<&FxHashMap<SubstsRef<'_>, CrateNum>> {
325 debug_assert!(!def_id.is_local());
326 tcx.upstream_monomorphizations(LOCAL_CRATE).get(&def_id)
329 fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
330 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
331 !tcx.reachable_set(LOCAL_CRATE).0.contains(&hir_id)
333 bug!("is_unreachable_local_definition called with non-local DefId: {:?}",
338 pub fn provide(providers: &mut Providers<'_>) {
339 providers.reachable_non_generics = reachable_non_generics_provider;
340 providers.is_reachable_non_generic = is_reachable_non_generic_provider_local;
341 providers.exported_symbols = exported_symbols_provider_local;
342 providers.upstream_monomorphizations = upstream_monomorphizations_provider;
343 providers.is_unreachable_local_definition = is_unreachable_local_definition_provider;
346 pub fn provide_extern(providers: &mut Providers<'_>) {
347 providers.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
348 providers.upstream_monomorphizations_for = upstream_monomorphizations_for_provider;
351 fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
352 // We export anything that's not mangled at the "C" layer as it probably has
353 // to do with ABI concerns. We do not, however, apply such treatment to
354 // special symbols in the standard library for various plumbing between
355 // core/std/allocators/etc. For example symbols used to hook up allocation
356 // are not considered for export
357 let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
358 let is_extern = codegen_fn_attrs.contains_extern_indicator();
360 codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
362 if is_extern && !std_internal {
363 let target = &tcx.sess.target.target.llvm_target;
364 // WebAssembly cannot export data symbols, so reduce their export level
365 if target.contains("wasm32") || target.contains("emscripten") {
366 if let Some(Node::Item(&hir::Item {
367 kind: hir::ItemKind::Static(..),
369 })) = tcx.hir().get_if_local(sym_def_id) {
370 return SymbolExportLevel::Rust;
376 SymbolExportLevel::Rust