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::{self, Sanitizer};
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 let Some(Sanitizer::Memory) = tcx.sess.opts.debugging_opts.sanitizer {
210 // Similar to profiling, preserve weak msan symbol during LTO.
211 const MSAN_WEAK_SYMBOLS: [&str; 2] = ["__msan_track_origins", "__msan_keep_going"];
213 symbols.extend(MSAN_WEAK_SYMBOLS.iter().map(|sym| {
214 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(sym));
215 (exported_symbol, SymbolExportLevel::C)
219 if tcx.sess.crate_types.borrow().contains(&config::CrateType::Dylib) {
220 let symbol_name = metadata_symbol_name(tcx);
221 let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(&symbol_name));
223 symbols.push((exported_symbol, SymbolExportLevel::Rust));
226 if tcx.sess.opts.share_generics() && tcx.local_crate_exports_generics() {
227 use rustc::mir::mono::{Linkage, MonoItem, Visibility};
228 use rustc::ty::InstanceDef;
230 // Normally, we require that shared monomorphizations are not hidden,
231 // because if we want to re-use a monomorphization from a Rust dylib, it
232 // needs to be exported.
233 // However, on platforms that don't allow for Rust dylibs, having
234 // external linkage is enough for monomorphization to be linked to.
235 let need_visibility = tcx.sess.target.target.options.dynamic_linking
236 && !tcx.sess.target.target.options.only_cdylib;
238 let (_, cgus) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
240 for (mono_item, &(linkage, visibility)) in cgus.iter().flat_map(|cgu| cgu.items().iter()) {
241 if linkage != Linkage::External {
242 // We can only re-use things with external linkage, otherwise
243 // we'll get a linker error
247 if need_visibility && visibility == Visibility::Hidden {
248 // If we potentially share things from Rust dylibs, they must
253 if let &MonoItem::Fn(Instance { def: InstanceDef::Item(def_id), substs }) = mono_item {
254 if substs.non_erasable_generics().next().is_some() {
256 .push((ExportedSymbol::Generic(def_id, substs), SymbolExportLevel::Rust));
262 // Sort so we get a stable incr. comp. hash.
263 symbols.sort_unstable_by(|&(ref symbol1, ..), &(ref symbol2, ..)| {
264 symbol1.compare_stable(tcx, symbol2)
270 fn upstream_monomorphizations_provider(
273 ) -> &DefIdMap<FxHashMap<SubstsRef<'_>, CrateNum>> {
274 debug_assert!(cnum == LOCAL_CRATE);
276 let cnums = tcx.all_crate_nums(LOCAL_CRATE);
278 let mut instances: DefIdMap<FxHashMap<_, _>> = Default::default();
280 let cnum_stable_ids: IndexVec<CrateNum, Fingerprint> = {
281 let mut cnum_stable_ids = IndexVec::from_elem_n(Fingerprint::ZERO, cnums.len() + 1);
283 for &cnum in cnums.iter() {
284 cnum_stable_ids[cnum] =
285 tcx.def_path_hash(DefId { krate: cnum, index: CRATE_DEF_INDEX }).0;
291 for &cnum in cnums.iter() {
292 for (exported_symbol, _) in tcx.exported_symbols(cnum).iter() {
293 if let &ExportedSymbol::Generic(def_id, substs) = exported_symbol {
294 let substs_map = instances.entry(def_id).or_default();
296 match substs_map.entry(substs) {
298 // If there are multiple monomorphizations available,
299 // we select one deterministically.
300 let other_cnum = *e.get();
301 if cnum_stable_ids[other_cnum] > cnum_stable_ids[cnum] {
313 tcx.arena.alloc(instances)
316 fn upstream_monomorphizations_for_provider(
319 ) -> Option<&FxHashMap<SubstsRef<'_>, CrateNum>> {
320 debug_assert!(!def_id.is_local());
321 tcx.upstream_monomorphizations(LOCAL_CRATE).get(&def_id)
324 fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
325 if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
326 !tcx.reachable_set(LOCAL_CRATE).contains(&hir_id)
328 bug!("is_unreachable_local_definition called with non-local DefId: {:?}", def_id)
332 pub fn provide(providers: &mut Providers<'_>) {
333 providers.reachable_non_generics = reachable_non_generics_provider;
334 providers.is_reachable_non_generic = is_reachable_non_generic_provider_local;
335 providers.exported_symbols = exported_symbols_provider_local;
336 providers.upstream_monomorphizations = upstream_monomorphizations_provider;
337 providers.is_unreachable_local_definition = is_unreachable_local_definition_provider;
340 pub fn provide_extern(providers: &mut Providers<'_>) {
341 providers.is_reachable_non_generic = is_reachable_non_generic_provider_extern;
342 providers.upstream_monomorphizations_for = upstream_monomorphizations_for_provider;
345 fn symbol_export_level(tcx: TyCtxt<'_>, sym_def_id: DefId) -> SymbolExportLevel {
346 // We export anything that's not mangled at the "C" layer as it probably has
347 // to do with ABI concerns. We do not, however, apply such treatment to
348 // special symbols in the standard library for various plumbing between
349 // core/std/allocators/etc. For example symbols used to hook up allocation
350 // are not considered for export
351 let codegen_fn_attrs = tcx.codegen_fn_attrs(sym_def_id);
352 let is_extern = codegen_fn_attrs.contains_extern_indicator();
354 codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL);
356 if is_extern && !std_internal {
357 let target = &tcx.sess.target.target.llvm_target;
358 // WebAssembly cannot export data symbols, so reduce their export level
359 if target.contains("emscripten") {
360 if let Some(Node::Item(&hir::Item { kind: hir::ItemKind::Static(..), .. })) =
361 tcx.hir().get_if_local(sym_def_id)
363 return SymbolExportLevel::Rust;
369 SymbolExportLevel::Rust
373 /// This is the symbol name of the given instance instantiated in a specific crate.
374 pub fn symbol_name_for_instance_in_crate<'tcx>(
376 symbol: ExportedSymbol<'tcx>,
377 instantiating_crate: CrateNum,
379 // If this is something instantiated in the local crate then we might
380 // already have cached the name as a query result.
381 if instantiating_crate == LOCAL_CRATE {
382 return symbol.symbol_name_for_local_instance(tcx).to_string();
385 // This is something instantiated in an upstream crate, so we have to use
386 // the slower (because uncached) version of computing the symbol name.
388 ExportedSymbol::NonGeneric(def_id) => symbol_names::symbol_name_for_instance_in_crate(
390 Instance::mono(tcx, def_id),
393 ExportedSymbol::Generic(def_id, substs) => symbol_names::symbol_name_for_instance_in_crate(
395 Instance::new(def_id, substs),
398 ExportedSymbol::NoDefId(symbol_name) => symbol_name.to_string(),