Skip to content

Commit 1807305

Browse files
committed
Auto merge of #86698 - cjgillot:modc, r=estebank
Move OnDiskCache to rustc_query_impl. This should be the last remnant of the query implementation that was still in rustc_middle.
2 parents 5a8a441 + 5b92150 commit 1807305

File tree

15 files changed

+231
-204
lines changed

15 files changed

+231
-204
lines changed

Cargo.lock

+4
Original file line numberDiff line numberDiff line change
@@ -4242,12 +4242,16 @@ version = "0.0.0"
42424242
dependencies = [
42434243
"measureme",
42444244
"rustc-rayon-core",
4245+
"rustc_ast",
42454246
"rustc_data_structures",
42464247
"rustc_errors",
42474248
"rustc_hir",
4249+
"rustc_index",
4250+
"rustc_macros",
42484251
"rustc_middle",
42494252
"rustc_query_system",
42504253
"rustc_serialize",
4254+
"rustc_session",
42514255
"rustc_span",
42524256
"tracing",
42534257
]

compiler/rustc_incremental/src/persist/load.rs

+4-6
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
33
use rustc_data_structures::fx::FxHashMap;
44
use rustc_middle::dep_graph::{SerializedDepGraph, WorkProduct, WorkProductId};
5-
use rustc_middle::ty::query::OnDiskCache;
5+
use rustc_middle::ty::OnDiskCache;
66
use rustc_serialize::opaque::Decoder;
77
use rustc_serialize::Decodable;
88
use rustc_session::Session;
@@ -198,7 +198,7 @@ pub fn load_dep_graph(sess: &Session) -> DepGraphFuture {
198198
/// If we are not in incremental compilation mode, returns `None`.
199199
/// Otherwise, tries to load the query result cache from disk,
200200
/// creating an empty cache if it could not be loaded.
201-
pub fn load_query_result_cache<'a>(sess: &'a Session) -> Option<OnDiskCache<'a>> {
201+
pub fn load_query_result_cache<'a, C: OnDiskCache<'a>>(sess: &'a Session) -> Option<C> {
202202
if sess.opts.incremental.is_none() {
203203
return None;
204204
}
@@ -210,9 +210,7 @@ pub fn load_query_result_cache<'a>(sess: &'a Session) -> Option<OnDiskCache<'a>>
210210
&query_cache_path(sess),
211211
sess.is_nightly_build(),
212212
) {
213-
LoadResult::Ok { data: (bytes, start_pos) } => {
214-
Some(OnDiskCache::new(sess, bytes, start_pos))
215-
}
216-
_ => Some(OnDiskCache::new_empty(sess.source_map())),
213+
LoadResult::Ok { data: (bytes, start_pos) } => Some(C::new(sess, bytes, start_pos)),
214+
_ => Some(C::new_empty(sess.source_map())),
217215
}
218216
}

compiler/rustc_interface/src/interface.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use rustc_errors::{ErrorReported, Handler};
1212
use rustc_lint::LintStore;
1313
use rustc_middle::ty;
1414
use rustc_parse::new_parser_from_source_str;
15+
use rustc_query_impl::QueryCtxt;
1516
use rustc_session::config::{self, ErrorOutputType, Input, OutputFilenames};
1617
use rustc_session::early_error;
1718
use rustc_session::lint;
@@ -233,7 +234,7 @@ pub fn try_print_query_stack(handler: &Handler, num_frames: Option<usize>) {
233234
// state if it was responsible for triggering the panic.
234235
let i = ty::tls::with_context_opt(|icx| {
235236
if let Some(icx) = icx {
236-
icx.tcx.queries.try_print_query_stack(icx.tcx, icx.query, handler, num_frames)
237+
QueryCtxt::from_tcx(icx.tcx).try_print_query_stack(icx.query, handler, num_frames)
237238
} else {
238239
0
239240
}

compiler/rustc_interface/src/passes.rs

+5-3
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ use rustc_mir_build as mir_build;
2626
use rustc_parse::{parse_crate_from_file, parse_crate_from_source_str};
2727
use rustc_passes::{self, hir_stats, layout_test};
2828
use rustc_plugin_impl as plugin;
29-
use rustc_query_impl::Queries as TcxQueries;
29+
use rustc_query_impl::{OnDiskCache, Queries as TcxQueries};
3030
use rustc_resolve::{Resolver, ResolverArenas};
3131
use rustc_serialize::json;
3232
use rustc_session::config::{CrateType, Input, OutputFilenames, OutputType, PpMode, PpSourceMode};
@@ -819,7 +819,9 @@ pub fn create_global_ctxt<'tcx>(
819819
callback(sess, &mut local_providers, &mut extern_providers);
820820
}
821821

822-
let queries = queries.get_or_init(|| TcxQueries::new(local_providers, extern_providers));
822+
let queries = queries.get_or_init(|| {
823+
TcxQueries::new(local_providers, extern_providers, query_result_on_disk_cache)
824+
});
823825

824826
let gcx = sess.time("setup_global_ctxt", || {
825827
global_ctxt.get_or_init(move || {
@@ -830,7 +832,7 @@ pub fn create_global_ctxt<'tcx>(
830832
resolver_outputs,
831833
krate,
832834
dep_graph,
833-
query_result_on_disk_cache,
835+
queries.on_disk_cache.as_ref().map(OnDiskCache::as_dyn),
834836
queries.as_dyn(),
835837
&crate_name,
836838
outputs,

compiler/rustc_interface/src/util.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ use rustc_errors::registry::Registry;
1010
use rustc_metadata::dynamic_lib::DynamicLibrary;
1111
#[cfg(parallel_compiler)]
1212
use rustc_middle::ty::tls;
13+
#[cfg(parallel_compiler)]
14+
use rustc_query_impl::QueryCtxt;
1315
use rustc_resolve::{self, Resolver};
1416
use rustc_session as session;
1517
use rustc_session::config::{self, CrateType};
@@ -176,7 +178,7 @@ unsafe fn handle_deadlock() {
176178
thread::spawn(move || {
177179
tls::enter_context(icx, |_| {
178180
rustc_span::set_session_globals_then(session_globals, || {
179-
tls::with(|tcx| tcx.queries.deadlock(tcx, &registry))
181+
tls::with(|tcx| QueryCtxt::from_tcx(tcx).deadlock(&registry))
180182
})
181183
});
182184
});

compiler/rustc_macros/src/query.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ fn add_query_description_impl(
367367
tcx: QueryCtxt<'tcx>,
368368
id: SerializedDepNodeIndex
369369
) -> Option<Self::Value> {
370-
tcx.on_disk_cache.as_ref()?.try_load_query_result(*tcx, id)
370+
tcx.on_disk_cache().as_ref()?.try_load_query_result(*tcx, id)
371371
}
372372
}
373373
};

compiler/rustc_metadata/src/creader.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,10 @@ impl<'a> std::fmt::Debug for CrateDump<'a> {
131131

132132
impl CStore {
133133
pub fn from_tcx(tcx: TyCtxt<'_>) -> &CStore {
134-
tcx.cstore_as_any().downcast_ref::<CStore>().expect("`tcx.cstore` is not a `CStore`")
134+
tcx.cstore_untracked()
135+
.as_any()
136+
.downcast_ref::<CStore>()
137+
.expect("`tcx.cstore` is not a `CStore`")
135138
}
136139

137140
fn alloc_new_crate_num(&mut self) -> CrateNum {

compiler/rustc_middle/src/query/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -724,7 +724,7 @@ rustc_queries! {
724724
cache_on_disk_if { true }
725725
load_cached(tcx, id) {
726726
let typeck_results: Option<ty::TypeckResults<'tcx>> = tcx
727-
.on_disk_cache.as_ref()
727+
.on_disk_cache().as_ref()
728728
.and_then(|c| c.try_load_query_result(*tcx, id));
729729

730730
typeck_results.map(|x| &*tcx.arena.alloc(x))

compiler/rustc_middle/src/ty/context.rs

+50-10
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Type context book-keeping.
22
33
use crate::arena::Arena;
4-
use crate::dep_graph::DepGraph;
4+
use crate::dep_graph::{DepGraph, DepNode};
55
use crate::hir::place::Place as HirPlace;
66
use crate::ich::{NodeIdHashingMode, StableHashingContext};
77
use crate::infer::canonical::{Canonical, CanonicalVarInfo, CanonicalVarInfos};
@@ -14,7 +14,7 @@ use crate::mir::interpret::{self, AllocId, Allocation, ConstValue, Scalar};
1414
use crate::mir::{Body, Field, Local, Place, PlaceElem, ProjectionKind, Promoted};
1515
use crate::thir::Thir;
1616
use crate::traits;
17-
use crate::ty::query::{self, OnDiskCache, TyCtxtAt};
17+
use crate::ty::query::{self, TyCtxtAt};
1818
use crate::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, Subst, SubstsRef, UserSubsts};
1919
use crate::ty::TyKind::*;
2020
use crate::ty::{
@@ -52,8 +52,8 @@ use rustc_session::config::{BorrowckMode, CrateType, OutputFilenames};
5252
use rustc_session::lint::{Level, Lint};
5353
use rustc_session::Limit;
5454
use rustc_session::Session;
55-
use rustc_span::def_id::StableCrateId;
56-
use rustc_span::source_map::MultiSpan;
55+
use rustc_span::def_id::{DefPathHash, StableCrateId};
56+
use rustc_span::source_map::{MultiSpan, SourceMap};
5757
use rustc_span::symbol::{kw, sym, Ident, Symbol};
5858
use rustc_span::{Span, DUMMY_SP};
5959
use rustc_target::abi::{Layout, TargetDataLayout, VariantIdx};
@@ -71,6 +71,40 @@ use std::mem;
7171
use std::ops::{Bound, Deref};
7272
use std::sync::Arc;
7373

74+
pub trait OnDiskCache<'tcx>: rustc_data_structures::sync::Sync {
75+
/// Creates a new `OnDiskCache` instance from the serialized data in `data`.
76+
fn new(sess: &'tcx Session, data: Vec<u8>, start_pos: usize) -> Self
77+
where
78+
Self: Sized;
79+
80+
fn new_empty(source_map: &'tcx SourceMap) -> Self
81+
where
82+
Self: Sized;
83+
84+
/// Converts a `DefPathHash` to its corresponding `DefId` in the current compilation
85+
/// session, if it still exists. This is used during incremental compilation to
86+
/// turn a deserialized `DefPathHash` into its current `DefId`.
87+
fn def_path_hash_to_def_id(
88+
&self,
89+
tcx: TyCtxt<'tcx>,
90+
def_path_hash: DefPathHash,
91+
) -> Option<DefId>;
92+
93+
/// If the given `dep_node`'s hash still exists in the current compilation,
94+
/// and its current `DefId` is foreign, calls `store_foreign_def_id` with it.
95+
///
96+
/// Normally, `store_foreign_def_id_hash` can be called directly by
97+
/// the dependency graph when we construct a `DepNode`. However,
98+
/// when we re-use a deserialized `DepNode` from the previous compilation
99+
/// session, we only have the `DefPathHash` available. This method is used
100+
/// to that any `DepNode` that we re-use has a `DefPathHash` -> `RawId` written
101+
/// out for usage in the next compilation session.
102+
fn register_reused_dep_node(&self, tcx: TyCtxt<'tcx>, dep_node: &DepNode);
103+
fn store_foreign_def_id_hash(&self, def_id: DefId, hash: DefPathHash);
104+
105+
fn serialize(&self, tcx: TyCtxt<'tcx>, encoder: &mut FileEncoder) -> FileEncodeResult;
106+
}
107+
74108
/// A type that is not publicly constructable. This prevents people from making [`TyKind::Error`]s
75109
/// except through the error-reporting functions on a [`tcx`][TyCtxt].
76110
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
@@ -993,7 +1027,7 @@ pub struct GlobalCtxt<'tcx> {
9931027
/// Do not access this directly. It is only meant to be used by
9941028
/// `DepGraph::try_mark_green()` and the query infrastructure.
9951029
/// This is `None` if we are not incremental compilation mode
996-
pub on_disk_cache: Option<OnDiskCache<'tcx>>,
1030+
pub on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>,
9971031

9981032
pub queries: &'tcx dyn query::QueryEngine<'tcx>,
9991033
pub query_caches: query::QueryCaches<'tcx>,
@@ -1141,7 +1175,7 @@ impl<'tcx> TyCtxt<'tcx> {
11411175
resolutions: ty::ResolverOutputs,
11421176
krate: &'tcx hir::Crate<'tcx>,
11431177
dep_graph: DepGraph,
1144-
on_disk_cache: Option<query::OnDiskCache<'tcx>>,
1178+
on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>,
11451179
queries: &'tcx dyn query::QueryEngine<'tcx>,
11461180
crate_name: &str,
11471181
output_filenames: OutputFilenames,
@@ -1308,10 +1342,16 @@ impl<'tcx> TyCtxt<'tcx> {
13081342
self.untracked_resolutions.cstore.encode_metadata(self)
13091343
}
13101344

1311-
// Note that this is *untracked* and should only be used within the query
1312-
// system if the result is otherwise tracked through queries
1313-
pub fn cstore_as_any(self) -> &'tcx dyn Any {
1314-
self.untracked_resolutions.cstore.as_any()
1345+
/// Note that this is *untracked* and should only be used within the query
1346+
/// system if the result is otherwise tracked through queries
1347+
pub fn cstore_untracked(self) -> &'tcx ty::CrateStoreDyn {
1348+
&*self.untracked_resolutions.cstore
1349+
}
1350+
1351+
/// Note that this is *untracked* and should only be used within the query
1352+
/// system if the result is otherwise tracked through queries
1353+
pub fn definitions_untracked(self) -> &'tcx hir::definitions::Definitions {
1354+
&self.untracked_resolutions.definitions
13151355
}
13161356

13171357
#[inline(always)]

compiler/rustc_middle/src/ty/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ pub use self::consts::{Const, ConstInt, ConstKind, InferConst, ScalarInt, Uneval
5959
pub use self::context::{
6060
tls, CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations,
6161
CtxtInterners, DelaySpanBugEmitted, FreeRegionInfo, GeneratorInteriorTypeCause, GlobalCtxt,
62-
Lift, TyCtxt, TypeckResults, UserType, UserTypeAnnotationIndex,
62+
Lift, OnDiskCache, TyCtxt, TypeckResults, UserType, UserTypeAnnotationIndex,
6363
};
6464
pub use self::instance::{Instance, InstanceDef};
6565
pub use self::list::List;

compiler/rustc_middle/src/ty/query/mod.rs renamed to compiler/rustc_middle/src/ty/query.rs

+2-24
Original file line numberDiff line numberDiff line change
@@ -38,14 +38,13 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
3838
use rustc_data_structures::steal::Steal;
3939
use rustc_data_structures::svh::Svh;
4040
use rustc_data_structures::sync::Lrc;
41-
use rustc_errors::{ErrorReported, Handler};
41+
use rustc_errors::ErrorReported;
4242
use rustc_hir as hir;
4343
use rustc_hir::def::DefKind;
4444
use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIdSet, LocalDefId};
4545
use rustc_hir::lang_items::{LangItem, LanguageItems};
4646
use rustc_hir::{Crate, ItemLocalId, TraitCandidate};
4747
use rustc_index::{bit_set::FiniteBitSet, vec::IndexVec};
48-
use rustc_serialize::opaque;
4948
use rustc_session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion};
5049
use rustc_session::utils::NativeLibKind;
5150
use rustc_session::Limits;
@@ -63,9 +62,6 @@ use std::sync::Arc;
6362
pub(crate) use rustc_query_system::query::QueryJobId;
6463
use rustc_query_system::query::*;
6564

66-
pub mod on_disk_cache;
67-
pub use self::on_disk_cache::OnDiskCache;
68-
6965
#[derive(Copy, Clone)]
7066
pub struct TyCtxtAt<'tcx> {
7167
pub tcx: TyCtxt<'tcx>,
@@ -235,28 +231,10 @@ macro_rules! define_callbacks {
235231
}
236232

237233
pub trait QueryEngine<'tcx>: rustc_data_structures::sync::Sync {
238-
#[cfg(parallel_compiler)]
239-
unsafe fn deadlock(&'tcx self, tcx: TyCtxt<'tcx>, registry: &rustc_rayon_core::Registry);
240-
241-
fn encode_query_results(
242-
&'tcx self,
243-
tcx: TyCtxt<'tcx>,
244-
encoder: &mut on_disk_cache::CacheEncoder<'a, 'tcx, opaque::FileEncoder>,
245-
query_result_index: &mut on_disk_cache::EncodedQueryResultIndex,
246-
) -> opaque::FileEncodeResult;
247-
248-
fn exec_cache_promotions(&'tcx self, tcx: TyCtxt<'tcx>);
234+
fn as_any(&'tcx self) -> &'tcx dyn std::any::Any;
249235

250236
fn try_mark_green(&'tcx self, tcx: TyCtxt<'tcx>, dep_node: &dep_graph::DepNode) -> bool;
251237

252-
fn try_print_query_stack(
253-
&'tcx self,
254-
tcx: TyCtxt<'tcx>,
255-
query: Option<QueryJobId<dep_graph::DepKind>>,
256-
handler: &Handler,
257-
num_frames: Option<usize>,
258-
) -> usize;
259-
260238
$($(#[$attr])*
261239
fn $name(
262240
&'tcx self,

compiler/rustc_query_impl/Cargo.toml

+5-1
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,14 @@ doctest = false
1111
measureme = "9.0.0"
1212
rustc-rayon-core = "0.3.1"
1313
tracing = "0.1"
14+
rustc_ast = { path = "../rustc_ast" }
1415
rustc_data_structures = { path = "../rustc_data_structures" }
1516
rustc_errors = { path = "../rustc_errors" }
1617
rustc_hir = { path = "../rustc_hir" }
18+
rustc_index = { path = "../rustc_index" }
19+
rustc_macros = { path = "../rustc_macros" }
1720
rustc_middle = { path = "../rustc_middle" }
1821
rustc_query_system = { path = "../rustc_query_system" }
19-
rustc_span = { path = "../rustc_span" }
2022
rustc_serialize = { path = "../rustc_serialize" }
23+
rustc_session = { path = "../rustc_session" }
24+
rustc_span = { path = "../rustc_span" }

compiler/rustc_query_impl/src/lib.rs

+7-3
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,29 @@
11
//! Support for serializing the dep-graph and reloading it.
22
33
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
4+
#![feature(crate_visibility_modifier)]
45
#![feature(in_band_lifetimes)]
56
#![feature(nll)]
67
#![feature(min_specialization)]
8+
#![feature(once_cell)]
79
#![feature(rustc_attrs)]
810
#![recursion_limit = "256"]
911

12+
#[macro_use]
13+
extern crate rustc_macros;
1014
#[macro_use]
1115
extern crate rustc_middle;
1216
#[macro_use]
1317
extern crate tracing;
1418

1519
use rustc_data_structures::fingerprint::Fingerprint;
1620
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
17-
use rustc_errors::{DiagnosticBuilder, Handler};
21+
use rustc_errors::DiagnosticBuilder;
1822
use rustc_middle::dep_graph;
1923
use rustc_middle::ich::StableHashingContext;
2024
use rustc_middle::ty::query::{query_keys, query_storage, query_stored, query_values};
2125
use rustc_middle::ty::query::{Providers, QueryEngine};
2226
use rustc_middle::ty::{self, TyCtxt};
23-
use rustc_serialize::opaque;
2427
use rustc_span::Span;
2528

2629
#[macro_use]
@@ -42,7 +45,8 @@ use rustc_query_system::query::QueryAccessors;
4245
pub use rustc_query_system::query::QueryConfig;
4346
pub(crate) use rustc_query_system::query::QueryDescription;
4447

45-
use rustc_middle::ty::query::on_disk_cache;
48+
mod on_disk_cache;
49+
pub use on_disk_cache::OnDiskCache;
4650

4751
mod profiling_support;
4852
pub use self::profiling_support::alloc_self_profile_query_strings;

0 commit comments

Comments
 (0)