Skip to content

Commit 1a609b9

Browse files
committed
Auto merge of rust-lang#122371 - oli-obk:visit_nested_body, r=<try>
Stop walking the bodies of statics for reachability, and evaluate them instead cc `@saethlin` `@RalfJung` cc rust-lang#119214 This reuses the `DefIdVisitor` from `rustc_privacy`, because they basically try to do the same thing. It can probably be extended to constants, too, but let's tackle that separately, it's likely more involved.
2 parents b0170b6 + 7b7b6b5 commit 1a609b9

File tree

6 files changed

+110
-21
lines changed

6 files changed

+110
-21
lines changed

Cargo.lock

+1
Original file line numberDiff line numberDiff line change
@@ -4400,6 +4400,7 @@ dependencies = [
44004400
"rustc_lexer",
44014401
"rustc_macros",
44024402
"rustc_middle",
4403+
"rustc_privacy",
44034404
"rustc_session",
44044405
"rustc_span",
44054406
"rustc_target",

compiler/rustc_passes/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ rustc_index = { path = "../rustc_index" }
1818
rustc_lexer = { path = "../rustc_lexer" }
1919
rustc_macros = { path = "../rustc_macros" }
2020
rustc_middle = { path = "../rustc_middle" }
21+
rustc_privacy = { path = "../rustc_privacy" }
2122
rustc_session = { path = "../rustc_session" }
2223
rustc_span = { path = "../rustc_span" }
2324
rustc_target = { path = "../rustc_target" }

compiler/rustc_passes/src/reachable.rs

+81-19
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@ use rustc_hir::intravisit::{self, Visitor};
1313
use rustc_hir::Node;
1414
use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
1515
use rustc_middle::middle::privacy::{self, Level};
16+
use rustc_middle::mir::interpret::{ConstAllocation, GlobalAlloc};
1617
use rustc_middle::query::Providers;
17-
use rustc_middle::ty::{self, TyCtxt};
18+
use rustc_middle::ty::{self, ExistentialTraitRef, TyCtxt};
19+
use rustc_privacy::DefIdVisitor;
1820
use rustc_session::config::CrateType;
1921
use rustc_target::spec::abi::Abi;
2022

@@ -64,23 +66,8 @@ impl<'tcx> Visitor<'tcx> for ReachableContext<'tcx> {
6466
_ => None,
6567
};
6668

67-
if let Some(res) = res
68-
&& let Some(def_id) = res.opt_def_id().and_then(|el| el.as_local())
69-
{
70-
if self.def_id_represents_local_inlined_item(def_id.to_def_id()) {
71-
self.worklist.push(def_id);
72-
} else {
73-
match res {
74-
// Reachable constants and reachable statics can have their contents inlined
75-
// into other crates. Mark them as reachable and recurse into their body.
76-
Res::Def(DefKind::Const | DefKind::AssocConst | DefKind::Static(_), _) => {
77-
self.worklist.push(def_id);
78-
}
79-
_ => {
80-
self.reachable_symbols.insert(def_id);
81-
}
82-
}
83-
}
69+
if let Some(res) = res {
70+
self.propagate_item(res);
8471
}
8572

8673
intravisit::walk_expr(self, expr)
@@ -197,9 +184,14 @@ impl<'tcx> ReachableContext<'tcx> {
197184
// Reachable constants will be inlined into other crates
198185
// unconditionally, so we need to make sure that their
199186
// contents are also reachable.
200-
hir::ItemKind::Const(_, _, init) | hir::ItemKind::Static(_, _, init) => {
187+
hir::ItemKind::Const(_, _, init) => {
201188
self.visit_nested_body(init);
202189
}
190+
hir::ItemKind::Static(..) => {
191+
if let Ok(alloc) = self.tcx.eval_static_initializer(item.owner_id.def_id) {
192+
self.propagate_from_alloc(item.owner_id.def_id, alloc);
193+
}
194+
}
203195

204196
// These are normal, nothing reachable about these
205197
// inherently and their children are already in the
@@ -266,6 +258,76 @@ impl<'tcx> ReachableContext<'tcx> {
266258
}
267259
}
268260
}
261+
262+
/// Finds things to add to `reachable_symbols` within allocations.
263+
/// In contrast to visit_nested_body this ignores things that were only needed to evaluate
264+
/// to the allocation.
265+
fn propagate_from_alloc(&mut self, root: LocalDefId, alloc: ConstAllocation<'tcx>) {
266+
if !self.any_library {
267+
return;
268+
}
269+
for (_, prov) in alloc.0.provenance().ptrs().iter() {
270+
match self.tcx.global_alloc(prov.alloc_id()) {
271+
GlobalAlloc::Static(def_id) => {
272+
self.propagate_item(Res::Def(self.tcx.def_kind(def_id), def_id))
273+
}
274+
GlobalAlloc::Function(instance) => {
275+
// Manually visit to actually see the instance's `DefId`. Type visitors won't see it
276+
self.propagate_item(Res::Def(
277+
self.tcx.def_kind(instance.def_id()),
278+
instance.def_id(),
279+
));
280+
self.visit(instance.args);
281+
}
282+
GlobalAlloc::VTable(ty, trait_ref) => {
283+
self.visit(ty);
284+
// Manually visit to actually see the trait's `DefId`. Type visitors won't see it
285+
if let Some(trait_ref) = trait_ref {
286+
let ExistentialTraitRef { def_id, args } = trait_ref.skip_binder();
287+
self.visit_def_id(def_id, "", &"");
288+
self.visit(args);
289+
}
290+
}
291+
GlobalAlloc::Memory(alloc) => self.propagate_from_alloc(root, alloc),
292+
}
293+
}
294+
}
295+
296+
fn propagate_item(&mut self, res: Res) {
297+
let Res::Def(kind, def_id) = res else { return };
298+
let Some(def_id) = def_id.as_local() else { return };
299+
if self.def_id_represents_local_inlined_item(def_id.to_def_id()) {
300+
self.worklist.push(def_id);
301+
} else {
302+
match kind {
303+
// Reachable constants and reachable statics can have their contents inlined
304+
// into other crates. Mark them as reachable and recurse into their body.
305+
DefKind::Const | DefKind::AssocConst | DefKind::Static(_) => {
306+
self.worklist.push(def_id);
307+
}
308+
_ => {
309+
self.reachable_symbols.insert(def_id);
310+
}
311+
}
312+
}
313+
}
314+
}
315+
316+
impl<'tcx> DefIdVisitor<'tcx> for ReachableContext<'tcx> {
317+
type Result = ();
318+
319+
fn tcx(&self) -> TyCtxt<'tcx> {
320+
self.tcx
321+
}
322+
323+
fn visit_def_id(
324+
&mut self,
325+
def_id: DefId,
326+
_kind: &str,
327+
_descr: &dyn std::fmt::Display,
328+
) -> Self::Result {
329+
self.propagate_item(Res::Def(self.tcx.def_kind(def_id), def_id))
330+
}
269331
}
270332

271333
fn check_item<'tcx>(

compiler/rustc_privacy/src/lib.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ impl<'tcx> fmt::Display for LazyDefPathStr<'tcx> {
6767
/// First, it doesn't have overridable `fn visit_trait_ref`, so we have to catch trait `DefId`s
6868
/// manually. Second, it doesn't visit some type components like signatures of fn types, or traits
6969
/// in `impl Trait`, see individual comments in `DefIdVisitorSkeleton::visit_ty`.
70-
trait DefIdVisitor<'tcx> {
70+
pub trait DefIdVisitor<'tcx> {
7171
type Result: VisitorResult = ();
7272
const SHALLOW: bool = false;
7373
const SKIP_ASSOC_TYS: bool = false;
@@ -98,7 +98,7 @@ trait DefIdVisitor<'tcx> {
9898
}
9999
}
100100

101-
struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> {
101+
pub struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> {
102102
def_id_visitor: &'v mut V,
103103
visited_opaque_tys: FxHashSet<DefId>,
104104
dummy: PhantomData<TyCtxt<'tcx>>,

tests/ui/cross-crate/auxiliary/static_init_aux.rs

+21
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
pub static V: &u32 = &X;
22
pub static F: fn() = f;
33
pub static G: fn() = G0;
4+
pub static H: &(dyn Fn() + Sync) = &h;
5+
pub static I: fn() = Helper(j).mk();
46

57
static X: u32 = 42;
68
static G0: fn() = g;
@@ -12,3 +14,22 @@ pub fn v() -> *const u32 {
1214
fn f() {}
1315

1416
fn g() {}
17+
18+
fn h() {}
19+
20+
#[derive(Copy, Clone)]
21+
struct Helper<T: Copy>(T);
22+
23+
impl<T: Copy + FnOnce()> Helper<T> {
24+
const fn mk(self) -> fn() {
25+
i::<T>
26+
}
27+
}
28+
29+
fn i<T: FnOnce()>() {
30+
assert_eq!(std::mem::size_of::<T>(), 0);
31+
// unsafe to work around the lack of a `Default` impl for function items
32+
unsafe { (std::mem::transmute_copy::<(), T>(&()))() }
33+
}
34+
35+
fn j() {}

tests/ui/cross-crate/static-init.rs

+4
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ extern crate static_init_aux as aux;
66
static V: &u32 = aux::V;
77
static F: fn() = aux::F;
88
static G: fn() = aux::G;
9+
static H: &(dyn Fn() + Sync) = aux::H;
10+
static I: fn() = aux::I;
911

1012
fn v() -> *const u32 {
1113
V
@@ -15,4 +17,6 @@ fn main() {
1517
assert_eq!(aux::v(), crate::v());
1618
F();
1719
G();
20+
H();
21+
I();
1822
}

0 commit comments

Comments
 (0)