Skip to content

Commit d9ce420

Browse files
committed
Auto merge of #68414 - michaelwoerister:share-drop-glue, r=<try>
Also share drop-glue when compiling with -Zshare-generics (i.e. at opt-level=0) This PR adds drop-glue to the set of monomorphizations that can be shared across crates via `-Zshare-generics`. This version of the PR might have detrimental effects on performance as it makes lots of stuff dependent on a single query results (`upstream_monomorphizations_for(def_id_of_drop_in_place)`). That should be fixable but let's do a perf run first. Potentially fixes issue #64140. (cc @alexcrichton) The changes here are related to @matthewjasper's #67332 but should be mostly orthogonal. r? @ghost
2 parents 2f688ac + 9494974 commit d9ce420

File tree

14 files changed

+140
-121
lines changed

14 files changed

+140
-121
lines changed

src/librustc/middle/exported_symbols.rs

Lines changed: 0 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ use crate::ty::subst::SubstsRef;
33
use crate::ty::{self, TyCtxt};
44
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
55
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
6-
use std::cmp;
76
use std::mem;
87

98
/// The SymbolExportLevel of a symbols specifies from which kinds of crates
@@ -43,43 +42,6 @@ impl<'tcx> ExportedSymbol<'tcx> {
4342
ExportedSymbol::NoDefId(symbol_name) => symbol_name,
4443
}
4544
}
46-
47-
pub fn compare_stable(&self, tcx: TyCtxt<'tcx>, other: &ExportedSymbol<'tcx>) -> cmp::Ordering {
48-
match *self {
49-
ExportedSymbol::NonGeneric(self_def_id) => match *other {
50-
ExportedSymbol::NonGeneric(other_def_id) => {
51-
tcx.def_path_hash(self_def_id).cmp(&tcx.def_path_hash(other_def_id))
52-
}
53-
ExportedSymbol::Generic(..) | ExportedSymbol::NoDefId(_) => cmp::Ordering::Less,
54-
},
55-
ExportedSymbol::Generic(self_def_id, self_substs) => match *other {
56-
ExportedSymbol::NonGeneric(_) => cmp::Ordering::Greater,
57-
ExportedSymbol::Generic(other_def_id, other_substs) => {
58-
// We compare the symbol names because they are cached as query
59-
// results which makes them relatively cheap to access repeatedly.
60-
//
61-
// It might be even faster to build a local cache of stable IDs
62-
// for sorting. Exported symbols are really only sorted once
63-
// in order to make the `exported_symbols` query result stable.
64-
let self_symbol_name =
65-
tcx.symbol_name(ty::Instance::new(self_def_id, self_substs));
66-
let other_symbol_name =
67-
tcx.symbol_name(ty::Instance::new(other_def_id, other_substs));
68-
69-
self_symbol_name.cmp(&other_symbol_name)
70-
}
71-
ExportedSymbol::NoDefId(_) => cmp::Ordering::Less,
72-
},
73-
ExportedSymbol::NoDefId(self_symbol_name) => match *other {
74-
ExportedSymbol::NonGeneric(_) | ExportedSymbol::Generic(..) => {
75-
cmp::Ordering::Greater
76-
}
77-
ExportedSymbol::NoDefId(ref other_symbol_name) => {
78-
self_symbol_name.cmp(other_symbol_name)
79-
}
80-
},
81-
}
82-
}
8345
}
8446

8547
pub fn metadata_symbol_name(tcx: TyCtxt<'_>) -> String {

src/librustc/mir/mono.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ impl<'tcx> MonoItem<'tcx> {
7979
}
8080

8181
pub fn instantiation_mode(&self, tcx: TyCtxt<'tcx>) -> InstantiationMode {
82-
let inline_in_all_cgus = tcx
82+
let generate_cgu_internal_copies = tcx
8383
.sess
8484
.opts
8585
.debugging_opts
@@ -93,7 +93,7 @@ impl<'tcx> MonoItem<'tcx> {
9393
// If this function isn't inlined or otherwise has explicit
9494
// linkage, then we'll be creating a globally shared version.
9595
if self.explicit_linkage(tcx).is_some()
96-
|| !instance.def.requires_local(tcx)
96+
|| !instance.def.generates_cgu_internal_copy(tcx)
9797
|| Some(instance.def_id()) == entry_def_id
9898
{
9999
return InstantiationMode::GloballyShared { may_conflict: false };
@@ -102,7 +102,7 @@ impl<'tcx> MonoItem<'tcx> {
102102
// At this point we don't have explicit linkage and we're an
103103
// inlined function. If we're inlining into all CGUs then we'll
104104
// be creating a local copy per CGU
105-
if inline_in_all_cgus {
105+
if generate_cgu_internal_copies {
106106
return InstantiationMode::LocalCopy;
107107
}
108108

src/librustc/query/mod.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -783,6 +783,11 @@ rustc_queries! {
783783
}
784784
query upstream_monomorphizations_for(_: DefId)
785785
-> Option<&'tcx FxHashMap<SubstsRef<'tcx>, CrateNum>> {}
786+
787+
query upstream_drop_glue_for(substs: SubstsRef<'tcx>) -> Option<CrateNum> {
788+
desc { "available upstream drop-glue for `{:?}`", substs }
789+
no_force
790+
}
786791
}
787792

788793
Other {

src/librustc/ty/instance.rs

Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use crate::traits;
44
use crate::ty::print::{FmtPrinter, Printer};
55
use crate::ty::{self, SubstsRef, Ty, TyCtxt, TypeFoldable};
66
use rustc_hir::def::Namespace;
7-
use rustc_hir::def_id::DefId;
7+
use rustc_hir::def_id::{CrateNum, DefId};
88
use rustc_macros::HashStable;
99
use rustc_target::spec::abi::Abi;
1010

@@ -91,6 +91,38 @@ impl<'tcx> Instance<'tcx> {
9191
let ty = tcx.type_of(self.def.def_id());
9292
tcx.subst_and_normalize_erasing_regions(self.substs, param_env, &ty)
9393
}
94+
95+
pub fn upstream_monomorphization(&self, tcx: TyCtxt<'tcx>) -> Option<CrateNum> {
96+
// If we are not in share generics mode, we don't link to upstream
97+
// monomorphizations but always instantiate our own internal versions
98+
// instead.
99+
if !tcx.sess.opts.share_generics() {
100+
return None;
101+
}
102+
103+
// If this instance has non-erasable parameters, it cannot be a shared
104+
// monomorphization. Non-generic instances are already handled above
105+
// by `is_reachable_non_generic()`.
106+
if self.substs.non_erasable_generics().next().is_none() {
107+
return None;
108+
}
109+
110+
if self.def_id().is_local() {
111+
return None;
112+
}
113+
114+
match self.def {
115+
InstanceDef::Item(def_id) => {
116+
tcx
117+
.upstream_monomorphizations_for(def_id)
118+
.and_then(|monos| monos.get(&self.substs).cloned())
119+
}
120+
InstanceDef::DropGlue(_, Some(_)) => {
121+
tcx.upstream_drop_glue_for(self.substs)
122+
}
123+
_ => None,
124+
}
125+
}
94126
}
95127

96128
impl<'tcx> InstanceDef<'tcx> {
@@ -114,7 +146,12 @@ impl<'tcx> InstanceDef<'tcx> {
114146
tcx.get_attrs(self.def_id())
115147
}
116148

117-
pub fn is_inline(&self, tcx: TyCtxt<'tcx>) -> bool {
149+
/// Returns `true` if the LLVM version of this instance is unconditionally
150+
/// marked with `inline`. This implies that a copy of this instance is
151+
/// generated in every codegen unit.
152+
/// Note that this is only a hint. See the documentation for
153+
/// `generates_cgu_internal_copy` for more information.
154+
pub fn requires_inline(&self, tcx: TyCtxt<'tcx>) -> bool {
118155
use crate::hir::map::DefPathData;
119156
let def_id = match *self {
120157
ty::InstanceDef::Item(def_id) => def_id,
@@ -127,8 +164,15 @@ impl<'tcx> InstanceDef<'tcx> {
127164
}
128165
}
129166

130-
pub fn requires_local(&self, tcx: TyCtxt<'tcx>) -> bool {
131-
if self.is_inline(tcx) {
167+
/// Returns `true` if the machine code for this instance is instantiated in
168+
/// each codegen unit that references it.
169+
/// Note that this is only a hint! The compiler can globally decide to *not*
170+
/// do this in order to speed up compilation. CGU-internal copies are
171+
/// only exist to enable inlining. If inlining is not performed (e.g. at
172+
/// `-Copt-level=0`) then the time for generating them is wasted and it's
173+
/// better to create a single copy with external linkage.
174+
pub fn generates_cgu_internal_copy(&self, tcx: TyCtxt<'tcx>) -> bool {
175+
if self.requires_inline(tcx) {
132176
return true;
133177
}
134178
if let ty::InstanceDef::DropGlue(..) = *self {

src/librustc/ty/query/keys.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,15 @@ impl Key for (DefId, SimplifiedType) {
116116
}
117117
}
118118

119+
impl<'tcx> Key for SubstsRef<'tcx> {
120+
fn query_crate(&self) -> CrateNum {
121+
LOCAL_CRATE
122+
}
123+
fn default_span(&self, _: TyCtxt<'_>) -> Span {
124+
DUMMY_SP
125+
}
126+
}
127+
119128
impl<'tcx> Key for (DefId, SubstsRef<'tcx>) {
120129
fn query_crate(&self) -> CrateNum {
121130
self.0.krate

src/librustc_codegen_llvm/attributes.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ pub fn from_fn_attrs(
246246
}
247247

248248
// FIXME(eddyb) consolidate these two `inline` calls (and avoid overwrites).
249-
if instance.def.is_inline(cx.tcx) {
249+
if instance.def.requires_inline(cx.tcx) {
250250
inline(cx, llfn, attributes::InlineAttr::Hint);
251251
}
252252

src/librustc_codegen_llvm/callee.rs

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -130,12 +130,7 @@ pub fn get_fn(cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'tcx>) -> &'ll Value
130130
} else {
131131
// This is a monomorphization of a generic function
132132
// defined in an upstream crate.
133-
if cx
134-
.tcx
135-
.upstream_monomorphizations_for(instance_def_id)
136-
.map(|set| set.contains_key(instance.substs))
137-
.unwrap_or(false)
138-
{
133+
if instance.upstream_monomorphization(tcx).is_some() {
139134
// This is instantiated in another crate. It cannot
140135
// be `hidden`.
141136
} else {

src/librustc_codegen_ssa/back/symbol_export.rs

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use rustc::middle::codegen_fn_attrs::CodegenFnAttrFlags;
55
use rustc::middle::exported_symbols::{metadata_symbol_name, ExportedSymbol, SymbolExportLevel};
66
use rustc::session::config;
77
use rustc::ty::query::Providers;
8-
use rustc::ty::subst::SubstsRef;
8+
use rustc::ty::subst::{GenericArgKind, SubstsRef};
99
use rustc::ty::Instance;
1010
use rustc::ty::{SymbolName, TyCtxt};
1111
use rustc_codegen_utils::symbol_names;
@@ -17,8 +17,6 @@ use rustc_hir::Node;
1717
use rustc_index::vec::IndexVec;
1818
use syntax::expand::allocator::ALLOCATOR_METHODS;
1919

20-
pub type ExportedSymbols = FxHashMap<CrateNum, Arc<Vec<(String, SymbolExportLevel)>>>;
21-
2220
pub fn threshold(tcx: TyCtxt<'_>) -> SymbolExportLevel {
2321
crates_export_threshold(&tcx.sess.crate_types.borrow())
2422
}
@@ -96,7 +94,7 @@ fn reachable_non_generics_provider(
9694
if !generics.requires_monomorphization(tcx) &&
9795
// Functions marked with #[inline] are only ever codegened
9896
// with "internal" linkage and are never exported.
99-
!Instance::mono(tcx, def_id).def.requires_local(tcx)
97+
!Instance::mono(tcx, def_id).def.generates_cgu_internal_copy(tcx)
10098
{
10199
Some(def_id)
102100
} else {
@@ -240,19 +238,31 @@ fn exported_symbols_provider_local(
240238
continue;
241239
}
242240

243-
if let &MonoItem::Fn(Instance { def: InstanceDef::Item(def_id), substs }) = mono_item {
244-
if substs.non_erasable_generics().next().is_some() {
245-
symbols
246-
.push((ExportedSymbol::Generic(def_id, substs), SymbolExportLevel::Rust));
241+
match *mono_item {
242+
MonoItem::Fn(Instance { def: InstanceDef::Item(def_id), substs }) => {
243+
if substs.non_erasable_generics().next().is_some() {
244+
let symbol = ExportedSymbol::Generic(def_id, substs);
245+
symbols.push((symbol, SymbolExportLevel::Rust));
246+
}
247+
}
248+
MonoItem::Fn(Instance { def: InstanceDef::DropGlue(def_id, Some(ty)), substs }) => {
249+
// A little sanity-check
250+
debug_assert_eq!(
251+
substs.non_erasable_generics().next(),
252+
Some(GenericArgKind::Type(ty))
253+
);
254+
let symbol = ExportedSymbol::Generic(def_id, substs);
255+
symbols.push((symbol, SymbolExportLevel::Rust));
256+
}
257+
_ => {
258+
// Any other symbols don't qualify for sharing
247259
}
248260
}
249261
}
250262
}
251263

252264
// Sort so we get a stable incr. comp. hash.
253-
symbols.sort_unstable_by(|&(ref symbol1, ..), &(ref symbol2, ..)| {
254-
symbol1.compare_stable(tcx, symbol2)
255-
});
265+
symbols.sort_by_cached_key(|s| s.0.symbol_name_for_local_instance(tcx));
256266

257267
Arc::new(symbols)
258268
}
@@ -311,6 +321,17 @@ fn upstream_monomorphizations_for_provider(
311321
tcx.upstream_monomorphizations(LOCAL_CRATE).get(&def_id)
312322
}
313323

324+
fn upstream_drop_glue_for_provider<'tcx>(
325+
tcx: TyCtxt<'tcx>,
326+
substs: SubstsRef<'tcx>,
327+
) -> Option<CrateNum> {
328+
if let Some(def_id) = tcx.lang_items().drop_in_place_fn() {
329+
tcx.upstream_monomorphizations(LOCAL_CRATE).get(&def_id).and_then(|monos| monos.get(&substs).cloned())
330+
} else {
331+
None
332+
}
333+
}
334+
314335
fn is_unreachable_local_definition_provider(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
315336
if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
316337
!tcx.reachable_set(LOCAL_CRATE).contains(&hir_id)
@@ -325,6 +346,7 @@ pub fn provide(providers: &mut Providers<'_>) {
325346
providers.exported_symbols = exported_symbols_provider_local;
326347
providers.upstream_monomorphizations = upstream_monomorphizations_provider;
327348
providers.is_unreachable_local_definition = is_unreachable_local_definition_provider;
349+
providers.upstream_drop_glue_for = upstream_drop_glue_for_provider;
328350
}
329351

330352
pub fn provide_extern(providers: &mut Providers<'_>) {

src/librustc_codegen_ssa/back/write.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ use super::command::Command;
22
use super::link::{self, get_linker, remove};
33
use super::linker::LinkerInfo;
44
use super::lto::{self, SerializedModule};
5-
use super::symbol_export::{symbol_name_for_instance_in_crate, ExportedSymbols};
5+
use super::symbol_export::symbol_name_for_instance_in_crate;
6+
67
use crate::{
78
CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
89
RLIB_BYTECODE_EXTENSION,
@@ -12,6 +13,7 @@ use crate::traits::*;
1213
use jobserver::{Acquired, Client};
1314
use rustc::dep_graph::{WorkProduct, WorkProductFileKind, WorkProductId};
1415
use rustc::middle::cstore::EncodedMetadata;
16+
use rustc::middle::exported_symbols::SymbolExportLevel;
1517
use rustc::session::config::{
1618
self, Lto, OutputFilenames, OutputType, Passes, Sanitizer, SwitchWithOptPath,
1719
};
@@ -205,6 +207,8 @@ impl<B: WriteBackendMethods> Clone for TargetMachineFactory<B> {
205207
}
206208
}
207209

210+
pub type ExportedSymbols = FxHashMap<CrateNum, Arc<Vec<(String, SymbolExportLevel)>>>;
211+
208212
/// Additional resources used by optimize_and_codegen (not module specific)
209213
#[derive(Clone)]
210214
pub struct CodegenContext<B: WriteBackendMethods> {

src/librustc_codegen_utils/symbol_names.rs

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -129,26 +129,8 @@ fn symbol_name_provider(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> ty::Symb
129129
//
130130
// For generics we might find re-usable upstream instances. For anything
131131
// else we rely on their being a local copy available.
132-
133132
if is_generic(instance.substs) {
134-
let def_id = instance.def_id();
135-
136-
if !def_id.is_local() && tcx.sess.opts.share_generics() {
137-
// If we are re-using a monomorphization from another crate,
138-
// we have to compute the symbol hash accordingly.
139-
let upstream_monomorphizations = tcx.upstream_monomorphizations_for(def_id);
140-
141-
upstream_monomorphizations
142-
.and_then(|monos| monos.get(&instance.substs).cloned())
143-
// If there is no instance available upstream, there'll be
144-
// one in the current crate.
145-
.unwrap_or(LOCAL_CRATE)
146-
} else {
147-
// For generic functions defined in the current crate, there
148-
// can be no upstream instances. Also, if we don't share
149-
// generics, we'll instantiate a local copy too.
150-
LOCAL_CRATE
151-
}
133+
instance.upstream_monomorphization(tcx).unwrap_or(LOCAL_CRATE)
152134
} else {
153135
// For non-generic things that need to avoid naming conflicts, we
154136
// always instantiate a copy in the local crate.

0 commit comments

Comments
 (0)