1 use std::collections::hash_map::Entry::*;
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;
15 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, CRATE_DEF_INDEX, LOCAL_CRATE};
17 use rustc_index::vec::IndexVec;
18 use syntax::expand::allocator::ALLOCATOR_METHODS;
20 pub type ExportedSymbols = FxHashMap<CrateNum, Arc<Vec<(String, SymbolExportLevel)>>>;
22 pub fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
23 crates_export_threshold(&tcx.sess.crate_types.borrow())
26 fn crate_export_threshold(crate_type: config::CrateType) -> SymbolExportLevel {
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,
36 pub fn crates_export_threshold(crate_types: &[config::CrateType]) -> SymbolExportLevel {
39 .any(|&crate_type| crate_export_threshold(crate_type) == SymbolExportLevel::Rust)
41 SymbolExportLevel::Rust
47 fn reachable_non_generics_provider(
50 ) -> &DefIdMap<SymbolExportLevel> {
51 assert_eq!(cnum, LOCAL_CRATE);
53 if !tcx.sess.opts.output_types.should_codegen() {
54 return tcx.arena.alloc(Default::default());
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
64 let special_runtime_crate =
65 tcx.is_panic_runtime(LOCAL_CRATE) || tcx.is_compiler_builtins(LOCAL_CRATE);
67 let mut reachable_non_generics: DefIdMap<_> = tcx
68 .reachable_set(LOCAL_CRATE)
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
75 // 1. Those that are included statically via a static library
76 // 2. Those included otherwise (e.g., dynamically or via a framework)
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.
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)
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)
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.
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"
126 SymbolExportLevel::Rust
129 symbol_export_level(tcx, def_id)
132 "EXPORTED SYMBOL (local): {} ({:?})",
133 tcx.symbol_name(Instance::mono(tcx, def_id)),
136 (def_id, export_level)
140 if let Some(id) = tcx.proc_macro_decls_static(LOCAL_CRATE) {
141 reachable_non_generics.insert(id, SymbolExportLevel::C);
144 if let Some(id) = tcx.plugin_registrar_fn(LOCAL_CRATE) {
145 reachable_non_generics.insert(id, SymbolExportLevel::C);
148 tcx.arena.alloc(reachable_non_generics)
151 fn is_reachable_non_generic_provider_local(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
152 let export_threshold = threshold(tcx);
154 if let Some(&level) = tcx.reachable_non_generics(def_id.krate).get(&def_id) {
155 level.is_below_threshold(export_threshold)
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)
165 fn exported_symbols_provider_local(
168 ) -> Arc<Vec<(ExportedSymbol<'_>, SymbolExportLevel)>> {
169 assert_eq!(cnum, LOCAL_CRATE);
171 if !tcx.sess.opts.output_types.should_codegen() {
172 return Arc::new(vec![]);
175 let mut symbols: Vec<_> = tcx
176 .reachable_non_generics(LOCAL_CRATE)
178 .map(|(&def_id, &level)| (ExportedSymbol::NonGeneric(def_id), level))
181 if tcx.entry_fn(LOCAL_CRATE).is_some() {
182 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new("main"));
184 symbols.push((exported_symbol, SymbolExportLevel::C));
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));
192 symbols.push((exported_symbol, SymbolExportLevel::Rust));
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
200 const PROFILER_WEAK_SYMBOLS: [&str; 2] =
201 ["__llvm_profile_raw_version", "__llvm_profile_filename"];
203 symbols.extend(PROFILER_WEAK_SYMBOLS.iter().map(|sym| {
204 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(sym));
205 (exported_symbol, SymbolExportLevel::C)
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));
213 symbols.push((exported_symbol, SymbolExportLevel::Rust));
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;
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;
228 let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
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
237 if need_visibility && visibility == Visibility::Hidden {
238 // If we potentially share things from Rust dylibs, they must
243 if let &MonoItem::Fn(Instance { def: InstanceDef::Item(def_id), substs }) = mono_item {
244 if substs.non_erasable_generics().next().is_some() {
246 .push((ExportedSymbol::Generic(def_id, substs), SymbolExportLevel::Rust));
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)
260 fn upstream_monomorphizations_provider(
263 ) -> &DefIdMap<FxHashMap<SubstsRef<'_>, CrateNum>> {
264 debug_assert!(cnum == LOCAL_CRATE);
266 let cnums = tcx.all_crate_nums(LOCAL_CRATE);
268 let mut instances: DefIdMap<FxHashMap<_, _>> = Default::default();
270 let cnum_stable_ids: IndexVec<CrateNum, Fingerprint> = {
271 let mut cnum_stable_ids = IndexVec::from_elem_n(Fingerprint::ZERO, cnums.len() + 1);
273 for &cnum in cnums.iter() {
274 cnum_stable_ids[cnum] =
275 tcx.def_path_hash(DefId { krate: cnum, index: CRATE_DEF_INDEX }).0;
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();
286 match substs_map.entry(substs) {
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] {
303 tcx.arena.alloc(instances)
306 fn upstream_monomorphizations_for_provider(
309 ) -> Option<&FxHashMap<SubstsRef<'_>, CrateNum>> {
310 debug_assert!(!def_id.is_local());
311 tcx.upstream_monomorphizations(LOCAL_CRATE).get(&def_id)
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)
318 bug!("is_unreachable_local_definition called with non-local DefId: {:?}", def_id)
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;
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;
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();
344 codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
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)
353 return SymbolExportLevel::Rust;
359 SymbolExportLevel::Rust
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>(
366 symbol: ExportedSymbol<'tcx>,
367 instantiating_crate: CrateNum,
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();
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.
378 ExportedSymbol::NonGeneric(def_id) => symbol_names::symbol_name_for_instance_in_crate(
380 Instance::mono(tcx, def_id),
383 ExportedSymbol::Generic(def_id, substs) => symbol_names::symbol_name_for_instance_in_crate(
385 Instance::new(def_id, substs),
388 ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),