Skip to content

Commit 1806efe

Browse files
committed
Move DepKind to rustc_query_system and define it as u16
1 parent 66ab7e6 commit 1806efe

File tree

24 files changed

+508
-518
lines changed

24 files changed

+508
-518
lines changed

compiler/rustc_incremental/src/assert_dep_graph.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ use rustc_hir as hir;
4242
use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID};
4343
use rustc_hir::intravisit::{self, Visitor};
4444
use rustc_middle::dep_graph::{
45-
DepGraphQuery, DepKind, DepNode, DepNodeExt, DepNodeFilter, EdgeFilter,
45+
dep_kinds, DepGraphQuery, DepKind, DepNode, DepNodeExt, DepNodeFilter, EdgeFilter,
4646
};
4747
use rustc_middle::hir::nested_filter;
4848
use rustc_middle::ty::TyCtxt;
@@ -129,7 +129,7 @@ impl<'tcx> IfThisChanged<'tcx> {
129129
let dep_node_interned = self.argument(attr);
130130
let dep_node = match dep_node_interned {
131131
None => {
132-
DepNode::from_def_path_hash(self.tcx, def_path_hash, DepKind::hir_owner)
132+
DepNode::from_def_path_hash(self.tcx, def_path_hash, dep_kinds::hir_owner)
133133
}
134134
Some(n) => {
135135
match DepNode::from_label_string(self.tcx, n.as_str(), def_path_hash) {

compiler/rustc_incremental/src/persist/load.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
use crate::errors;
44
use rustc_data_structures::memmap::Mmap;
55
use rustc_data_structures::unord::UnordMap;
6-
use rustc_middle::dep_graph::{SerializedDepGraph, WorkProductMap};
6+
use rustc_middle::dep_graph::{DepsType, SerializedDepGraph, WorkProductMap};
77
use rustc_middle::query::on_disk_cache::OnDiskCache;
88
use rustc_serialize::opaque::MemDecoder;
99
use rustc_serialize::Decodable;
@@ -208,7 +208,7 @@ pub fn load_dep_graph(sess: &Session) -> DepGraphFuture {
208208
return LoadResult::DataOutOfDate;
209209
}
210210

211-
let dep_graph = SerializedDepGraph::decode(&mut decoder);
211+
let dep_graph = SerializedDepGraph::decode::<DepsType>(&mut decoder);
212212

213213
LoadResult::Ok { data: (dep_graph, prev_work_products) }
214214
}

compiler/rustc_interface/src/callbacks.rs

+42-1
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,10 @@
1010
//! origin crate when the `TyCtxt` is not present in TLS.
1111
1212
use rustc_errors::{Diagnostic, TRACK_DIAGNOSTICS};
13-
use rustc_middle::dep_graph::TaskDepsRef;
13+
use rustc_middle::dep_graph::{DepNodeExt, TaskDepsRef};
1414
use rustc_middle::ty::tls;
15+
use rustc_query_system::dep_graph::dep_node::default_dep_kind_debug;
16+
use rustc_query_system::dep_graph::{DepContext, DepKind, DepNode};
1517
use std::fmt;
1618

1719
fn track_span_parent(def_id: rustc_span::def_id::LocalDefId) {
@@ -59,10 +61,49 @@ fn def_id_debug(def_id: rustc_hir::def_id::DefId, f: &mut fmt::Formatter<'_>) ->
5961
write!(f, ")")
6062
}
6163

64+
/// This is a callback from `rustc_query_system` as it cannot access the implicit state
65+
/// in `rustc_middle` otherwise.
66+
pub fn dep_kind_debug(kind: DepKind, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67+
tls::with_opt(|opt_tcx| {
68+
if let Some(tcx) = opt_tcx {
69+
write!(f, "{}", tcx.dep_kind_info(kind).name)
70+
} else {
71+
default_dep_kind_debug(kind, f)
72+
}
73+
})
74+
}
75+
76+
/// This is a callback from `rustc_query_system` as it cannot access the implicit state
77+
/// in `rustc_middle` otherwise.
78+
pub fn dep_node_debug(node: DepNode, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79+
write!(f, "{:?}(", node.kind)?;
80+
81+
tls::with_opt(|opt_tcx| {
82+
if let Some(tcx) = opt_tcx {
83+
if let Some(def_id) = node.extract_def_id(tcx) {
84+
write!(f, "{}", tcx.def_path_debug_str(def_id))?;
85+
} else if let Some(ref s) = tcx.dep_graph.dep_node_debug_str(node) {
86+
write!(f, "{s}")?;
87+
} else {
88+
write!(f, "{}", node.hash)?;
89+
}
90+
} else {
91+
write!(f, "{}", node.hash)?;
92+
}
93+
Ok(())
94+
})?;
95+
96+
write!(f, ")")
97+
}
98+
6299
/// Sets up the callbacks in prior crates which we want to refer to the
63100
/// TyCtxt in.
64101
pub fn setup_callbacks() {
65102
rustc_span::SPAN_TRACK.swap(&(track_span_parent as fn(_)));
66103
rustc_hir::def_id::DEF_ID_DEBUG.swap(&(def_id_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
104+
rustc_query_system::dep_graph::dep_node::DEP_KIND_DEBUG
105+
.swap(&(dep_kind_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
106+
rustc_query_system::dep_graph::dep_node::DEP_NODE_DEBUG
107+
.swap(&(dep_node_debug as fn(_, &mut fmt::Formatter<'_>) -> _));
67108
TRACK_DIAGNOSTICS.swap(&(track_diagnostic as _));
68109
}

compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,8 @@ macro_rules! provide_one {
126126
// External query providers call `crate_hash` in order to register a dependency
127127
// on the crate metadata. The exception is `crate_hash` itself, which obviously
128128
// doesn't need to do this (and can't, as it would cause a query cycle).
129-
use rustc_middle::dep_graph::DepKind;
130-
if DepKind::$name != DepKind::crate_hash && $tcx.dep_graph.is_fully_enabled() {
129+
use rustc_middle::dep_graph::dep_kinds;
130+
if dep_kinds::$name != dep_kinds::crate_hash && $tcx.dep_graph.is_fully_enabled() {
131131
$tcx.ensure().crate_hash($def_id.krate);
132132
}
133133

compiler/rustc_middle/src/dep_graph/dep_node.rs

+25-54
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,9 @@ use rustc_hir::definitions::DefPathHash;
6565
use rustc_hir::{HirId, ItemLocalId, OwnerId};
6666
use rustc_query_system::dep_graph::FingerprintStyle;
6767
use rustc_span::symbol::Symbol;
68-
use std::hash::Hash;
6968

70-
pub use rustc_query_system::dep_graph::{DepContext, DepNodeParams};
69+
pub use rustc_query_system::dep_graph::dep_node::DepKind;
70+
pub use rustc_query_system::dep_graph::{DepContext, DepNode, DepNodeParams};
7171

7272
macro_rules! define_dep_nodes {
7373
(
@@ -84,55 +84,39 @@ macro_rules! define_dep_nodes {
8484
// encoding. The derived Encodable/Decodable uses leb128 encoding which is
8585
// dense when only considering this enum. But DepKind is encoded in a larger
8686
// struct, and there we can take advantage of the unused bits in the u16.
87-
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8887
#[allow(non_camel_case_types)]
89-
#[repr(u16)]
90-
pub enum DepKind {
88+
#[repr(u16)] // Must be kept in sync with the inner type of `DepKind`.
89+
enum DepKindDefs {
9190
$( $( #[$attr] )* $variant),*
9291
}
9392

94-
impl DepKind {
95-
// This const implements two things: A bounds check so that we can decode
96-
// a DepKind from a u16 with just one check, and a const check that the
97-
// discriminants of the variants have been assigned consecutively from 0
98-
// so that just the one comparison suffices to check that the u16 can be
99-
// transmuted to a DepKind.
100-
pub const VARIANTS: u16 = {
101-
let deps: &[DepKind] = &[$(DepKind::$variant,)*];
102-
let mut i = 0;
103-
while i < deps.len() {
104-
if i as u16 != deps[i] as u16 {
105-
panic!();
106-
}
107-
i += 1;
108-
}
109-
deps.len() as u16
110-
};
111-
}
93+
#[allow(non_upper_case_globals)]
94+
pub mod dep_kinds {
95+
use super::*;
11296

113-
impl<S: rustc_serialize::Encoder> rustc_serialize::Encodable<S> for DepKind {
114-
#[inline]
115-
fn encode(&self, s: &mut S) {
116-
s.emit_u16(*self as u16);
117-
}
97+
$(
98+
// The `as u16` cast must be kept in sync with the inner type of `DepKind`.
99+
pub const $variant: DepKind = DepKind::new(DepKindDefs::$variant as u16);
100+
)*
118101
}
119102

120-
impl<D: rustc_serialize::Decoder> rustc_serialize::Decodable<D> for DepKind {
121-
#[inline]
122-
fn decode(d: &mut D) -> DepKind {
123-
let discrim = d.read_u16();
124-
assert!(discrim < DepKind::VARIANTS);
125-
// SAFETY: DepKind::VARIANTS checks that the discriminant values permit
126-
// this one check to soundly guard the transmute.
127-
unsafe {
128-
std::mem::transmute::<u16, DepKind>(discrim)
103+
// This checks that the discriminants of the variants have been assigned consecutively
104+
// from 0 so that they can be used as a dense index.
105+
pub const DEP_KIND_VARIANTS: u16 = {
106+
let deps = &[$(dep_kinds::$variant,)*];
107+
let mut i = 0;
108+
while i < deps.len() {
109+
if i != deps[i].as_usize() {
110+
panic!();
129111
}
112+
i += 1;
130113
}
131-
}
114+
deps.len() as u16
115+
};
132116

133117
pub(super) fn dep_kind_from_label_string(label: &str) -> Result<DepKind, ()> {
134118
match label {
135-
$(stringify!($variant) => Ok(DepKind::$variant),)*
119+
$(stringify!($variant) => Ok(dep_kinds::$variant),)*
136120
_ => Err(()),
137121
}
138122
}
@@ -158,12 +142,10 @@ rustc_query_append!(define_dep_nodes![
158142
[] fn CompileMonoItem() -> (),
159143
]);
160144

161-
static_assert_size!(DepKind, 2);
162-
163145
// WARNING: `construct` is generic and does not know that `CompileCodegenUnit` takes `Symbol`s as keys.
164146
// Be very careful changing this type signature!
165147
pub(crate) fn make_compile_codegen_unit(tcx: TyCtxt<'_>, name: Symbol) -> DepNode {
166-
DepNode::construct(tcx, DepKind::CompileCodegenUnit, &name)
148+
DepNode::construct(tcx, dep_kinds::CompileCodegenUnit, &name)
167149
}
168150

169151
// WARNING: `construct` is generic and does not know that `CompileMonoItem` takes `MonoItem`s as keys.
@@ -172,20 +154,9 @@ pub(crate) fn make_compile_mono_item<'tcx>(
172154
tcx: TyCtxt<'tcx>,
173155
mono_item: &MonoItem<'tcx>,
174156
) -> DepNode {
175-
DepNode::construct(tcx, DepKind::CompileMonoItem, mono_item)
157+
DepNode::construct(tcx, dep_kinds::CompileMonoItem, mono_item)
176158
}
177159

178-
pub type DepNode = rustc_query_system::dep_graph::DepNode<DepKind>;
179-
180-
// We keep a lot of `DepNode`s in memory during compilation. It's not
181-
// required that their size stay the same, but we don't want to change
182-
// it inadvertently. This assert just ensures we're aware of any change.
183-
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
184-
static_assert_size!(DepNode, 18);
185-
186-
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
187-
static_assert_size!(DepNode, 24);
188-
189160
pub trait DepNodeExt: Sized {
190161
/// Extracts the DefId corresponding to this DepNode. This will work
191162
/// if two conditions are met:

compiler/rustc_middle/src/dep_graph/mod.rs

+14-50
Original file line numberDiff line numberDiff line change
@@ -6,49 +6,24 @@ use rustc_session::Session;
66
#[macro_use]
77
mod dep_node;
88

9+
pub use rustc_query_system::dep_graph::debug::EdgeFilter;
910
pub use rustc_query_system::dep_graph::{
10-
debug::DepNodeFilter, hash_result, DepContext, DepNodeColor, DepNodeIndex,
11-
SerializedDepNodeIndex, WorkProduct, WorkProductId, WorkProductMap,
11+
debug::DepNodeFilter, hash_result, DepContext, DepGraphQuery, DepNodeColor, DepNodeIndex, Deps,
12+
SerializedDepGraph, SerializedDepNodeIndex, TaskDeps, TaskDepsRef, WorkProduct, WorkProductId,
13+
WorkProductMap,
1214
};
1315

14-
pub use dep_node::{label_strs, DepKind, DepNode, DepNodeExt};
16+
pub use dep_node::{dep_kinds, label_strs, DepKind, DepNode, DepNodeExt};
1517
pub(crate) use dep_node::{make_compile_codegen_unit, make_compile_mono_item};
1618

17-
pub type DepGraph = rustc_query_system::dep_graph::DepGraph<DepKind>;
19+
pub type DepGraph = rustc_query_system::dep_graph::DepGraph<DepsType>;
1820

19-
pub type TaskDeps = rustc_query_system::dep_graph::TaskDeps<DepKind>;
20-
pub type TaskDepsRef<'a> = rustc_query_system::dep_graph::TaskDepsRef<'a, DepKind>;
21-
pub type DepGraphQuery = rustc_query_system::dep_graph::DepGraphQuery<DepKind>;
22-
pub type SerializedDepGraph = rustc_query_system::dep_graph::SerializedDepGraph<DepKind>;
23-
pub type EdgeFilter = rustc_query_system::dep_graph::debug::EdgeFilter<DepKind>;
2421
pub type DepKindStruct<'tcx> = rustc_query_system::dep_graph::DepKindStruct<TyCtxt<'tcx>>;
2522

26-
impl rustc_query_system::dep_graph::DepKind for DepKind {
27-
const NULL: Self = DepKind::Null;
28-
const RED: Self = DepKind::Red;
29-
const MAX: u16 = DepKind::VARIANTS - 1;
30-
31-
fn debug_node(node: &DepNode, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32-
write!(f, "{:?}(", node.kind)?;
33-
34-
ty::tls::with_opt(|opt_tcx| {
35-
if let Some(tcx) = opt_tcx {
36-
if let Some(def_id) = node.extract_def_id(tcx) {
37-
write!(f, "{}", tcx.def_path_debug_str(def_id))?;
38-
} else if let Some(ref s) = tcx.dep_graph.dep_node_debug_str(*node) {
39-
write!(f, "{s}")?;
40-
} else {
41-
write!(f, "{}", node.hash)?;
42-
}
43-
} else {
44-
write!(f, "{}", node.hash)?;
45-
}
46-
Ok(())
47-
})?;
48-
49-
write!(f, ")")
50-
}
23+
#[derive(Clone)]
24+
pub struct DepsType;
5125

26+
impl Deps for DepsType {
5227
fn with_deps<OP, R>(task_deps: TaskDepsRef<'_>, op: OP) -> R
5328
where
5429
OP: FnOnce() -> R,
@@ -70,24 +45,13 @@ impl rustc_query_system::dep_graph::DepKind for DepKind {
7045
})
7146
}
7247

73-
#[track_caller]
74-
#[inline]
75-
fn from_u16(u: u16) -> Self {
76-
if u > Self::MAX {
77-
panic!("Invalid DepKind {u}");
78-
}
79-
// SAFETY: See comment on DepKind::VARIANTS
80-
unsafe { std::mem::transmute(u) }
81-
}
82-
83-
#[inline]
84-
fn to_u16(self) -> u16 {
85-
self as u16
86-
}
48+
const DEP_KIND_NULL: DepKind = dep_kinds::Null;
49+
const DEP_KIND_RED: DepKind = dep_kinds::Red;
50+
const DEP_KIND_MAX: u16 = dep_node::DEP_KIND_VARIANTS - 1;
8751
}
8852

8953
impl<'tcx> DepContext for TyCtxt<'tcx> {
90-
type DepKind = DepKind;
54+
type Deps = DepsType;
9155

9256
#[inline]
9357
fn with_stable_hashing_context<R>(self, f: impl FnOnce(StableHashingContext<'_>) -> R) -> R {
@@ -111,6 +75,6 @@ impl<'tcx> DepContext for TyCtxt<'tcx> {
11175

11276
#[inline]
11377
fn dep_kind_info(&self, dk: DepKind) -> &DepKindStruct<'tcx> {
114-
&self.query_kinds[dk as usize]
78+
&self.query_kinds[dk.as_usize()]
11579
}
11680
}

compiler/rustc_middle/src/query/mod.rs

-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
#![allow(unused_parens)]
88

99
use crate::dep_graph;
10-
use crate::dep_graph::DepKind;
1110
use crate::infer::canonical::{self, Canonical};
1211
use crate::lint::LintExpectation;
1312
use crate::metadata::ModChild;

compiler/rustc_middle/src/query/plumbing.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ pub struct DynamicQuery<'tcx, C: QueryCache> {
3737
pub eval_always: bool,
3838
pub dep_kind: DepKind,
3939
pub handle_cycle_error: HandleCycleError,
40-
pub query_state: FieldOffset<QueryStates<'tcx>, QueryState<C::Key, DepKind>>,
40+
pub query_state: FieldOffset<QueryStates<'tcx>, QueryState<C::Key>>,
4141
pub query_cache: FieldOffset<QueryCaches<'tcx>, C>,
4242
pub cache_on_disk: fn(tcx: TyCtxt<'tcx>, key: &C::Key) -> bool,
4343
pub execute_query: fn(tcx: TyCtxt<'tcx>, k: C::Key) -> C::Value,
@@ -53,7 +53,7 @@ pub struct DynamicQuery<'tcx, C: QueryCache> {
5353
fn(tcx: TyCtxt<'tcx>, key: &C::Key, index: SerializedDepNodeIndex) -> bool,
5454
pub hash_result: HashResult<C::Value>,
5555
pub value_from_cycle_error:
56-
fn(tcx: TyCtxt<'tcx>, cycle: &[QueryInfo<DepKind>], guar: ErrorGuaranteed) -> C::Value,
56+
fn(tcx: TyCtxt<'tcx>, cycle: &[QueryInfo], guar: ErrorGuaranteed) -> C::Value,
5757
pub format_value: fn(&C::Value) -> String,
5858
}
5959

@@ -402,7 +402,7 @@ macro_rules! define_callbacks {
402402
#[derive(Default)]
403403
pub struct QueryStates<'tcx> {
404404
$(
405-
pub $name: QueryState<$($K)*, DepKind>,
405+
pub $name: QueryState<$($K)*>,
406406
)*
407407
}
408408

@@ -516,7 +516,7 @@ macro_rules! define_feedable {
516516
}
517517
}
518518
None => {
519-
let dep_node = dep_graph::DepNode::construct(tcx, dep_graph::DepKind::$name, &key);
519+
let dep_node = dep_graph::DepNode::construct(tcx, dep_graph::dep_kinds::$name, &key);
520520
let dep_node_index = tcx.dep_graph.with_feed_task(
521521
dep_node,
522522
tcx,

0 commit comments

Comments
 (0)