1 use std::collections::hash_map::Entry::*;
5 use rustc::hir::def_id::{CrateNum, DefId, DefIdMap, CRATE_DEF_INDEX, LOCAL_CRATE};
7 use rustc::middle::codegen_fn_attrs::CodegenFnAttrFlags;
8 use rustc::middle::exported_symbols::{metadata_symbol_name, ExportedSymbol, SymbolExportLevel};
9 use rustc::session::config;
10 use rustc::ty::query::Providers;
11 use rustc::ty::subst::SubstsRef;
12 use rustc::ty::Instance;
13 use rustc::ty::{SymbolName, TyCtxt};
14 use rustc_data_structures::fingerprint::Fingerprint;
15 use rustc_data_structures::fx::FxHashMap;
16 use rustc_index::vec::IndexVec;
17 use syntax::expand::allocator::ALLOCATOR_METHODS;
19 pub type ExportedSymbols = FxHashMap<CrateNum, Arc<Vec<(String, SymbolExportLevel)>>>;
21 pub fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
22 crates_export_threshold(&tcx.sess.crate_types.borrow())
25 fn crate_export_threshold(crate_type: config::CrateType) -> SymbolExportLevel {
27 config::CrateType::Executable
28 | config::CrateType::Staticlib
29 | config::CrateType::ProcMacro
30 | config::CrateType::Cdylib => SymbolExportLevel::C,
31 config::CrateType::Rlib | config::CrateType::Dylib => SymbolExportLevel::Rust,
35 pub fn crates_export_threshold(crate_types: &[config::CrateType]) -> SymbolExportLevel {
38 .any(|&crate_type| crate_export_threshold(crate_type) == SymbolExportLevel::Rust)
40 SymbolExportLevel::Rust
46 fn reachable_non_generics_provider(
49 ) -> &DefIdMap<SymbolExportLevel> {
50 assert_eq!(cnum, LOCAL_CRATE);
52 if !tcx.sess.opts.output_types.should_codegen() {
53 return tcx.arena.alloc(Default::default());
56 // Check to see if this crate is a "special runtime crate". These
57 // crates, implementation details of the standard library, typically
58 // have a bunch of `pub extern` and `#[no_mangle]` functions as the
59 // ABI between them. We don't want their symbols to have a `C`
60 // export level, however, as they're just implementation details.
61 // Down below we'll hardwire all of the symbols to the `Rust` export
63 let special_runtime_crate =
64 tcx.is_panic_runtime(LOCAL_CRATE) || tcx.is_compiler_builtins(LOCAL_CRATE);
66 let mut reachable_non_generics: DefIdMap<_> = tcx
67 .reachable_set(LOCAL_CRATE)
69 .filter_map(|&hir_id| {
70 // We want to ignore some FFI functions that are not exposed from
71 // this crate. Reachable FFI functions can be lumped into two
74 // 1. Those that are included statically via a static library
75 // 2. Those included otherwise (e.g., dynamically or via a framework)
77 // Although our LLVM module is not literally emitting code for the
78 // statically included symbols, it's an export of our library which
79 // needs to be passed on to the linker and encoded in the metadata.
81 // As a result, if this id is an FFI item (foreign item) then we only
82 // let it through if it's included statically.
83 match tcx.hir().get(hir_id) {
84 Node::ForeignItem(..) => {
85 let def_id = tcx.hir().local_def_id(hir_id);
86 tcx.is_statically_included_foreign_item(def_id).then_some(def_id)
89 // Only consider nodes that actually have exported symbols.
90 Node::Item(&hir::Item { kind: hir::ItemKind::Static(..), .. })
91 | Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. })
92 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Method(..), .. }) => {
93 let def_id = tcx.hir().local_def_id(hir_id);
94 let generics = tcx.generics_of(def_id);
95 if !generics.requires_monomorphization(tcx) &&
96 // Functions marked with #[inline] are only ever codegened
97 // with "internal" linkage and are never exported.
98 !Instance::mono(tcx, def_id).def.requires_local(tcx)
110 let export_level = if special_runtime_crate {
111 let name = tcx.symbol_name(Instance::mono(tcx, def_id)).name.as_str();
112 // We can probably do better here by just ensuring that
113 // it has hidden visibility rather than public
114 // visibility, as this is primarily here to ensure it's
115 // not stripped during LTO.
117 // In general though we won't link right if these
118 // symbols are stripped, and LTO currently strips them.
119 if name == "rust_eh_personality"
120 || name == "rust_eh_register_frames"
121 || name == "rust_eh_unregister_frames"
125 SymbolExportLevel::Rust
128 symbol_export_level(tcx, def_id)
131 "EXPORTED SYMBOL (local): {} ({:?})",
132 tcx.symbol_name(Instance::mono(tcx, def_id)),
135 (def_id, export_level)
139 if let Some(id) = tcx.proc_macro_decls_static(LOCAL_CRATE) {
140 reachable_non_generics.insert(id, SymbolExportLevel::C);
143 if let Some(id) = tcx.plugin_registrar_fn(LOCAL_CRATE) {
144 reachable_non_generics.insert(id, SymbolExportLevel::C);
147 tcx.arena.alloc(reachable_non_generics)
150 fn is_reachable_non_generic_provider_local(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
151 let export_threshold = threshold(tcx);
153 if let Some(&level) = tcx.reachable_non_generics(def_id.krate).get(&def_id) {
154 level.is_below_threshold(export_threshold)
160 fn is_reachable_non_generic_provider_extern(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
161 tcx.reachable_non_generics(def_id.krate).contains_key(&def_id)
164 fn exported_symbols_provider_local(
167 ) -> Arc<Vec<(ExportedSymbol<'_>, SymbolExportLevel)>> {
168 assert_eq!(cnum, LOCAL_CRATE);
170 if !tcx.sess.opts.output_types.should_codegen() {
171 return Arc::new(vec![]);
174 let mut symbols: Vec<_> = tcx
175 .reachable_non_generics(LOCAL_CRATE)
177 .map(|(&def_id, &level)| (ExportedSymbol::NonGeneric(def_id), level))
180 if tcx.entry_fn(LOCAL_CRATE).is_some() {
181 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new("main"));
183 symbols.push((exported_symbol, SymbolExportLevel::C));
186 if tcx.allocator_kind().is_some() {
187 for method in ALLOCATOR_METHODS {
188 let symbol_name = format!("__rust_{}", method.name);
189 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(&symbol_name));
191 symbols.push((exported_symbol, SymbolExportLevel::Rust));
195 if tcx.sess.opts.cg.profile_generate.enabled() {
196 // These are weak symbols that point to the profile version and the
197 // profile name, which need to be treated as exported so LTO doesn't nix
199 const PROFILER_WEAK_SYMBOLS: [&str; 2] =
200 ["__llvm_profile_raw_version", "__llvm_profile_filename"];
202 symbols.extend(PROFILER_WEAK_SYMBOLS.iter().map(|sym| {
203 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(sym));
204 (exported_symbol, SymbolExportLevel::C)
208 if tcx.sess.crate_types.borrow().contains(&config::CrateType::Dylib) {
209 let symbol_name = metadata_symbol_name(tcx);
210 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(&symbol_name));
212 symbols.push((exported_symbol, SymbolExportLevel::Rust));
215 if tcx.sess.opts.share_generics() && tcx.local_crate_exports_generics() {
216 use rustc::mir::mono::{Linkage, MonoItem, Visibility};
217 use rustc::ty::InstanceDef;
219 // Normally, we require that shared monomorphizations are not hidden,
220 // because if we want to re-use a monomorphization from a Rust dylib, it
221 // needs to be exported.
222 // However, on platforms that don't allow for Rust dylibs, having
223 // external linkage is enough for monomorphization to be linked to.
224 let need_visibility = tcx.sess.target.target.options.dynamic_linking
225 && !tcx.sess.target.target.options.only_cdylib;
227 let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
229 for (mono_item, &(linkage, visibility)) in cgus.iter().flat_map(|cgu| cgu.items().iter()) {
230 if linkage != Linkage::External {
231 // We can only re-use things with external linkage, otherwise
232 // we'll get a linker error
236 if need_visibility && visibility == Visibility::Hidden {
237 // If we potentially share things from Rust dylibs, they must
242 if let &MonoItem::Fn(Instance { def: InstanceDef::Item(def_id), substs }) = mono_item {
243 if substs.non_erasable_generics().next().is_some() {
245 .push((ExportedSymbol::Generic(def_id, substs), SymbolExportLevel::Rust));
251 // Sort so we get a stable incr. comp. hash.
252 symbols.sort_unstable_by(|&(ref symbol1, ..), &(ref symbol2, ..)| {
253 symbol1.compare_stable(tcx, symbol2)
259 fn upstream_monomorphizations_provider(
262 ) -> &DefIdMap<FxHashMap<SubstsRef<'_>, CrateNum>> {
263 debug_assert!(cnum == LOCAL_CRATE);
265 let cnums = tcx.all_crate_nums(LOCAL_CRATE);
267 let mut instances: DefIdMap<FxHashMap<_, _>> = Default::default();
269 let cnum_stable_ids: IndexVec<CrateNum, Fingerprint> = {
270 let mut cnum_stable_ids = IndexVec::from_elem_n(Fingerprint::ZERO, cnums.len() + 1);
272 for &cnum in cnums.iter() {
273 cnum_stable_ids[cnum] =
274 tcx.def_path_hash(DefId { krate: cnum, index: CRATE_DEF_INDEX }).0;
280 for &cnum in cnums.iter() {
281 for (exported_symbol, _) in tcx.exported_symbols(cnum).iter() {
282 if let &ExportedSymbol::Generic(def_id, substs) = exported_symbol {
283 let substs_map = instances.entry(def_id).or_default();
285 match substs_map.entry(substs) {
287 // If there are multiple monomorphizations available,
288 // we select one deterministically.
289 let other_cnum = *e.get();
290 if cnum_stable_ids[other_cnum] > cnum_stable_ids[cnum] {
302 tcx.arena.alloc(instances)
305 fn upstream_monomorphizations_for_provider(
308 ) -> Option<&FxHashMap<SubstsRef<'_>, CrateNum>> {
309 debug_assert!(!def_id.is_local());
310 tcx.upstream_monomorphizations(LOCAL_CRATE).get(&def_id)
313 fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
314 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
315 !tcx.reachable_set(LOCAL_CRATE).contains(&hir_id)
317 bug!("is_unreachable_local_definition called with non-local DefId: {:?}", def_id)
321 pub fn provide(providers: &mut Providers<'_>) {
322 providers.reachable_non_generics = reachable_non_generics_provider;
323 providers.is_reachable_non_generic = is_reachable_non_generic_provider_local;
324 providers.exported_symbols = exported_symbols_provider_local;
325 providers.upstream_monomorphizations = upstream_monomorphizations_provider;
326 providers.is_unreachable_local_definition = is_unreachable_local_definition_provider;
329 pub fn provide_extern(providers: &mut Providers<'_>) {
330 providers.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
331 providers.upstream_monomorphizations_for = upstream_monomorphizations_for_provider;
334 fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
335 // We export anything that's not mangled at the "C" layer as it probably has
336 // to do with ABI concerns. We do not, however, apply such treatment to
337 // special symbols in the standard library for various plumbing between
338 // core/std/allocators/etc. For example symbols used to hook up allocation
339 // are not considered for export
340 let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
341 let is_extern = codegen_fn_attrs.contains_extern_indicator();
343 codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
345 if is_extern && !std_internal {
346 let target = &tcx.sess.target.target.llvm_target;
347 // WebAssembly cannot export data symbols, so reduce their export level
348 if target.contains("wasm32") || target.contains("emscripten") {
349 if let Some(Node::Item(&hir::Item { kind: hir::ItemKind::Static(..), .. })) =
350 tcx.hir().get_if_local(sym_def_id)
352 return SymbolExportLevel::Rust;
358 SymbolExportLevel::Rust