Skip to content

Commit 09f4c9f

Browse files
committed
Auto merge of #75255 - davidtwco:polymorphisation-symbol-mangling-v0-upvar-closures, r=lcnr
instance: polymorphize upvar closures/generators This PR modifies how instances are polymorphized so that closures and generators have any closures or generators captured within their upvars also polymorphized. With the new symbol mangling, a fully polymorphised closure will produce the same symbol regardless of what it was instantiated with. However, when that polymorphised closure captures another closure as an upvar, then the type of that other closure in the upvar substitution wouldn't have been polymorphised. The other closure will still refer to the initial substitutions. Therefore, the polymorphised closure will end up hashing differently but producing the same symbol - triggering `assert_symbols_are_distinct` in MIR partitioning. The old mangling scheme had a hash at the end that meant this didn't happen (this would still have been an issue, we just didn't have a way to notice). See [this Zulip discussion for further elaboration](https://rust-lang.zulipchat.com/#narrow/stream/216091-t-compiler.2Fwg-polymorphization/topic/symbol.20mangling.20v0.20.E2.9C.95.20polymorphisation/near/206152008). r? @eddyb cc @lcnr
2 parents 4d43423 + ac50d61 commit 09f4c9f

File tree

9 files changed

+280
-20
lines changed

9 files changed

+280
-20
lines changed

src/librustc_middle/ty/flags.rs

+6
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,8 @@ impl FlagComputation {
8585
}
8686

8787
&ty::Generator(_, ref substs, _) => {
88+
self.add_flags(TypeFlags::MAY_POLYMORPHIZE);
89+
8890
let substs = substs.as_generator();
8991
let should_remove_further_specializable =
9092
!self.flags.contains(TypeFlags::STILL_FURTHER_SPECIALIZABLE);
@@ -107,6 +109,8 @@ impl FlagComputation {
107109
}
108110

109111
&ty::Closure(_, substs) => {
112+
self.add_flags(TypeFlags::MAY_POLYMORPHIZE);
113+
110114
let substs = substs.as_closure();
111115
let should_remove_further_specializable =
112116
!self.flags.contains(TypeFlags::STILL_FURTHER_SPECIALIZABLE);
@@ -192,6 +196,8 @@ impl FlagComputation {
192196
}
193197

194198
&ty::FnDef(_, substs) => {
199+
self.add_flags(TypeFlags::MAY_POLYMORPHIZE);
200+
195201
self.add_substs(substs);
196202
}
197203

src/librustc_middle/ty/fold.rs

+6
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,12 @@ pub trait TypeFoldable<'tcx>: fmt::Debug + Clone {
150150
self.has_type_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE)
151151
}
152152

153+
/// Does this value contain closures, generators or functions such that it may require
154+
/// polymorphization?
155+
fn may_polymorphize(&self) -> bool {
156+
self.has_type_flags(TypeFlags::MAY_POLYMORPHIZE)
157+
}
158+
153159
/// A visitor that does not recurse into types, works like `fn walk_shallow` in `Ty`.
154160
fn visit_tys_shallow(&self, visit: impl FnMut(Ty<'tcx>) -> bool) -> bool {
155161
pub struct Visitor<F>(F);

src/librustc_middle/ty/instance.rs

+77-20
Original file line numberDiff line numberDiff line change
@@ -474,26 +474,7 @@ impl<'tcx> Instance<'tcx> {
474474
}
475475

476476
if let InstanceDef::Item(def) = self.def {
477-
let unused = tcx.unused_generic_params(def.did);
478-
479-
if unused.is_empty() {
480-
// Exit early if every parameter was used.
481-
return self;
482-
}
483-
484-
debug!("polymorphize: unused={:?}", unused);
485-
let polymorphized_substs =
486-
InternalSubsts::for_item(tcx, def.did, |param, _| match param.kind {
487-
// If parameter is a const or type parameter..
488-
ty::GenericParamDefKind::Const | ty::GenericParamDefKind::Type { .. } if
489-
// ..and is within range and unused..
490-
unused.contains(param.index).unwrap_or(false) =>
491-
// ..then use the identity for this parameter.
492-
tcx.mk_param_from_def(param),
493-
// Otherwise, use the parameter as before.
494-
_ => self.substs[param.index as usize],
495-
});
496-
477+
let polymorphized_substs = polymorphize(tcx, def.did, self.substs);
497478
debug!("polymorphize: self={:?} polymorphized_substs={:?}", self, polymorphized_substs);
498479
Self { def: self.def, substs: polymorphized_substs }
499480
} else {
@@ -502,6 +483,82 @@ impl<'tcx> Instance<'tcx> {
502483
}
503484
}
504485

486+
fn polymorphize<'tcx>(
487+
tcx: TyCtxt<'tcx>,
488+
def_id: DefId,
489+
substs: SubstsRef<'tcx>,
490+
) -> SubstsRef<'tcx> {
491+
debug!("polymorphize({:?}, {:?})", def_id, substs);
492+
let unused = tcx.unused_generic_params(def_id);
493+
debug!("polymorphize: unused={:?}", unused);
494+
495+
struct PolymorphizationFolder<'tcx> {
496+
tcx: TyCtxt<'tcx>,
497+
};
498+
499+
impl ty::TypeFolder<'tcx> for PolymorphizationFolder<'tcx> {
500+
fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
501+
self.tcx
502+
}
503+
504+
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
505+
debug!("fold_ty: ty={:?}", ty);
506+
match ty.kind {
507+
ty::Closure(def_id, substs) => {
508+
let polymorphized_substs = polymorphize(self.tcx, def_id, substs);
509+
if substs == polymorphized_substs {
510+
ty
511+
} else {
512+
self.tcx.mk_closure(def_id, polymorphized_substs)
513+
}
514+
}
515+
ty::FnDef(def_id, substs) => {
516+
let polymorphized_substs = polymorphize(self.tcx, def_id, substs);
517+
if substs == polymorphized_substs {
518+
ty
519+
} else {
520+
self.tcx.mk_fn_def(def_id, polymorphized_substs)
521+
}
522+
}
523+
ty::Generator(def_id, substs, movability) => {
524+
let polymorphized_substs = polymorphize(self.tcx, def_id, substs);
525+
if substs == polymorphized_substs {
526+
ty
527+
} else {
528+
self.tcx.mk_generator(def_id, polymorphized_substs, movability)
529+
}
530+
}
531+
_ => ty.super_fold_with(self),
532+
}
533+
}
534+
}
535+
536+
InternalSubsts::for_item(tcx, def_id, |param, _| {
537+
let is_unused = unused.contains(param.index).unwrap_or(false);
538+
debug!("polymorphize: param={:?} is_unused={:?}", param, is_unused);
539+
match param.kind {
540+
// If parameter is a const or type parameter..
541+
ty::GenericParamDefKind::Const | ty::GenericParamDefKind::Type { .. } if
542+
// ..and is within range and unused..
543+
unused.contains(param.index).unwrap_or(false) =>
544+
// ..then use the identity for this parameter.
545+
tcx.mk_param_from_def(param),
546+
547+
// If the parameter does not contain any closures or generators, then use the
548+
// substitution directly.
549+
_ if !substs.may_polymorphize() => substs[param.index as usize],
550+
551+
// Otherwise, use the substitution after polymorphizing.
552+
_ => {
553+
let arg = substs[param.index as usize];
554+
let polymorphized_arg = arg.fold_with(&mut PolymorphizationFolder { tcx });
555+
debug!("polymorphize: arg={:?} polymorphized_arg={:?}", arg, polymorphized_arg);
556+
ty::GenericArg::from(polymorphized_arg)
557+
}
558+
}
559+
})
560+
}
561+
505562
fn needs_fn_once_adapter_shim(
506563
actual_closure_kind: ty::ClosureKind,
507564
trait_closure_kind: ty::ClosureKind,

src/librustc_middle/ty/mod.rs

+4
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,10 @@ bitflags! {
575575
/// Does this value have parameters/placeholders/inference variables which could be
576576
/// replaced later, in a way that would change the results of `impl` specialization?
577577
const STILL_FURTHER_SPECIALIZABLE = 1 << 17;
578+
579+
/// Does this value contain closures, generators or functions such that it may require
580+
/// polymorphization?
581+
const MAY_POLYMORPHIZE = 1 << 18;
578582
}
579583
}
580584

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// compile-flags:-Zpolymorphize=on -Zprint-mono-items=lazy -Copt-level=1
2+
// ignore-tidy-linelength
3+
4+
#![crate_type = "rlib"]
5+
6+
// Test that only one copy of `Iter::map` and `iter::repeat` are generated.
7+
8+
fn unused<T>() -> u64 {
9+
42
10+
}
11+
12+
fn foo<T>() {
13+
let x = [1, 2, 3, std::mem::size_of::<T>()];
14+
x.iter().map(|_| ());
15+
}
16+
17+
//~ MONO_ITEM fn core::iter[0]::adapters[0]::{{impl}}[29]::new[0]<core::slice[0]::Iter[0]<usize>, pr_75255::foo[0]::{{closure}}[0]<T>> @@ pr_75255-cgu.0[External]
18+
//~ MONO_ITEM fn core::iter[0]::traits[0]::iterator[0]::Iterator[0]::map[0]<core::slice[0]::Iter[0]<usize>, (), pr_75255::foo[0]::{{closure}}[0]<T>> @@ pr_75255-cgu.1[Internal]
19+
20+
fn bar<T>() {
21+
std::iter::repeat(unused::<T>);
22+
}
23+
24+
//~ MONO_ITEM fn core::iter[0]::sources[0]::repeat[0]<fn() -> u64> @@ pr_75255-cgu.1[Internal]
25+
26+
pub fn dispatch() {
27+
foo::<String>();
28+
foo::<Vec<String>>();
29+
30+
bar::<String>();
31+
bar::<Vec<String>>();
32+
}
33+
34+
// These are all the items that aren't relevant to the test.
35+
//~ MONO_ITEM fn core::mem[0]::size_of[0]<alloc::string[0]::String[0]> @@ pr_75255-cgu.1[Internal]
36+
//~ MONO_ITEM fn core::mem[0]::size_of[0]<alloc::vec[0]::Vec[0]<alloc::string[0]::String[0]>> @@ pr_75255-cgu.1[Internal]
37+
//~ MONO_ITEM fn core::mem[0]::size_of[0]<usize> @@ pr_75255-cgu.1[Internal]
38+
//~ MONO_ITEM fn core::ptr[0]::const_ptr[0]::{{impl}}[0]::add[0]<usize> @@ pr_75255-cgu.1[Internal]
39+
//~ MONO_ITEM fn core::ptr[0]::const_ptr[0]::{{impl}}[0]::is_null[0]<usize> @@ pr_75255-cgu.1[Internal]
40+
//~ MONO_ITEM fn core::ptr[0]::const_ptr[0]::{{impl}}[0]::offset[0]<usize> @@ pr_75255-cgu.1[Internal]
41+
//~ MONO_ITEM fn core::ptr[0]::const_ptr[0]::{{impl}}[0]::wrapping_add[0]<u8> @@ pr_75255-cgu.1[Internal]
42+
//~ MONO_ITEM fn core::ptr[0]::const_ptr[0]::{{impl}}[0]::wrapping_offset[0]<u8> @@ pr_75255-cgu.1[Internal]
43+
//~ MONO_ITEM fn core::ptr[0]::non_null[0]::{{impl}}[3]::new_unchecked[0]<usize> @@ pr_75255-cgu.1[Internal]
44+
//~ MONO_ITEM fn core::ptr[0]::null[0]<u8> @@ pr_75255-cgu.1[Internal]
45+
//~ MONO_ITEM fn core::slice[0]::{{impl}}[0]::as_ptr[0]<usize> @@ pr_75255-cgu.1[Internal]
46+
//~ MONO_ITEM fn core::slice[0]::{{impl}}[0]::iter[0]<usize> @@ pr_75255-cgu.1[Internal]
47+
//~ MONO_ITEM fn core::slice[0]::{{impl}}[0]::len[0]<usize> @@ pr_75255-cgu.1[Internal]
48+
//~ MONO_ITEM fn pr_75255::dispatch[0] @@ pr_75255-cgu.1[External]
49+
//~ MONO_ITEM fn pr_75255::foo[0]<alloc::string[0]::String[0]> @@ pr_75255-cgu.1[Internal]
50+
//~ MONO_ITEM fn pr_75255::foo[0]<alloc::vec[0]::Vec[0]<alloc::string[0]::String[0]>> @@ pr_75255-cgu.1[Internal]
51+
//~ MONO_ITEM fn pr_75255::bar[0]<alloc::string[0]::String[0]> @@ pr_75255-cgu.1[Internal]
52+
//~ MONO_ITEM fn pr_75255::bar[0]<alloc::vec[0]::Vec[0]<alloc::string[0]::String[0]>> @@ pr_75255-cgu.1[Internal]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// build-pass
2+
// compile-flags:-Zpolymorphize=on -Zsymbol-mangling-version=v0
3+
4+
fn foo(f: impl Fn()) {
5+
let x = |_: ()| ();
6+
7+
// Don't use `f` in `y`, but refer to `x` so that the closure substs contain a reference to
8+
// `x` that will differ for each instantiation despite polymorphisation of the varying
9+
// argument.
10+
let y = || x(());
11+
12+
// Consider `f` used in `foo`.
13+
f();
14+
// Use `y` so that it is visited in monomorphisation collection.
15+
y();
16+
}
17+
18+
fn entry_a() {
19+
foo(|| ());
20+
}
21+
22+
fn entry_b() {
23+
foo(|| ());
24+
}
25+
26+
fn main() {
27+
entry_a();
28+
entry_b();
29+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// build-pass
2+
// compile-flags:-Zpolymorphize=on -Zsymbol-mangling-version=v0
3+
4+
fn foo(f: impl Fn()) {
5+
// Mutate an upvar from `x` so that it implements `FnMut`.
6+
let mut outer = 3;
7+
let mut x = |_: ()| {
8+
outer = 4;
9+
()
10+
};
11+
12+
// Don't use `f` in `y`, but refer to `x` so that the closure substs contain a reference to
13+
// `x` that will differ for each instantiation despite polymorphisation of the varying
14+
// argument.
15+
let mut y = || x(());
16+
17+
// Consider `f` used in `foo`.
18+
f();
19+
// Use `y` so that it is visited in monomorphisation collection.
20+
y();
21+
}
22+
23+
fn entry_a() {
24+
foo(|| ());
25+
}
26+
27+
fn entry_b() {
28+
foo(|| ());
29+
}
30+
31+
fn main() {
32+
entry_a();
33+
entry_b();
34+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// build-pass
2+
// compile-flags:-Zpolymorphize=on -Zsymbol-mangling-version=v0
3+
4+
fn foo(f: impl Fn()) {
5+
// Move a non-copy type into `x` so that it implements `FnOnce`.
6+
let outer = Vec::<u32>::new();
7+
let x = move |_: ()| {
8+
let inner = outer;
9+
()
10+
};
11+
12+
// Don't use `f` in `y`, but refer to `x` so that the closure substs contain a reference to
13+
// `x` that will differ for each instantiation despite polymorphisation of the varying
14+
// argument.
15+
let y = || x(());
16+
17+
// Consider `f` used in `foo`.
18+
f();
19+
// Use `y` so that it is visited in monomorphisation collection.
20+
y();
21+
}
22+
23+
fn entry_a() {
24+
foo(|| ());
25+
}
26+
27+
fn entry_b() {
28+
foo(|| ());
29+
}
30+
31+
fn main() {
32+
entry_a();
33+
entry_b();
34+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// build-pass
2+
// compile-flags:-Zpolymorphize=on -Zsymbol-mangling-version=v0
3+
4+
fn y_uses_f(f: impl Fn()) {
5+
let x = |_: ()| ();
6+
7+
let y = || {
8+
f();
9+
x(());
10+
};
11+
12+
f();
13+
y();
14+
}
15+
16+
fn x_uses_f(f: impl Fn()) {
17+
let x = |_: ()| { f(); };
18+
19+
let y = || x(());
20+
21+
f();
22+
y();
23+
}
24+
25+
fn entry_a() {
26+
x_uses_f(|| ());
27+
y_uses_f(|| ());
28+
}
29+
30+
fn entry_b() {
31+
x_uses_f(|| ());
32+
y_uses_f(|| ());
33+
}
34+
35+
fn main() {
36+
entry_a();
37+
entry_b();
38+
}

0 commit comments

Comments
 (0)