Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 66d8543

Browse files
committedApr 26, 2023
Remove QueryEngine trait
1 parent 897a146 commit 66d8543

File tree

20 files changed

+271
-326
lines changed

20 files changed

+271
-326
lines changed
 

‎Cargo.lock

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3641,6 +3641,7 @@ dependencies = [
36413641
"rustc_plugin_impl",
36423642
"rustc_privacy",
36433643
"rustc_query_impl",
3644+
"rustc_query_system",
36443645
"rustc_resolve",
36453646
"rustc_session",
36463647
"rustc_span",
@@ -3770,6 +3771,7 @@ dependencies = [
37703771
"derive_more",
37713772
"either",
37723773
"gsgdt",
3774+
"measureme",
37733775
"polonius-engine",
37743776
"rustc-rayon",
37753777
"rustc-rayon-core",

‎compiler/rustc_incremental/src/persist/load.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use crate::errors;
44
use rustc_data_structures::fx::FxHashMap;
55
use rustc_data_structures::memmap::Mmap;
66
use rustc_middle::dep_graph::{SerializedDepGraph, WorkProduct, WorkProductId};
7-
use rustc_middle::ty::OnDiskCache;
7+
use rustc_middle::query::on_disk_cache::OnDiskCache;
88
use rustc_serialize::opaque::MemDecoder;
99
use rustc_serialize::Decodable;
1010
use rustc_session::config::IncrementalStateAssertion;
@@ -211,7 +211,7 @@ pub fn load_dep_graph(sess: &Session) -> DepGraphFuture {
211211
/// If we are not in incremental compilation mode, returns `None`.
212212
/// Otherwise, tries to load the query result cache from disk,
213213
/// creating an empty cache if it could not be loaded.
214-
pub fn load_query_result_cache<'a, C: OnDiskCache<'a>>(sess: &'a Session) -> Option<C> {
214+
pub fn load_query_result_cache(sess: &Session) -> Option<OnDiskCache<'_>> {
215215
if sess.opts.incremental.is_none() {
216216
return None;
217217
}
@@ -223,7 +223,9 @@ pub fn load_query_result_cache<'a, C: OnDiskCache<'a>>(sess: &'a Session) -> Opt
223223
&query_cache_path(sess),
224224
sess.is_nightly_build(),
225225
) {
226-
LoadResult::Ok { data: (bytes, start_pos) } => Some(C::new(sess, bytes, start_pos)),
227-
_ => Some(C::new_empty(sess.source_map())),
226+
LoadResult::Ok { data: (bytes, start_pos) } => {
227+
Some(OnDiskCache::new(sess, bytes, start_pos))
228+
}
229+
_ => Some(OnDiskCache::new_empty(sess.source_map())),
228230
}
229231
}

‎compiler/rustc_incremental/src/persist/save.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ pub fn save_dep_graph(tcx: TyCtxt<'_>) {
4848
move || {
4949
sess.time("incr_comp_persist_result_cache", || {
5050
// Drop the memory map so that we can remove the file and write to it.
51-
if let Some(odc) = &tcx.on_disk_cache {
51+
if let Some(odc) = &tcx.query_system.on_disk_cache {
5252
odc.drop_serialized_data(tcx);
5353
}
5454

‎compiler/rustc_interface/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ rustc_lint = { path = "../rustc_lint" }
4444
rustc_errors = { path = "../rustc_errors" }
4545
rustc_plugin_impl = { path = "../rustc_plugin_impl" }
4646
rustc_privacy = { path = "../rustc_privacy" }
47+
rustc_query_system = { path = "../rustc_query_system" }
4748
rustc_query_impl = { path = "../rustc_query_impl" }
4849
rustc_resolve = { path = "../rustc_resolve" }
4950
rustc_target = { path = "../rustc_target" }

‎compiler/rustc_interface/src/interface.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use rustc_lint::LintStore;
1212
use rustc_middle::ty;
1313
use rustc_parse::maybe_new_parser_from_source_str;
1414
use rustc_query_impl::QueryCtxt;
15+
use rustc_query_system::query::print_query_stack;
1516
use rustc_session::config::{self, CheckCfg, ErrorOutputType, Input, OutputFilenames};
1617
use rustc_session::lint;
1718
use rustc_session::parse::{CrateConfig, ParseSess};
@@ -317,7 +318,7 @@ pub fn try_print_query_stack(handler: &Handler, num_frames: Option<usize>) {
317318
// state if it was responsible for triggering the panic.
318319
let i = ty::tls::with_context_opt(|icx| {
319320
if let Some(icx) = icx {
320-
QueryCtxt::from_tcx(icx.tcx).try_print_query_stack(icx.query, handler, num_frames)
321+
print_query_stack(QueryCtxt { tcx: icx.tcx }, icx.query, handler, num_frames)
321322
} else {
322323
0
323324
}

‎compiler/rustc_interface/src/passes.rs

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ use rustc_mir_build as mir_build;
2323
use rustc_parse::{parse_crate_from_file, parse_crate_from_source_str, validate_attr};
2424
use rustc_passes::{self, hir_stats, layout_test};
2525
use rustc_plugin_impl as plugin;
26-
use rustc_query_impl::{OnDiskCache, Queries as TcxQueries};
2726
use rustc_resolve::Resolver;
2827
use rustc_session::config::{CrateType, Input, OutputFilenames, OutputType};
2928
use rustc_session::cstore::{MetadataLoader, Untracked};
@@ -669,7 +668,6 @@ pub fn create_global_ctxt<'tcx>(
669668
lint_store: Lrc<LintStore>,
670669
dep_graph: DepGraph,
671670
untracked: Untracked,
672-
queries: &'tcx OnceCell<TcxQueries<'tcx>>,
673671
gcx_cell: &'tcx OnceCell<GlobalCtxt<'tcx>>,
674672
arena: &'tcx WorkerLocal<Arena<'tcx>>,
675673
hir_arena: &'tcx WorkerLocal<rustc_hir::Arena<'tcx>>,
@@ -693,10 +691,6 @@ pub fn create_global_ctxt<'tcx>(
693691
callback(sess, &mut local_providers, &mut extern_providers);
694692
}
695693

696-
let queries = queries.get_or_init(|| {
697-
TcxQueries::new(local_providers, extern_providers, query_result_on_disk_cache)
698-
});
699-
700694
sess.time("setup_global_ctxt", || {
701695
gcx_cell.get_or_init(move || {
702696
TyCtxt::create_global_ctxt(
@@ -706,9 +700,9 @@ pub fn create_global_ctxt<'tcx>(
706700
hir_arena,
707701
untracked,
708702
dep_graph,
709-
queries.on_disk_cache.as_ref().map(OnDiskCache::as_dyn),
710-
queries.as_dyn(),
703+
query_result_on_disk_cache,
711704
rustc_query_impl::query_callbacks(arena),
705+
rustc_query_impl::query_system_fns(local_providers, extern_providers),
712706
)
713707
})
714708
})

‎compiler/rustc_interface/src/queries.rs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ use rustc_metadata::creader::CStore;
1616
use rustc_middle::arena::Arena;
1717
use rustc_middle::dep_graph::DepGraph;
1818
use rustc_middle::ty::{GlobalCtxt, TyCtxt};
19-
use rustc_query_impl::Queries as TcxQueries;
2019
use rustc_session::config::{self, OutputFilenames, OutputType};
2120
use rustc_session::cstore::Untracked;
2221
use rustc_session::{output::find_crate_name, Session};
@@ -81,7 +80,6 @@ impl<T> Default for Query<T> {
8180
pub struct Queries<'tcx> {
8281
compiler: &'tcx Compiler,
8382
gcx_cell: OnceCell<GlobalCtxt<'tcx>>,
84-
queries: OnceCell<TcxQueries<'tcx>>,
8583

8684
arena: WorkerLocal<Arena<'tcx>>,
8785
hir_arena: WorkerLocal<rustc_hir::Arena<'tcx>>,
@@ -102,7 +100,6 @@ impl<'tcx> Queries<'tcx> {
102100
Queries {
103101
compiler,
104102
gcx_cell: OnceCell::new(),
105-
queries: OnceCell::new(),
106103
arena: WorkerLocal::new(|_| Arena::default()),
107104
hir_arena: WorkerLocal::new(|_| rustc_hir::Arena::default()),
108105
dep_graph_future: Default::default(),
@@ -225,7 +222,6 @@ impl<'tcx> Queries<'tcx> {
225222
lint_store,
226223
self.dep_graph()?.steal(),
227224
untracked,
228-
&self.queries,
229225
&self.gcx_cell,
230226
&self.arena,
231227
&self.hir_arena,

‎compiler/rustc_interface/src/util.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,8 @@ pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
168168
) -> R {
169169
use rustc_data_structures::jobserver;
170170
use rustc_middle::ty::tls;
171-
use rustc_query_impl::{deadlock, QueryContext, QueryCtxt};
171+
use rustc_query_impl::QueryCtxt;
172+
use rustc_query_system::query::{deadlock, QueryContext};
172173

173174
let mut builder = rayon::ThreadPoolBuilder::new()
174175
.thread_name(|_| "rustc".to_string())
@@ -179,7 +180,7 @@ pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
179180
// On deadlock, creates a new thread and forwards information in thread
180181
// locals to it. The new thread runs the deadlock handler.
181182
let query_map = tls::with(|tcx| {
182-
QueryCtxt::from_tcx(tcx)
183+
QueryCtxt::new(tcx)
183184
.try_collect_active_jobs()
184185
.expect("active jobs shouldn't be locked in deadlock handler")
185186
});

‎compiler/rustc_middle/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ chalk-ir = "0.87.0"
1111
derive_more = "0.99.17"
1212
either = "1.5.0"
1313
gsgdt = "0.1.2"
14+
measureme = "10.0.0"
1415
polonius-engine = "0.13.0"
1516
rustc_apfloat = { path = "../rustc_apfloat" }
1617
rustc_arena = { path = "../rustc_arena" }

‎compiler/rustc_middle/src/mir/interpret/mod.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,9 @@ pub fn specialized_encode_alloc_id<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>>(
227227
// References to statics doesn't need to know about their allocations,
228228
// just about its `DefId`.
229229
AllocDiscriminant::Static.encode(encoder);
230-
did.encode(encoder);
230+
// Cannot use `did.encode(encoder)` because of a bug around
231+
// specializations and method calls.
232+
Encodable::<E>::encode(&did, encoder);
231233
}
232234
}
233235
}

‎compiler/rustc_middle/src/query/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use rustc_span::def_id::LOCAL_CRATE;
99

1010
pub mod erase;
1111
mod keys;
12+
pub mod on_disk_cache;
1213
pub use keys::{AsLocalKey, Key, LocalCrate};
1314

1415
// Each of these queries corresponds to a function pointer field in the

‎compiler/rustc_middle/src/query/on_disk_cache.rs

Lines changed: 9 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use crate::QueryCtxt;
21
use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
32
use rustc_data_structures::memmap::Mmap;
43
use rustc_data_structures::stable_hasher::Hash64;
@@ -13,8 +12,7 @@ use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState};
1312
use rustc_middle::mir::{self, interpret};
1413
use rustc_middle::ty::codec::{RefDecodable, TyDecoder, TyEncoder};
1514
use rustc_middle::ty::{self, Ty, TyCtxt};
16-
use rustc_query_system::dep_graph::DepContext;
17-
use rustc_query_system::query::{QueryCache, QuerySideEffects};
15+
use rustc_query_system::query::QuerySideEffects;
1816
use rustc_serialize::{
1917
opaque::{FileEncodeResult, FileEncoder, IntEncodedWithFixedSize, MemDecoder},
2018
Decodable, Decoder, Encodable, Encoder,
@@ -123,7 +121,7 @@ struct SourceFileIndex(u32);
123121
pub struct AbsoluteBytePos(u64);
124122

125123
impl AbsoluteBytePos {
126-
fn new(pos: usize) -> AbsoluteBytePos {
124+
pub fn new(pos: usize) -> AbsoluteBytePos {
127125
AbsoluteBytePos(pos.try_into().expect("Incremental cache file size overflowed u64."))
128126
}
129127

@@ -158,9 +156,9 @@ impl EncodedSourceFileId {
158156
}
159157
}
160158

161-
impl<'sess> rustc_middle::ty::OnDiskCache<'sess> for OnDiskCache<'sess> {
159+
impl<'sess> OnDiskCache<'sess> {
162160
/// Creates a new `OnDiskCache` instance from the serialized data in `data`.
163-
fn new(sess: &'sess Session, data: Mmap, start_pos: usize) -> Self {
161+
pub fn new(sess: &'sess Session, data: Mmap, start_pos: usize) -> Self {
164162
debug_assert!(sess.opts.incremental.is_some());
165163

166164
// Wrap in a scope so we can borrow `data`.
@@ -193,7 +191,7 @@ impl<'sess> rustc_middle::ty::OnDiskCache<'sess> for OnDiskCache<'sess> {
193191
}
194192
}
195193

196-
fn new_empty(source_map: &'sess SourceMap) -> Self {
194+
pub fn new_empty(source_map: &'sess SourceMap) -> Self {
197195
Self {
198196
serialized_data: RwLock::new(None),
199197
file_index_to_stable_id: Default::default(),
@@ -215,7 +213,7 @@ impl<'sess> rustc_middle::ty::OnDiskCache<'sess> for OnDiskCache<'sess> {
215213
/// Cache promotions require invoking queries, which needs to read the serialized data.
216214
/// In order to serialize the new on-disk cache, the former on-disk cache file needs to be
217215
/// deleted, hence we won't be able to refer to its memmapped data.
218-
fn drop_serialized_data(&self, tcx: TyCtxt<'_>) {
216+
pub fn drop_serialized_data(&self, tcx: TyCtxt<'_>) {
219217
// Load everything into memory so we can write it out to the on-disk
220218
// cache. The vast majority of cacheable query results should already
221219
// be in memory, so this should be a cheap operation.
@@ -227,7 +225,7 @@ impl<'sess> rustc_middle::ty::OnDiskCache<'sess> for OnDiskCache<'sess> {
227225
*self.serialized_data.write() = None;
228226
}
229227

230-
fn serialize(&self, tcx: TyCtxt<'_>, encoder: FileEncoder) -> FileEncodeResult {
228+
pub fn serialize(&self, tcx: TyCtxt<'_>, encoder: FileEncoder) -> FileEncodeResult {
231229
// Serializing the `DepGraph` should not modify it.
232230
tcx.dep_graph.with_ignore(|| {
233231
// Allocate `SourceFileIndex`es.
@@ -269,7 +267,7 @@ impl<'sess> rustc_middle::ty::OnDiskCache<'sess> for OnDiskCache<'sess> {
269267
tcx.sess.time("encode_query_results", || {
270268
let enc = &mut encoder;
271269
let qri = &mut query_result_index;
272-
QueryCtxt::from_tcx(tcx).encode_query_results(enc, qri);
270+
(tcx.query_system.fns.encode_query_results)(tcx, enc, qri);
273271
});
274272

275273
// Encode side effects.
@@ -358,12 +356,6 @@ impl<'sess> rustc_middle::ty::OnDiskCache<'sess> for OnDiskCache<'sess> {
358356
encoder.finish()
359357
})
360358
}
361-
}
362-
363-
impl<'sess> OnDiskCache<'sess> {
364-
pub fn as_dyn(&self) -> &dyn rustc_middle::ty::OnDiskCache<'sess> {
365-
self as _
366-
}
367359

368360
/// Loads a `QuerySideEffects` created during the previous compilation session.
369361
pub fn load_side_effects(
@@ -855,7 +847,7 @@ impl<'a, 'tcx> CacheEncoder<'a, 'tcx> {
855847
/// encode the specified tag, then the given value, then the number of
856848
/// bytes taken up by tag and value. On decoding, we can then verify that
857849
/// we get the expected tag and read the expected number of bytes.
858-
fn encode_tagged<T: Encodable<Self>, V: Encodable<Self>>(&mut self, tag: T, value: &V) {
850+
pub fn encode_tagged<T: Encodable<Self>, V: Encodable<Self>>(&mut self, tag: T, value: &V) {
859851
let start_pos = self.position();
860852

861853
tag.encode(self);
@@ -1032,33 +1024,3 @@ impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx>> for [u8] {
10321024
self.encode(&mut e.encoder);
10331025
}
10341026
}
1035-
1036-
pub(crate) fn encode_query_results<'a, 'tcx, Q>(
1037-
query: Q,
1038-
qcx: QueryCtxt<'tcx>,
1039-
encoder: &mut CacheEncoder<'a, 'tcx>,
1040-
query_result_index: &mut EncodedDepNodeIndex,
1041-
) where
1042-
Q: super::QueryConfigRestored<'tcx>,
1043-
Q::RestoredValue: Encodable<CacheEncoder<'a, 'tcx>>,
1044-
{
1045-
let _timer = qcx
1046-
.tcx
1047-
.profiler()
1048-
.verbose_generic_activity_with_arg("encode_query_results_for", query.name());
1049-
1050-
assert!(query.query_state(qcx).all_inactive());
1051-
let cache = query.query_cache(qcx);
1052-
cache.iter(&mut |key, value, dep_node| {
1053-
if query.cache_on_disk(qcx.tcx, &key) {
1054-
let dep_node = SerializedDepNodeIndex::new(dep_node.index());
1055-
1056-
// Record position of the cache entry.
1057-
query_result_index.push((dep_node, AbsoluteBytePos::new(encoder.encoder.position())));
1058-
1059-
// Encode the type check tables with the `SerializedDepNodeIndex`
1060-
// as tag.
1061-
encoder.encode_tagged(dep_node, &Q::restore(*value));
1062-
}
1063-
});
1064-
}

‎compiler/rustc_middle/src/ty/codec.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -500,7 +500,6 @@ impl_arena_copy_decoder! {<'tcx>
500500
macro_rules! implement_ty_decoder {
501501
($DecoderName:ident <$($typaram:tt),*>) => {
502502
mod __ty_decoder_impl {
503-
use std::borrow::Cow;
504503
use rustc_serialize::Decoder;
505504

506505
use super::$DecoderName;

‎compiler/rustc_middle/src/ty/context.rs

Lines changed: 7 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,14 @@ use crate::middle::resolve_bound_vars;
1414
use crate::middle::stability;
1515
use crate::mir::interpret::{self, Allocation, ConstAllocation};
1616
use crate::mir::{Body, Local, Place, PlaceElem, ProjectionKind, Promoted};
17+
use crate::query::on_disk_cache::OnDiskCache;
1718
use crate::query::LocalCrate;
1819
use crate::thir::Thir;
1920
use crate::traits;
2021
use crate::traits::solve;
2122
use crate::traits::solve::{ExternalConstraints, ExternalConstraintsData};
23+
use crate::ty::query::QuerySystem;
24+
use crate::ty::query::QuerySystemFns;
2225
use crate::ty::query::{self, TyCtxtAt};
2326
use crate::ty::{
2427
self, AdtDef, AdtDefData, AdtKind, Binder, Const, ConstData, FloatTy, FloatVar, FloatVid,
@@ -31,7 +34,6 @@ use rustc_ast::{self as ast, attr};
3134
use rustc_data_structures::fingerprint::Fingerprint;
3235
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
3336
use rustc_data_structures::intern::Interned;
34-
use rustc_data_structures::memmap::Mmap;
3537
use rustc_data_structures::profiling::SelfProfilerRef;
3638
use rustc_data_structures::sharded::{IntoPointer, ShardedHashMap};
3739
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
@@ -61,7 +63,6 @@ use rustc_session::lint::Lint;
6163
use rustc_session::Limit;
6264
use rustc_session::Session;
6365
use rustc_span::def_id::{DefPathHash, StableCrateId};
64-
use rustc_span::source_map::SourceMap;
6566
use rustc_span::symbol::{kw, sym, Ident, Symbol};
6667
use rustc_span::{Span, DUMMY_SP};
6768
use rustc_target::abi::{FieldIdx, Layout, LayoutS, TargetDataLayout, VariantIdx};
@@ -84,21 +85,6 @@ use super::query::IntoQueryParam;
8485

8586
const TINY_CONST_EVAL_LIMIT: Limit = Limit(20);
8687

87-
pub trait OnDiskCache<'tcx>: rustc_data_structures::sync::Sync {
88-
/// Creates a new `OnDiskCache` instance from the serialized data in `data`.
89-
fn new(sess: &'tcx Session, data: Mmap, start_pos: usize) -> Self
90-
where
91-
Self: Sized;
92-
93-
fn new_empty(source_map: &'tcx SourceMap) -> Self
94-
where
95-
Self: Sized;
96-
97-
fn drop_serialized_data(&self, tcx: TyCtxt<'tcx>);
98-
99-
fn serialize(&self, tcx: TyCtxt<'tcx>, encoder: FileEncoder) -> FileEncodeResult;
100-
}
101-
10288
#[allow(rustc::usage_of_ty_tykind)]
10389
impl<'tcx> Interner for TyCtxt<'tcx> {
10490
type AdtDef = ty::AdtDef<'tcx>;
@@ -527,13 +513,6 @@ pub struct GlobalCtxt<'tcx> {
527513

528514
untracked: Untracked,
529515

530-
/// This provides access to the incremental compilation on-disk cache for query results.
531-
/// Do not access this directly. It is only meant to be used by
532-
/// `DepGraph::try_mark_green()` and the query infrastructure.
533-
/// This is `None` if we are not incremental compilation mode
534-
pub on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>,
535-
536-
pub queries: &'tcx dyn query::QueryEngine<'tcx>,
537516
pub query_system: query::QuerySystem<'tcx>,
538517
pub(crate) query_kinds: &'tcx [DepKindStruct<'tcx>],
539518

@@ -674,9 +653,9 @@ impl<'tcx> TyCtxt<'tcx> {
674653
hir_arena: &'tcx WorkerLocal<hir::Arena<'tcx>>,
675654
untracked: Untracked,
676655
dep_graph: DepGraph,
677-
on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>,
678-
queries: &'tcx dyn query::QueryEngine<'tcx>,
656+
on_disk_cache: Option<OnDiskCache<'tcx>>,
679657
query_kinds: &'tcx [DepKindStruct<'tcx>],
658+
query_system_fns: QuerySystemFns<'tcx>,
680659
) -> GlobalCtxt<'tcx> {
681660
let data_layout = s.target.parse_data_layout().unwrap_or_else(|err| {
682661
s.emit_fatal(err);
@@ -698,9 +677,7 @@ impl<'tcx> TyCtxt<'tcx> {
698677
lifetimes: common_lifetimes,
699678
consts: common_consts,
700679
untracked,
701-
on_disk_cache,
702-
queries,
703-
query_system: Default::default(),
680+
query_system: QuerySystem::new(query_system_fns, on_disk_cache),
704681
query_kinds,
705682
ty_rcache: Default::default(),
706683
pred_rcache: Default::default(),
@@ -1039,7 +1016,7 @@ impl<'tcx> TyCtxt<'tcx> {
10391016
}
10401017

10411018
pub fn serialize_query_result_cache(self, encoder: FileEncoder) -> FileEncodeResult {
1042-
self.on_disk_cache.as_ref().map_or(Ok(0), |c| c.serialize(self, encoder))
1019+
self.query_system.on_disk_cache.as_ref().map_or(Ok(0), |c| c.serialize(self, encoder))
10431020
}
10441021

10451022
/// If `true`, we should use lazy normalization for constants, otherwise

‎compiler/rustc_middle/src/ty/mod.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,7 @@ pub use self::consts::{
8484
Const, ConstData, ConstInt, ConstKind, Expr, InferConst, ScalarInt, UnevaluatedConst, ValTree,
8585
};
8686
pub use self::context::{
87-
tls, CtxtInterners, DeducedParamAttrs, FreeRegionInfo, GlobalCtxt, Lift, OnDiskCache, TyCtxt,
88-
TyCtxtFeed,
87+
tls, CtxtInterners, DeducedParamAttrs, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt, TyCtxtFeed,
8988
};
9089
pub use self::instance::{Instance, InstanceDef, ShortInstance, UnusedGenericParams};
9190
pub use self::list::List;

‎compiler/rustc_middle/src/ty/query.rs

Lines changed: 87 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#![allow(unused_parens)]
22

33
use crate::dep_graph;
4+
use crate::dep_graph::DepKind;
45
use crate::infer::canonical::{self, Canonical};
56
use crate::lint::LintExpectation;
67
use crate::metadata::ModChild;
@@ -17,7 +18,11 @@ use crate::mir::interpret::{
1718
};
1819
use crate::mir::interpret::{LitToConstError, LitToConstInput};
1920
use crate::mir::mono::CodegenUnit;
21+
2022
use crate::query::erase::{erase, restore, Erase};
23+
use crate::query::on_disk_cache::CacheEncoder;
24+
use crate::query::on_disk_cache::EncodedDepNodeIndex;
25+
use crate::query::on_disk_cache::OnDiskCache;
2126
use crate::query::{AsLocalKey, Key};
2227
use crate::thir;
2328
use crate::traits::query::{
@@ -38,13 +43,16 @@ use crate::ty::subst::{GenericArg, SubstsRef};
3843
use crate::ty::util::AlwaysRequiresDrop;
3944
use crate::ty::GeneratorDiagnosticData;
4045
use crate::ty::{self, CrateInherentImpls, ParamEnvAnd, Ty, TyCtxt, UnusedGenericParams};
46+
use measureme::StringId;
4147
use rustc_arena::TypedArena;
4248
use rustc_ast as ast;
4349
use rustc_ast::expand::allocator::AllocatorKind;
4450
use rustc_attr as attr;
51+
use rustc_data_structures::fingerprint::Fingerprint;
4552
use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet};
4653
use rustc_data_structures::steal::Steal;
4754
use rustc_data_structures::svh::Svh;
55+
use rustc_data_structures::sync::AtomicU64;
4856
use rustc_data_structures::sync::Lrc;
4957
use rustc_data_structures::sync::WorkerLocal;
5058
use rustc_data_structures::unord::UnordSet;
@@ -58,6 +66,7 @@ use rustc_hir::hir_id::OwnerId;
5866
use rustc_hir::lang_items::{LangItem, LanguageItems};
5967
use rustc_hir::{Crate, ItemLocalId, TraitCandidate};
6068
use rustc_index::IndexVec;
69+
use rustc_query_system::ich::StableHashingContext;
6170
pub(crate) use rustc_query_system::query::QueryJobId;
6271
use rustc_query_system::query::*;
6372
use rustc_session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion};
@@ -76,17 +85,70 @@ use std::ops::Deref;
7685
use std::path::PathBuf;
7786
use std::sync::Arc;
7887

79-
use rustc_data_structures::fingerprint::Fingerprint;
80-
use rustc_query_system::ich::StableHashingContext;
88+
pub struct QueryKeyStringCache {
89+
pub def_id_cache: FxHashMap<DefId, StringId>,
90+
}
91+
92+
impl QueryKeyStringCache {
93+
pub fn new() -> QueryKeyStringCache {
94+
QueryKeyStringCache { def_id_cache: Default::default() }
95+
}
96+
}
97+
98+
#[derive(Clone, Copy)]
99+
pub struct QueryStruct<'tcx> {
100+
pub try_collect_active_jobs: fn(TyCtxt<'tcx>, &mut QueryMap<DepKind>) -> Option<()>,
101+
pub alloc_self_profile_query_strings: fn(TyCtxt<'tcx>, &mut QueryKeyStringCache),
102+
pub encode_query_results:
103+
Option<fn(TyCtxt<'tcx>, &mut CacheEncoder<'_, 'tcx>, &mut EncodedDepNodeIndex)>,
104+
}
105+
106+
pub struct QuerySystemFns<'tcx> {
107+
pub engine: QueryEngine,
108+
pub local_providers: Providers,
109+
pub extern_providers: ExternProviders,
110+
pub query_structs: Vec<QueryStruct<'tcx>>,
111+
pub encode_query_results: fn(
112+
tcx: TyCtxt<'tcx>,
113+
encoder: &mut CacheEncoder<'_, 'tcx>,
114+
query_result_index: &mut EncodedDepNodeIndex,
115+
),
116+
pub try_mark_green: fn(tcx: TyCtxt<'tcx>, dep_node: &dep_graph::DepNode) -> bool,
117+
}
81118

82-
#[derive(Default)]
83119
pub struct QuerySystem<'tcx> {
120+
pub states: QueryStates<'tcx>,
84121
pub arenas: QueryArenas<'tcx>,
85122
pub caches: QueryCaches<'tcx>,
123+
124+
/// This provides access to the incremental compilation on-disk cache for query results.
125+
/// Do not access this directly. It is only meant to be used by
126+
/// `DepGraph::try_mark_green()` and the query infrastructure.
127+
/// This is `None` if we are not incremental compilation mode
128+
pub on_disk_cache: Option<OnDiskCache<'tcx>>,
129+
130+
pub fns: QuerySystemFns<'tcx>,
131+
132+
pub jobs: AtomicU64,
133+
86134
// Since we erase query value types we tell the typesystem about them with `PhantomData`.
87135
_phantom_values: QueryPhantomValues<'tcx>,
88136
}
89137

138+
impl<'tcx> QuerySystem<'tcx> {
139+
pub fn new(fns: QuerySystemFns<'tcx>, on_disk_cache: Option<OnDiskCache<'tcx>>) -> Self {
140+
QuerySystem {
141+
states: Default::default(),
142+
arenas: Default::default(),
143+
caches: Default::default(),
144+
on_disk_cache,
145+
fns,
146+
jobs: AtomicU64::new(1),
147+
_phantom_values: Default::default(),
148+
}
149+
}
150+
}
151+
90152
#[derive(Copy, Clone)]
91153
pub struct TyCtxtAt<'tcx> {
92154
pub tcx: TyCtxt<'tcx>,
@@ -136,7 +198,7 @@ impl<'tcx> TyCtxt<'tcx> {
136198
}
137199

138200
pub fn try_mark_green(self, dep_node: &dep_graph::DepNode) -> bool {
139-
self.queries.try_mark_green(self, dep_node)
201+
(self.query_system.fns.try_mark_green)(self, dep_node)
140202
}
141203
}
142204

@@ -349,7 +411,7 @@ macro_rules! define_callbacks {
349411

350412
match try_get_cached(self.tcx, &self.tcx.query_system.caches.$name, &key) {
351413
Some(_) => return,
352-
None => self.tcx.queries.$name(
414+
None => (self.tcx.query_system.fns.engine.$name)(
353415
self.tcx,
354416
DUMMY_SP,
355417
key,
@@ -367,7 +429,7 @@ macro_rules! define_callbacks {
367429

368430
match try_get_cached(self.tcx, &self.tcx.query_system.caches.$name, &key) {
369431
Some(_) => return,
370-
None => self.tcx.queries.$name(
432+
None => (self.tcx.query_system.fns.engine.$name)(
371433
self.tcx,
372434
DUMMY_SP,
373435
key,
@@ -396,11 +458,22 @@ macro_rules! define_callbacks {
396458

397459
restore::<$V>(match try_get_cached(self.tcx, &self.tcx.query_system.caches.$name, &key) {
398460
Some(value) => value,
399-
None => self.tcx.queries.$name(self.tcx, self.span, key, QueryMode::Get).unwrap(),
461+
None => (self.tcx.query_system.fns.engine.$name)(
462+
self.tcx,
463+
self.span,
464+
key, QueryMode::Get
465+
).unwrap(),
400466
})
401467
})*
402468
}
403469

470+
#[derive(Default)]
471+
pub struct QueryStates<'tcx> {
472+
$(
473+
pub $name: QueryState<$($K)*, DepKind>,
474+
)*
475+
}
476+
404477
pub struct Providers {
405478
$(pub $name: for<'tcx> fn(
406479
TyCtxt<'tcx>,
@@ -446,19 +519,13 @@ macro_rules! define_callbacks {
446519
fn clone(&self) -> Self { *self }
447520
}
448521

449-
pub trait QueryEngine<'tcx>: rustc_data_structures::sync::Sync {
450-
fn as_any(&'tcx self) -> &'tcx dyn std::any::Any;
451-
452-
fn try_mark_green(&'tcx self, tcx: TyCtxt<'tcx>, dep_node: &dep_graph::DepNode) -> bool;
453-
454-
$($(#[$attr])*
455-
fn $name(
456-
&'tcx self,
457-
tcx: TyCtxt<'tcx>,
458-
span: Span,
459-
key: query_keys::$name<'tcx>,
460-
mode: QueryMode,
461-
) -> Option<Erase<$V>>;)*
522+
pub struct QueryEngine {
523+
$(pub $name: for<'tcx> fn(
524+
TyCtxt<'tcx>,
525+
Span,
526+
query_keys::$name<'tcx>,
527+
QueryMode,
528+
) -> Option<Erase<$V>>,)*
462529
}
463530
};
464531
}

‎compiler/rustc_query_impl/src/lib.rs

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,36 +11,29 @@
1111
#![deny(rustc::untranslatable_diagnostic)]
1212
#![deny(rustc::diagnostic_outside_of_impl)]
1313

14-
#[macro_use]
15-
extern crate rustc_macros;
1614
#[macro_use]
1715
extern crate rustc_middle;
1816

19-
use rustc_data_structures::sync::AtomicU64;
17+
use crate::plumbing::{encode_all_query_results, try_mark_green};
2018
use rustc_middle::arena::Arena;
2119
use rustc_middle::dep_graph::{self, DepKind, DepKindStruct};
2220
use rustc_middle::query::erase::{erase, restore, Erase};
2321
use rustc_middle::query::AsLocalKey;
2422
use rustc_middle::ty::query::{
2523
query_keys, query_provided, query_provided_to_value, query_storage, query_values,
2624
};
27-
use rustc_middle::ty::query::{ExternProviders, Providers, QueryEngine};
25+
use rustc_middle::ty::query::{ExternProviders, Providers, QueryEngine, QuerySystemFns};
2826
use rustc_middle::ty::TyCtxt;
2927
use rustc_query_system::dep_graph::SerializedDepNodeIndex;
3028
use rustc_query_system::Value;
3129
use rustc_span::Span;
3230

3331
#[macro_use]
3432
mod plumbing;
35-
pub use plumbing::QueryCtxt;
36-
use rustc_query_system::query::*;
37-
#[cfg(parallel_compiler)]
38-
pub use rustc_query_system::query::{deadlock, QueryContext};
33+
pub use crate::plumbing::QueryCtxt;
3934

4035
pub use rustc_query_system::query::QueryConfig;
41-
42-
mod on_disk_cache;
43-
pub use on_disk_cache::OnDiskCache;
36+
use rustc_query_system::query::*;
4437

4538
mod profiling_support;
4639
pub use self::profiling_support::alloc_self_profile_query_strings;
@@ -54,9 +47,16 @@ trait QueryConfigRestored<'tcx>: QueryConfig<QueryCtxt<'tcx>> + Default {
5447

5548
rustc_query_append! { define_queries! }
5649

57-
impl<'tcx> Queries<'tcx> {
58-
// Force codegen in the dyn-trait transformation in this crate.
59-
pub fn as_dyn(&'tcx self) -> &'tcx dyn QueryEngine<'tcx> {
60-
self
50+
pub fn query_system_fns<'tcx>(
51+
local_providers: Providers,
52+
extern_providers: ExternProviders,
53+
) -> QuerySystemFns<'tcx> {
54+
QuerySystemFns {
55+
engine: engine(),
56+
local_providers,
57+
extern_providers,
58+
query_structs: make_dep_kind_array!(query_structs).to_vec(),
59+
encode_query_results: encode_all_query_results,
60+
try_mark_green: try_mark_green,
6161
}
6262
}

‎compiler/rustc_query_impl/src/plumbing.rs

Lines changed: 127 additions & 176 deletions
Large diffs are not rendered by default.

‎compiler/rustc_query_impl/src/profiling_support.rs

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,13 @@
1-
use crate::QueryCtxt;
21
use measureme::{StringComponent, StringId};
3-
use rustc_data_structures::fx::FxHashMap;
42
use rustc_data_structures::profiling::SelfProfiler;
53
use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, LOCAL_CRATE};
64
use rustc_hir::definitions::DefPathData;
5+
use rustc_middle::ty::query::QueryKeyStringCache;
76
use rustc_middle::ty::TyCtxt;
87
use rustc_query_system::query::QueryCache;
98
use std::fmt::Debug;
109
use std::io::Write;
1110

12-
pub(crate) struct QueryKeyStringCache {
13-
def_id_cache: FxHashMap<DefId, StringId>,
14-
}
15-
16-
impl QueryKeyStringCache {
17-
fn new() -> QueryKeyStringCache {
18-
QueryKeyStringCache { def_id_cache: Default::default() }
19-
}
20-
}
21-
2211
struct QueryKeyStringBuilder<'p, 'tcx> {
2312
profiler: &'p SelfProfiler,
2413
tcx: TyCtxt<'tcx>,
@@ -253,9 +242,8 @@ pub fn alloc_self_profile_query_strings(tcx: TyCtxt<'_>) {
253242
}
254243

255244
let mut string_cache = QueryKeyStringCache::new();
256-
let queries = QueryCtxt::from_tcx(tcx);
257245

258-
for query in &queries.queries.query_structs {
246+
for query in &tcx.query_system.fns.query_structs {
259247
(query.alloc_self_profile_query_strings)(tcx, &mut string_cache);
260248
}
261249
}

‎compiler/rustc_session/src/session.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1190,6 +1190,7 @@ impl Session {
11901190

11911191
/// Returns the number of query threads that should be used for this
11921192
/// compilation
1193+
#[inline]
11931194
pub fn threads(&self) -> usize {
11941195
self.opts.unstable_opts.threads
11951196
}

0 commit comments

Comments
 (0)
Please sign in to comment.