1 use crate::dep_graph::{DepNode, DepNodeIndex, SerializedDepNodeIndex};
2 use crate::mir::interpret::{AllocDecodingSession, AllocDecodingState};
3 use crate::mir::{self, interpret};
4 use crate::ty::codec::{OpaqueEncoder, RefDecodable, TyDecoder, TyEncoder};
5 use crate::ty::context::TyCtxt;
6 use crate::ty::{self, Ty};
7 use rustc_data_structures::fingerprint::{Fingerprint, FingerprintDecoder, FingerprintEncoder};
8 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
9 use rustc_data_structures::sync::{HashMapExt, Lock, Lrc, OnceCell};
10 use rustc_data_structures::thin_vec::ThinVec;
11 use rustc_errors::Diagnostic;
12 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, LOCAL_CRATE};
13 use rustc_hir::definitions::DefPathHash;
14 use rustc_hir::definitions::Definitions;
15 use rustc_index::vec::{Idx, IndexVec};
16 use rustc_serialize::{opaque, Decodable, Decoder, Encodable, Encoder};
17 use rustc_session::{CrateDisambiguator, Session};
18 use rustc_span::hygiene::{
19 ExpnDataDecodeMode, ExpnDataEncodeMode, ExpnId, HygieneDecodeContext, HygieneEncodeContext,
20 SyntaxContext, SyntaxContextData,
22 use rustc_span::source_map::{SourceMap, StableSourceFileId};
23 use rustc_span::CachingSourceMapView;
24 use rustc_span::{BytePos, ExpnData, SourceFile, Span, DUMMY_SP};
25 use std::collections::hash_map::Entry;
26 use std::iter::FromIterator;
29 const TAG_FILE_FOOTER: u128 = 0xC0FFEE_C0FFEE_C0FFEE_C0FFEE_C0FFEE;
31 const TAG_VALID_SPAN: u8 = 0;
32 const TAG_INVALID_SPAN: u8 = 1;
34 const TAG_SYNTAX_CONTEXT: u8 = 0;
35 const TAG_EXPN_DATA: u8 = 1;
37 /// Provides an interface to incremental compilation data cached from the
38 /// previous compilation session. This data will eventually include the results
39 /// of a few selected queries (like `typeck` and `mir_optimized`) and
40 /// any diagnostics that have been emitted during a query.
41 pub struct OnDiskCache<'sess> {
42 // The complete cache data in serialized form.
43 serialized_data: Vec<u8>,
45 // Collects all `Diagnostic`s emitted during the current compilation
47 current_diagnostics: Lock<FxHashMap<DepNodeIndex, Vec<Diagnostic>>>,
49 prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
50 cnum_map: OnceCell<IndexVec<CrateNum, Option<CrateNum>>>,
52 source_map: &'sess SourceMap,
53 file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
55 // Caches that are populated lazily during decoding.
56 file_index_to_file: Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
58 // A map from dep-node to the position of the cached query result in
60 query_result_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
62 // A map from dep-node to the position of any associated diagnostics in
64 prev_diagnostics_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
66 alloc_decoding_state: AllocDecodingState,
68 // A map from syntax context ids to the position of their associated
69 // `SyntaxContextData`. We use a `u32` instead of a `SyntaxContext`
70 // to represent the fact that we are storing *encoded* ids. When we decode
71 // a `SyntaxContext`, a new id will be allocated from the global `HygieneData`,
72 // which will almost certainly be different than the serialized id.
73 syntax_contexts: FxHashMap<u32, AbsoluteBytePos>,
74 // A map from the `DefPathHash` of an `ExpnId` to the position
75 // of their associated `ExpnData`. Ideally, we would store a `DefId`,
76 // but we need to decode this before we've constructed a `TyCtxt` (which
77 // makes it difficult to decode a `DefId`).
79 // Note that these `DefPathHashes` correspond to both local and foreign
80 // `ExpnData` (e.g `ExpnData.krate` may not be `LOCAL_CRATE`). Alternatively,
81 // we could look up the `ExpnData` from the metadata of foreign crates,
82 // but it seemed easier to have `OnDiskCache` be independent of the `CStore`.
83 expn_data: FxHashMap<u32, AbsoluteBytePos>,
84 // Additional information used when decoding hygiene data.
85 hygiene_context: HygieneDecodeContext,
86 // Maps `DefPathHash`es to their `RawDefId`s from the *previous*
87 // compilation session. This is used as an initial 'guess' when
88 // we try to map a `DefPathHash` to its `DefId` in the current compilation
90 foreign_def_path_hashes: FxHashMap<DefPathHash, RawDefId>,
92 // The *next* compilation sessison's `foreign_def_path_hashes` - at
93 // the end of our current compilation session, this will get written
94 // out to the `foreign_def_path_hashes` field of the `Footer`, which
95 // will become `foreign_def_path_hashes` of the next compilation session.
96 // This stores any `DefPathHash` that we may need to map to a `DefId`
97 // during the next compilation session.
98 latest_foreign_def_path_hashes: Lock<FxHashMap<DefPathHash, RawDefId>>,
100 // Maps `DefPathHashes` to their corresponding `LocalDefId`s for all
101 // local items in the current compilation session. This is only populated
102 // when we are in incremental mode and have loaded a pre-existing cache
103 // from disk, since this map is only used when deserializing a `DefPathHash`
104 // from the incremental cache.
105 local_def_path_hash_to_def_id: FxHashMap<DefPathHash, LocalDefId>,
106 // Caches all lookups of `DefPathHashes`, both for local and foreign
107 // definitions. A definition from the previous compilation session
108 // may no longer exist in the current compilation session, so
109 // we use `Option<DefId>` so that we can cache a lookup failure.
110 def_path_hash_to_def_id_cache: Lock<FxHashMap<DefPathHash, Option<DefId>>>,
113 // This type is used only for serialization and deserialization.
114 #[derive(Encodable, Decodable)]
116 file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
117 prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
118 query_result_index: EncodedQueryResultIndex,
119 diagnostics_index: EncodedQueryResultIndex,
120 // The location of all allocations.
121 interpret_alloc_index: Vec<u32>,
122 // See `OnDiskCache.syntax_contexts`
123 syntax_contexts: FxHashMap<u32, AbsoluteBytePos>,
124 // See `OnDiskCache.expn_data`
125 expn_data: FxHashMap<u32, AbsoluteBytePos>,
126 foreign_def_path_hashes: FxHashMap<DefPathHash, RawDefId>,
129 type EncodedQueryResultIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
130 type EncodedDiagnosticsIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
131 type EncodedDiagnostics = Vec<Diagnostic>;
133 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable)]
134 struct SourceFileIndex(u32);
136 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Encodable, Decodable)]
137 struct AbsoluteBytePos(u32);
139 impl AbsoluteBytePos {
140 fn new(pos: usize) -> AbsoluteBytePos {
141 debug_assert!(pos <= u32::MAX as usize);
142 AbsoluteBytePos(pos as u32)
145 fn to_usize(self) -> usize {
150 /// Represents a potentially invalid `DefId`. This is used during incremental
151 /// compilation to represent a `DefId` from the *previous* compilation session,
152 /// which may no longer be valid. This is used to help map a `DefPathHash`
153 /// to a `DefId` in the current compilation session.
154 #[derive(Encodable, Decodable, Copy, Clone, Debug)]
155 crate struct RawDefId {
156 // We deliberately do not use `CrateNum` and `DefIndex`
157 // here, since a crate/index from the previous compilation
158 // session may no longer exist.
163 fn make_local_def_path_hash_map(definitions: &Definitions) -> FxHashMap<DefPathHash, LocalDefId> {
164 FxHashMap::from_iter(
167 .all_def_path_hashes_and_def_ids(LOCAL_CRATE)
168 .map(|(hash, def_id)| (hash, def_id.as_local().unwrap())),
172 impl<'sess> OnDiskCache<'sess> {
173 /// Creates a new `OnDiskCache` instance from the serialized data in `data`.
175 sess: &'sess Session,
178 definitions: &Definitions,
180 debug_assert!(sess.opts.incremental.is_some());
182 // Wrap in a scope so we can borrow `data`.
183 let footer: Footer = {
184 let mut decoder = opaque::Decoder::new(&data[..], start_pos);
186 // Decode the *position* of the footer, which can be found in the
187 // last 8 bytes of the file.
188 decoder.set_position(data.len() - IntEncodedWithFixedSize::ENCODED_SIZE);
189 let footer_pos = IntEncodedWithFixedSize::decode(&mut decoder)
190 .expect("error while trying to decode footer position")
193 // Decode the file footer, which contains all the lookup tables, etc.
194 decoder.set_position(footer_pos);
196 decode_tagged(&mut decoder, TAG_FILE_FOOTER)
197 .expect("error while trying to decode footer position")
201 serialized_data: data,
202 file_index_to_stable_id: footer.file_index_to_stable_id,
203 file_index_to_file: Default::default(),
204 prev_cnums: footer.prev_cnums,
205 cnum_map: OnceCell::new(),
206 source_map: sess.source_map(),
207 current_diagnostics: Default::default(),
208 query_result_index: footer.query_result_index.into_iter().collect(),
209 prev_diagnostics_index: footer.diagnostics_index.into_iter().collect(),
210 alloc_decoding_state: AllocDecodingState::new(footer.interpret_alloc_index),
211 syntax_contexts: footer.syntax_contexts,
212 expn_data: footer.expn_data,
213 hygiene_context: Default::default(),
214 foreign_def_path_hashes: footer.foreign_def_path_hashes,
215 latest_foreign_def_path_hashes: Default::default(),
216 local_def_path_hash_to_def_id: make_local_def_path_hash_map(definitions),
217 def_path_hash_to_def_id_cache: Default::default(),
221 pub fn new_empty(source_map: &'sess SourceMap) -> Self {
223 serialized_data: Vec::new(),
224 file_index_to_stable_id: Default::default(),
225 file_index_to_file: Default::default(),
227 cnum_map: OnceCell::new(),
229 current_diagnostics: Default::default(),
230 query_result_index: Default::default(),
231 prev_diagnostics_index: Default::default(),
232 alloc_decoding_state: AllocDecodingState::new(Vec::new()),
233 syntax_contexts: FxHashMap::default(),
234 expn_data: FxHashMap::default(),
235 hygiene_context: Default::default(),
236 foreign_def_path_hashes: Default::default(),
237 latest_foreign_def_path_hashes: Default::default(),
238 local_def_path_hash_to_def_id: Default::default(),
239 def_path_hash_to_def_id_cache: Default::default(),
243 pub fn serialize<'tcx, E>(&self, tcx: TyCtxt<'tcx>, encoder: &mut E) -> Result<(), E::Error>
247 // Serializing the `DepGraph` should not modify it.
248 tcx.dep_graph.with_ignore(|| {
249 // Allocate `SourceFileIndex`es.
250 let (file_to_file_index, file_index_to_stable_id) = {
251 let files = tcx.sess.source_map().files();
252 let mut file_to_file_index =
253 FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
254 let mut file_index_to_stable_id =
255 FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
257 for (index, file) in files.iter().enumerate() {
258 let index = SourceFileIndex(index as u32);
259 let file_ptr: *const SourceFile = &**file as *const _;
260 file_to_file_index.insert(file_ptr, index);
261 file_index_to_stable_id.insert(index, StableSourceFileId::new(&file));
264 (file_to_file_index, file_index_to_stable_id)
267 // Register any dep nodes that we reused from the previous session,
268 // but didn't `DepNode::construct` in this session. This ensures
269 // that their `DefPathHash` to `RawDefId` mappings are registered
270 // in 'latest_foreign_def_path_hashes' if necessary, since that
271 // normally happens in `DepNode::construct`.
272 tcx.dep_graph.register_reused_dep_nodes(tcx);
274 // Load everything into memory so we can write it out to the on-disk
275 // cache. The vast majority of cacheable query results should already
276 // be in memory, so this should be a cheap operation.
277 // Do this *before* we clone 'latest_foreign_def_path_hashes', since
278 // loading existing queries may cause us to create new DepNodes, which
279 // may in turn end up invoking `store_foreign_def_id_hash`
280 tcx.dep_graph.exec_cache_promotions(tcx);
282 let latest_foreign_def_path_hashes = self.latest_foreign_def_path_hashes.lock().clone();
283 let hygiene_encode_context = HygieneEncodeContext::default();
285 let mut encoder = CacheEncoder {
288 type_shorthands: Default::default(),
289 predicate_shorthands: Default::default(),
290 interpret_allocs: Default::default(),
291 source_map: CachingSourceMapView::new(tcx.sess.source_map()),
293 hygiene_context: &hygiene_encode_context,
294 latest_foreign_def_path_hashes,
297 // Encode query results.
298 let mut query_result_index = EncodedQueryResultIndex::new();
300 tcx.sess.time("encode_query_results", || {
301 let enc = &mut encoder;
302 let qri = &mut query_result_index;
304 macro_rules! encode_queries {
305 ($($query:ident,)*) => {
307 encode_query_results::<ty::query::queries::$query<'_>, _>(
316 rustc_cached_queries!(encode_queries!);
321 // Encode diagnostics.
322 let diagnostics_index: EncodedDiagnosticsIndex = self
326 .map(|(dep_node_index, diagnostics)| {
327 let pos = AbsoluteBytePos::new(encoder.position());
328 // Let's make sure we get the expected type here.
329 let diagnostics: &EncodedDiagnostics = diagnostics;
330 let dep_node_index = SerializedDepNodeIndex::new(dep_node_index.index());
331 encoder.encode_tagged(dep_node_index, diagnostics)?;
333 Ok((dep_node_index, pos))
335 .collect::<Result<_, _>>()?;
337 let interpret_alloc_index = {
338 let mut interpret_alloc_index = Vec::new();
341 let new_n = encoder.interpret_allocs.len();
342 // If we have found new IDs, serialize those too.
347 interpret_alloc_index.reserve(new_n - n);
348 for idx in n..new_n {
349 let id = encoder.interpret_allocs[idx];
350 let pos = encoder.position() as u32;
351 interpret_alloc_index.push(pos);
352 interpret::specialized_encode_alloc_id(&mut encoder, tcx, id)?;
356 interpret_alloc_index
359 let sorted_cnums = sorted_cnums_including_local_crate(tcx);
360 let prev_cnums: Vec<_> = sorted_cnums
363 let crate_name = tcx.original_crate_name(cnum).to_string();
364 let crate_disambiguator = tcx.crate_disambiguator(cnum);
365 (cnum.as_u32(), crate_name, crate_disambiguator)
369 let mut syntax_contexts = FxHashMap::default();
370 let mut expn_ids = FxHashMap::default();
372 // Encode all hygiene data (`SyntaxContextData` and `ExpnData`) from the current
375 hygiene_encode_context.encode(
377 |encoder, index, ctxt_data| {
378 let pos = AbsoluteBytePos::new(encoder.position());
379 encoder.encode_tagged(TAG_SYNTAX_CONTEXT, ctxt_data)?;
380 syntax_contexts.insert(index, pos);
383 |encoder, index, expn_data| {
384 let pos = AbsoluteBytePos::new(encoder.position());
385 encoder.encode_tagged(TAG_EXPN_DATA, expn_data)?;
386 expn_ids.insert(index, pos);
391 let foreign_def_path_hashes =
392 std::mem::take(&mut encoder.latest_foreign_def_path_hashes);
394 // `Encode the file footer.
395 let footer_pos = encoder.position() as u64;
396 encoder.encode_tagged(
399 file_index_to_stable_id,
403 interpret_alloc_index,
406 foreign_def_path_hashes,
410 // Encode the position of the footer as the last 8 bytes of the
411 // file so we know where to look for it.
412 IntEncodedWithFixedSize(footer_pos).encode(encoder.encoder.opaque())?;
414 // DO NOT WRITE ANYTHING TO THE ENCODER AFTER THIS POINT! The address
415 // of the footer must be the last thing in the data stream.
419 fn sorted_cnums_including_local_crate(tcx: TyCtxt<'_>) -> Vec<CrateNum> {
420 let mut cnums = vec![LOCAL_CRATE];
421 cnums.extend_from_slice(&tcx.crates()[..]);
422 cnums.sort_unstable();
423 // Just to be sure...
430 /// Loads a diagnostic emitted during the previous compilation session.
431 pub fn load_diagnostics(
434 dep_node_index: SerializedDepNodeIndex,
435 ) -> Vec<Diagnostic> {
436 let diagnostics: Option<EncodedDiagnostics> =
437 self.load_indexed(tcx, dep_node_index, &self.prev_diagnostics_index, "diagnostics");
439 diagnostics.unwrap_or_default()
442 /// Stores a diagnostic emitted during the current compilation session.
443 /// Anything stored like this will be available via `load_diagnostics` in
444 /// the next compilation session.
447 pub fn store_diagnostics(
449 dep_node_index: DepNodeIndex,
450 diagnostics: ThinVec<Diagnostic>,
452 let mut current_diagnostics = self.current_diagnostics.borrow_mut();
453 let prev = current_diagnostics.insert(dep_node_index, diagnostics.into());
454 debug_assert!(prev.is_none());
457 fn get_raw_def_id(&self, hash: &DefPathHash) -> Option<RawDefId> {
458 self.foreign_def_path_hashes.get(hash).copied()
461 fn try_remap_cnum(&self, tcx: TyCtxt<'_>, cnum: u32) -> Option<CrateNum> {
463 self.cnum_map.get_or_init(|| Self::compute_cnum_map(tcx, &self.prev_cnums[..]));
464 debug!("try_remap_cnum({}): cnum_map={:?}", cnum, cnum_map);
466 cnum_map[CrateNum::from_u32(cnum)]
469 pub(crate) fn store_foreign_def_id_hash(&self, def_id: DefId, hash: DefPathHash) {
470 // We may overwrite an existing entry, but it will have the same value,
472 self.latest_foreign_def_path_hashes
474 .insert(hash, RawDefId { krate: def_id.krate.as_u32(), index: def_id.index.as_u32() });
477 /// If the given `dep_node`'s hash still exists in the current compilation,
478 /// calls `store_foreign_def_id` with its current `DefId`.
480 /// Normally, `store_foreign_def_id_hash` can be called directly by
481 /// the dependency graph when we construct a `DepNode`. However,
482 /// when we re-use a deserialized `DepNode` from the previous compilation
483 /// session, we only have the `DefPathHash` available. This method is used
484 /// to that any `DepNode` that we re-use has a `DefPathHash` -> `RawId` written
485 /// out for usage in the next compilation session.
486 pub fn register_reused_dep_node(&self, tcx: TyCtxt<'tcx>, dep_node: &DepNode) {
487 // For reused dep nodes, we only need to store the mapping if the node
488 // is one whose query key we can reconstruct from the hash. We use the
489 // mapping to aid that reconstruction in the next session. While we also
490 // use it to decode `DefId`s we encoded in the cache as `DefPathHashes`,
491 // they're already registered during `DefId` encoding.
492 if dep_node.kind.can_reconstruct_query_key() {
493 let hash = DefPathHash(dep_node.hash.into());
495 // We can't simply copy the `RawDefId` from `foreign_def_path_hashes` to
496 // `latest_foreign_def_path_hashes`, since the `RawDefId` might have
497 // changed in the current compilation session (e.g. we've added/removed crates,
498 // or added/removed definitions before/after the target definition).
499 if let Some(def_id) = self.def_path_hash_to_def_id(tcx, hash) {
500 self.store_foreign_def_id_hash(def_id, hash);
505 /// Returns the cached query result if there is something in the cache for
506 /// the given `SerializedDepNodeIndex`; otherwise returns `None`.
507 crate fn try_load_query_result<'tcx, T>(
510 dep_node_index: SerializedDepNodeIndex,
513 T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
515 self.load_indexed(tcx, dep_node_index, &self.query_result_index, "query result")
518 /// Stores a diagnostic emitted during computation of an anonymous query.
519 /// Since many anonymous queries can share the same `DepNode`, we aggregate
520 /// them -- as opposed to regular queries where we assume that there is a
521 /// 1:1 relationship between query-key and `DepNode`.
524 pub fn store_diagnostics_for_anon_node(
526 dep_node_index: DepNodeIndex,
527 diagnostics: ThinVec<Diagnostic>,
529 let mut current_diagnostics = self.current_diagnostics.borrow_mut();
531 let x = current_diagnostics.entry(dep_node_index).or_insert(Vec::new());
533 x.extend(Into::<Vec<_>>::into(diagnostics));
536 fn load_indexed<'tcx, T>(
539 dep_node_index: SerializedDepNodeIndex,
540 index: &FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
541 debug_tag: &'static str,
544 T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
546 let pos = index.get(&dep_node_index).cloned()?;
548 self.with_decoder(tcx, pos, |decoder| match decode_tagged(decoder, dep_node_index) {
550 Err(e) => bug!("could not decode cached {}: {}", debug_tag, e),
554 fn with_decoder<'a, 'tcx, T, F: FnOnce(&mut CacheDecoder<'sess, 'tcx>) -> T>(
557 pos: AbsoluteBytePos,
561 T: Decodable<CacheDecoder<'a, 'tcx>>,
564 self.cnum_map.get_or_init(|| Self::compute_cnum_map(tcx, &self.prev_cnums[..]));
566 let mut decoder = CacheDecoder {
568 opaque: opaque::Decoder::new(&self.serialized_data[..], pos.to_usize()),
569 source_map: self.source_map,
571 file_index_to_file: &self.file_index_to_file,
572 file_index_to_stable_id: &self.file_index_to_stable_id,
573 alloc_decoding_session: self.alloc_decoding_state.new_decoding_session(),
574 syntax_contexts: &self.syntax_contexts,
575 expn_data: &self.expn_data,
576 hygiene_context: &self.hygiene_context,
581 // This function builds mapping from previous-session-`CrateNum` to
582 // current-session-`CrateNum`. There might be `CrateNum`s from the previous
583 // `Session` that don't occur in the current one. For these, the mapping
587 prev_cnums: &[(u32, String, CrateDisambiguator)],
588 ) -> IndexVec<CrateNum, Option<CrateNum>> {
589 tcx.dep_graph.with_ignore(|| {
590 let current_cnums = tcx
591 .all_crate_nums(LOCAL_CRATE)
594 let crate_name = tcx.original_crate_name(cnum).to_string();
595 let crate_disambiguator = tcx.crate_disambiguator(cnum);
596 ((crate_name, crate_disambiguator), cnum)
598 .collect::<FxHashMap<_, _>>();
600 let map_size = prev_cnums.iter().map(|&(cnum, ..)| cnum).max().unwrap_or(0) + 1;
601 let mut map = IndexVec::from_elem_n(None, map_size as usize);
603 for &(prev_cnum, ref crate_name, crate_disambiguator) in prev_cnums {
604 let key = (crate_name.clone(), crate_disambiguator);
605 map[CrateNum::from_u32(prev_cnum)] = current_cnums.get(&key).cloned();
608 map[LOCAL_CRATE] = Some(LOCAL_CRATE);
613 /// Converts a `DefPathHash` to its corresponding `DefId` in the current compilation
614 /// session, if it still exists. This is used during incremental compilation to
615 /// turn a deserialized `DefPathHash` into its current `DefId`.
616 pub(crate) fn def_path_hash_to_def_id(
621 let mut cache = self.def_path_hash_to_def_id_cache.lock();
622 match cache.entry(hash) {
623 Entry::Occupied(e) => *e.get(),
624 Entry::Vacant(e) => {
625 debug!("def_path_hash_to_def_id({:?})", hash);
626 // Check if the `DefPathHash` corresponds to a definition in the current
628 if let Some(def_id) = self.local_def_path_hash_to_def_id.get(&hash).cloned() {
629 let def_id = def_id.to_def_id();
630 e.insert(Some(def_id));
633 // This `raw_def_id` represents the `DefId` of this `DefPathHash` in
634 // the *previous* compliation session. The `DefPathHash` includes the
635 // owning crate, so if the corresponding definition still exists in the
636 // current compilation session, the crate is guaranteed to be the same
637 // (otherwise, we would compute a different `DefPathHash`).
638 let raw_def_id = self.get_raw_def_id(&hash)?;
639 debug!("def_path_hash_to_def_id({:?}): raw_def_id = {:?}", hash, raw_def_id);
640 // If the owning crate no longer exists, the corresponding definition definitely
642 let krate = self.try_remap_cnum(tcx, raw_def_id.krate)?;
643 debug!("def_path_hash_to_def_id({:?}): krate = {:?}", hash, krate);
644 // If our `DefPathHash` corresponded to a definition in the local crate,
645 // we should have either found it in `local_def_path_hash_to_def_id`, or
646 // never attempted to load it in the first place. Any query result or `DepNode`
647 // that references a local `DefId` should depend on some HIR-related `DepNode`.
648 // If a local definition is removed/modified such that its old `DefPathHash`
649 // no longer has a corresponding definition, that HIR-related `DepNode` should
650 // end up red. This should prevent us from ever calling
651 // `tcx.def_path_hash_to_def_id`, since we'll end up recomputing any
653 debug_assert_ne!(krate, LOCAL_CRATE);
654 // Try to find a definition in the current session, using the previous `DefIndex`
655 // as an initial guess.
656 let opt_def_id = tcx.cstore.def_path_hash_to_def_id(krate, raw_def_id.index, hash);
657 debug!("def_path_to_def_id({:?}): opt_def_id = {:?}", hash, opt_def_id);
658 e.insert(opt_def_id);
665 //- DECODING -------------------------------------------------------------------
667 /// A decoder that can read from the incr. comp. cache. It is similar to the one
668 /// we use for crate metadata decoding in that it can rebase spans and eventually
669 /// will also handle things that contain `Ty` instances.
670 crate struct CacheDecoder<'a, 'tcx> {
672 opaque: opaque::Decoder<'a>,
673 source_map: &'a SourceMap,
674 cnum_map: &'a IndexVec<CrateNum, Option<CrateNum>>,
675 file_index_to_file: &'a Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
676 file_index_to_stable_id: &'a FxHashMap<SourceFileIndex, StableSourceFileId>,
677 alloc_decoding_session: AllocDecodingSession<'a>,
678 syntax_contexts: &'a FxHashMap<u32, AbsoluteBytePos>,
679 expn_data: &'a FxHashMap<u32, AbsoluteBytePos>,
680 hygiene_context: &'a HygieneDecodeContext,
683 impl<'a, 'tcx> CacheDecoder<'a, 'tcx> {
684 fn file_index_to_file(&self, index: SourceFileIndex) -> Lrc<SourceFile> {
686 ref file_index_to_file,
687 ref file_index_to_stable_id,
696 let stable_id = file_index_to_stable_id[&index];
698 .source_file_by_stable_id(stable_id)
699 .expect("failed to lookup `SourceFile` in new context")
705 trait DecoderWithPosition: Decoder {
706 fn position(&self) -> usize;
709 impl<'a> DecoderWithPosition for opaque::Decoder<'a> {
710 fn position(&self) -> usize {
715 impl<'a, 'tcx> DecoderWithPosition for CacheDecoder<'a, 'tcx> {
716 fn position(&self) -> usize {
717 self.opaque.position()
721 // Decodes something that was encoded with `encode_tagged()` and verify that the
722 // tag matches and the correct amount of bytes was read.
723 fn decode_tagged<D, T, V>(decoder: &mut D, expected_tag: T) -> Result<V, D::Error>
725 T: Decodable<D> + Eq + std::fmt::Debug,
727 D: DecoderWithPosition,
729 let start_pos = decoder.position();
731 let actual_tag = T::decode(decoder)?;
732 assert_eq!(actual_tag, expected_tag);
733 let value = V::decode(decoder)?;
734 let end_pos = decoder.position();
736 let expected_len: u64 = Decodable::decode(decoder)?;
737 assert_eq!((end_pos - start_pos) as u64, expected_len);
742 impl<'a, 'tcx> TyDecoder<'tcx> for CacheDecoder<'a, 'tcx> {
743 const CLEAR_CROSS_CRATE: bool = false;
746 fn tcx(&self) -> TyCtxt<'tcx> {
751 fn position(&self) -> usize {
752 self.opaque.position()
756 fn peek_byte(&self) -> u8 {
757 self.opaque.data[self.opaque.position()]
760 fn cached_ty_for_shorthand<F>(
764 ) -> Result<Ty<'tcx>, Self::Error>
766 F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>,
768 let tcx = self.tcx();
771 ty::CReaderCacheKey { cnum: CrateNum::ReservedForIncrCompCache, pos: shorthand };
773 if let Some(&ty) = tcx.ty_rcache.borrow().get(&cache_key) {
777 let ty = or_insert_with(self)?;
778 // This may overwrite the entry, but it should overwrite with the same value.
779 tcx.ty_rcache.borrow_mut().insert_same(cache_key, ty);
783 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
785 F: FnOnce(&mut Self) -> R,
787 debug_assert!(pos < self.opaque.data.len());
789 let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
790 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
792 self.opaque = old_opaque;
796 fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
797 self.cnum_map[cnum].unwrap_or_else(|| bug!("could not find new `CrateNum` for {:?}", cnum))
800 fn decode_alloc_id(&mut self) -> Result<interpret::AllocId, Self::Error> {
801 let alloc_decoding_session = self.alloc_decoding_session;
802 alloc_decoding_session.decode_alloc_id(self)
806 crate::implement_ty_decoder!(CacheDecoder<'a, 'tcx>);
808 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for SyntaxContext {
809 fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
810 let syntax_contexts = decoder.syntax_contexts;
811 rustc_span::hygiene::decode_syntax_context(decoder, decoder.hygiene_context, |this, id| {
812 // This closure is invoked if we haven't already decoded the data for the `SyntaxContext` we are deserializing.
813 // We look up the position of the associated `SyntaxData` and decode it.
814 let pos = syntax_contexts.get(&id).unwrap();
815 this.with_position(pos.to_usize(), |decoder| {
816 let data: SyntaxContextData = decode_tagged(decoder, TAG_SYNTAX_CONTEXT)?;
823 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for ExpnId {
824 fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
825 let expn_data = decoder.expn_data;
826 rustc_span::hygiene::decode_expn_id(
828 ExpnDataDecodeMode::incr_comp(decoder.hygiene_context),
830 // This closure is invoked if we haven't already decoded the data for the `ExpnId` we are deserializing.
831 // We look up the position of the associated `ExpnData` and decode it.
834 .unwrap_or_else(|| panic!("Bad index {:?} (map {:?})", index, expn_data));
836 this.with_position(pos.to_usize(), |decoder| {
837 let data: ExpnData = decode_tagged(decoder, TAG_EXPN_DATA)?;
845 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Span {
846 fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
847 let tag: u8 = Decodable::decode(decoder)?;
849 if tag == TAG_INVALID_SPAN {
852 debug_assert_eq!(tag, TAG_VALID_SPAN);
855 let file_lo_index = SourceFileIndex::decode(decoder)?;
856 let line_lo = usize::decode(decoder)?;
857 let col_lo = BytePos::decode(decoder)?;
858 let len = BytePos::decode(decoder)?;
859 let ctxt = SyntaxContext::decode(decoder)?;
861 let file_lo = decoder.file_index_to_file(file_lo_index);
862 let lo = file_lo.lines[line_lo - 1] + col_lo;
865 Ok(Span::new(lo, hi, ctxt))
869 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for CrateNum {
870 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
871 let cnum = CrateNum::from_u32(u32::decode(d)?);
872 Ok(d.map_encoded_cnum_to_current(cnum))
876 // This impl makes sure that we get a runtime error when we try decode a
877 // `DefIndex` that is not contained in a `DefId`. Such a case would be problematic
878 // because we would not know how to transform the `DefIndex` to the current
880 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for DefIndex {
881 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<DefIndex, String> {
882 Err(d.error("trying to decode `DefIndex` outside the context of a `DefId`"))
886 // Both the `CrateNum` and the `DefIndex` of a `DefId` can change in between two
887 // compilation sessions. We use the `DefPathHash`, which is stable across
888 // sessions, to map the old `DefId` to the new one.
889 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for DefId {
890 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
891 // Load the `DefPathHash` which is was we encoded the `DefId` as.
892 let def_path_hash = DefPathHash::decode(d)?;
894 // Using the `DefPathHash`, we can lookup the new `DefId`.
895 // Subtle: We only encode a `DefId` as part of a query result.
896 // If we get to this point, then all of the query inputs were green,
897 // which means that the definition with this hash is guaranteed to
898 // still exist in the current compilation session.
904 .def_path_hash_to_def_id(d.tcx(), def_path_hash)
909 impl<'a, 'tcx> FingerprintDecoder for CacheDecoder<'a, 'tcx> {
910 fn decode_fingerprint(&mut self) -> Result<Fingerprint, Self::Error> {
911 Fingerprint::decode_opaque(&mut self.opaque)
915 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx FxHashSet<LocalDefId> {
916 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
917 RefDecodable::decode(d)
921 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
922 for &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>>
924 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
925 RefDecodable::decode(d)
929 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [mir::abstract_const::Node<'tcx>] {
930 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
931 RefDecodable::decode(d)
935 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
936 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
937 RefDecodable::decode(d)
941 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [rustc_ast::InlineAsmTemplatePiece] {
942 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
943 RefDecodable::decode(d)
947 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [Span] {
948 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
949 RefDecodable::decode(d)
953 //- ENCODING -------------------------------------------------------------------
955 /// An encoder that can write the incr. comp. cache.
956 struct CacheEncoder<'a, 'tcx, E: OpaqueEncoder> {
959 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
960 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
961 interpret_allocs: FxIndexSet<interpret::AllocId>,
962 source_map: CachingSourceMapView<'tcx>,
963 file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>,
964 hygiene_context: &'a HygieneEncodeContext,
965 latest_foreign_def_path_hashes: FxHashMap<DefPathHash, RawDefId>,
968 impl<'a, 'tcx, E> CacheEncoder<'a, 'tcx, E>
970 E: 'a + OpaqueEncoder,
972 fn source_file_index(&mut self, source_file: Lrc<SourceFile>) -> SourceFileIndex {
973 self.file_to_file_index[&(&*source_file as *const SourceFile)]
976 /// Encode something with additional information that allows to do some
977 /// sanity checks when decoding the data again. This method will first
978 /// encode the specified tag, then the given value, then the number of
979 /// bytes taken up by tag and value. On decoding, we can then verify that
980 /// we get the expected tag and read the expected number of bytes.
981 fn encode_tagged<T: Encodable<Self>, V: Encodable<Self>>(
985 ) -> Result<(), E::Error> {
986 let start_pos = self.position();
991 let end_pos = self.position();
992 ((end_pos - start_pos) as u64).encode(self)
996 impl<'a, 'tcx> FingerprintEncoder for CacheEncoder<'a, 'tcx, rustc_serialize::opaque::Encoder> {
997 fn encode_fingerprint(&mut self, f: &Fingerprint) -> opaque::EncodeResult {
998 f.encode_opaque(self.encoder)
1002 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for SyntaxContext
1004 E: 'a + OpaqueEncoder,
1006 fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1007 rustc_span::hygiene::raw_encode_syntax_context(*self, s.hygiene_context, s)
1011 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for ExpnId
1013 E: 'a + OpaqueEncoder,
1015 fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1016 rustc_span::hygiene::raw_encode_expn_id(
1019 ExpnDataEncodeMode::IncrComp,
1025 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for Span
1027 E: 'a + OpaqueEncoder,
1029 fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1030 if *self == DUMMY_SP {
1031 return TAG_INVALID_SPAN.encode(s);
1034 let span_data = self.data();
1035 let (file_lo, line_lo, col_lo) = match s.source_map.byte_pos_to_line_and_col(span_data.lo) {
1037 None => return TAG_INVALID_SPAN.encode(s),
1040 if !file_lo.contains(span_data.hi) {
1041 return TAG_INVALID_SPAN.encode(s);
1044 let len = span_data.hi - span_data.lo;
1046 let source_file_index = s.source_file_index(file_lo);
1048 TAG_VALID_SPAN.encode(s)?;
1049 source_file_index.encode(s)?;
1053 span_data.ctxt.encode(s)
1057 impl<'a, 'tcx, E> TyEncoder<'tcx> for CacheEncoder<'a, 'tcx, E>
1059 E: 'a + OpaqueEncoder,
1061 const CLEAR_CROSS_CRATE: bool = false;
1063 fn position(&self) -> usize {
1064 self.encoder.encoder_position()
1066 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
1067 &mut self.type_shorthands
1069 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::Predicate<'tcx>, usize> {
1070 &mut self.predicate_shorthands
1072 fn encode_alloc_id(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
1073 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
1079 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for DefId
1081 E: 'a + OpaqueEncoder,
1083 fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1084 let def_path_hash = s.tcx.def_path_hash(*self);
1085 // Store additional information when we encode a foreign `DefId`,
1086 // so that we can map its `DefPathHash` back to a `DefId` in the next
1087 // compilation session.
1088 if !self.is_local() {
1089 s.latest_foreign_def_path_hashes.insert(
1091 RawDefId { krate: self.krate.as_u32(), index: self.index.as_u32() },
1094 def_path_hash.encode(s)
1098 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for DefIndex
1100 E: 'a + OpaqueEncoder,
1102 fn encode(&self, _: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1103 bug!("encoding `DefIndex` without context");
1107 macro_rules! encoder_methods {
1108 ($($name:ident($ty:ty);)*) => {
1110 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
1111 self.encoder.$name(value)
1116 impl<'a, 'tcx, E> Encoder for CacheEncoder<'a, 'tcx, E>
1118 E: 'a + OpaqueEncoder,
1120 type Error = E::Error;
1123 fn emit_unit(&mut self) -> Result<(), Self::Error> {
1150 // An integer that will always encode to 8 bytes.
1151 struct IntEncodedWithFixedSize(u64);
1153 impl IntEncodedWithFixedSize {
1154 pub const ENCODED_SIZE: usize = 8;
1157 impl Encodable<opaque::Encoder> for IntEncodedWithFixedSize {
1158 fn encode(&self, e: &mut opaque::Encoder) -> Result<(), !> {
1159 let start_pos = e.position();
1160 for i in 0..IntEncodedWithFixedSize::ENCODED_SIZE {
1161 ((self.0 >> (i * 8)) as u8).encode(e)?;
1163 let end_pos = e.position();
1164 assert_eq!((end_pos - start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
1169 impl<'a> Decodable<opaque::Decoder<'a>> for IntEncodedWithFixedSize {
1170 fn decode(decoder: &mut opaque::Decoder<'a>) -> Result<IntEncodedWithFixedSize, String> {
1171 let mut value: u64 = 0;
1172 let start_pos = decoder.position();
1174 for i in 0..IntEncodedWithFixedSize::ENCODED_SIZE {
1175 let byte: u8 = Decodable::decode(decoder)?;
1176 value |= (byte as u64) << (i * 8);
1179 let end_pos = decoder.position();
1180 assert_eq!((end_pos - start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
1182 Ok(IntEncodedWithFixedSize(value))
1186 fn encode_query_results<'a, 'tcx, Q, E>(
1188 encoder: &mut CacheEncoder<'a, 'tcx, E>,
1189 query_result_index: &mut EncodedQueryResultIndex,
1190 ) -> Result<(), E::Error>
1192 Q: super::QueryDescription<TyCtxt<'tcx>> + super::QueryAccessors<TyCtxt<'tcx>>,
1193 Q::Value: Encodable<CacheEncoder<'a, 'tcx, E>>,
1194 E: 'a + OpaqueEncoder,
1199 .extra_verbose_generic_activity("encode_query_results_for", std::any::type_name::<Q>());
1201 let state = Q::query_state(tcx);
1202 assert!(state.all_inactive());
1204 state.iter_results(|results| {
1205 for (key, value, dep_node) in results {
1206 if Q::cache_on_disk(tcx, &key, Some(value)) {
1207 let dep_node = SerializedDepNodeIndex::new(dep_node.index());
1209 // Record position of the cache entry.
1211 .push((dep_node, AbsoluteBytePos::new(encoder.encoder.opaque().position())));
1213 // Encode the type check tables with the `SerializedDepNodeIndex`
1215 encoder.encode_tagged(dep_node, value)?;