]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/query/on_disk_cache.rs
rustc_query_system: explicitly register reused dep nodes
[rust.git] / compiler / rustc_middle / src / ty / query / on_disk_cache.rs
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,
21 };
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;
27 use std::mem;
28
29 const TAG_FILE_FOOTER: u128 = 0xC0FFEE_C0FFEE_C0FFEE_C0FFEE_C0FFEE;
30
31 const TAG_VALID_SPAN: u8 = 0;
32 const TAG_INVALID_SPAN: u8 = 1;
33
34 const TAG_SYNTAX_CONTEXT: u8 = 0;
35 const TAG_EXPN_DATA: u8 = 1;
36
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>,
44
45     // Collects all `Diagnostic`s emitted during the current compilation
46     // session.
47     current_diagnostics: Lock<FxHashMap<DepNodeIndex, Vec<Diagnostic>>>,
48
49     prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
50     cnum_map: OnceCell<IndexVec<CrateNum, Option<CrateNum>>>,
51
52     source_map: &'sess SourceMap,
53     file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
54
55     // Caches that are populated lazily during decoding.
56     file_index_to_file: Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
57
58     // A map from dep-node to the position of the cached query result in
59     // `serialized_data`.
60     query_result_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
61
62     // A map from dep-node to the position of any associated diagnostics in
63     // `serialized_data`.
64     prev_diagnostics_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
65
66     alloc_decoding_state: AllocDecodingState,
67
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`).
78
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
89     // session.
90     foreign_def_path_hashes: FxHashMap<DefPathHash, RawDefId>,
91
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>>,
99
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>>>,
111 }
112
113 // This type is used only for serialization and deserialization.
114 #[derive(Encodable, Decodable)]
115 struct Footer {
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>,
127 }
128
129 type EncodedQueryResultIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
130 type EncodedDiagnosticsIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
131 type EncodedDiagnostics = Vec<Diagnostic>;
132
133 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable)]
134 struct SourceFileIndex(u32);
135
136 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Encodable, Decodable)]
137 struct AbsoluteBytePos(u32);
138
139 impl AbsoluteBytePos {
140     fn new(pos: usize) -> AbsoluteBytePos {
141         debug_assert!(pos <= u32::MAX as usize);
142         AbsoluteBytePos(pos as u32)
143     }
144
145     fn to_usize(self) -> usize {
146         self.0 as usize
147     }
148 }
149
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.
159     pub krate: u32,
160     pub index: u32,
161 }
162
163 fn make_local_def_path_hash_map(definitions: &Definitions) -> FxHashMap<DefPathHash, LocalDefId> {
164     FxHashMap::from_iter(
165         definitions
166             .def_path_table()
167             .all_def_path_hashes_and_def_ids(LOCAL_CRATE)
168             .map(|(hash, def_id)| (hash, def_id.as_local().unwrap())),
169     )
170 }
171
172 impl<'sess> OnDiskCache<'sess> {
173     /// Creates a new `OnDiskCache` instance from the serialized data in `data`.
174     pub fn new(
175         sess: &'sess Session,
176         data: Vec<u8>,
177         start_pos: usize,
178         definitions: &Definitions,
179     ) -> Self {
180         debug_assert!(sess.opts.incremental.is_some());
181
182         // Wrap in a scope so we can borrow `data`.
183         let footer: Footer = {
184             let mut decoder = opaque::Decoder::new(&data[..], start_pos);
185
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")
191                 .0 as usize;
192
193             // Decode the file footer, which contains all the lookup tables, etc.
194             decoder.set_position(footer_pos);
195
196             decode_tagged(&mut decoder, TAG_FILE_FOOTER)
197                 .expect("error while trying to decode footer position")
198         };
199
200         Self {
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(),
218         }
219     }
220
221     pub fn new_empty(source_map: &'sess SourceMap) -> Self {
222         Self {
223             serialized_data: Vec::new(),
224             file_index_to_stable_id: Default::default(),
225             file_index_to_file: Default::default(),
226             prev_cnums: vec![],
227             cnum_map: OnceCell::new(),
228             source_map,
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(),
240         }
241     }
242
243     pub fn serialize<'tcx, E>(&self, tcx: TyCtxt<'tcx>, encoder: &mut E) -> Result<(), E::Error>
244     where
245         E: OpaqueEncoder,
246     {
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());
256
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));
262                 }
263
264                 (file_to_file_index, file_index_to_stable_id)
265             };
266
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);
273
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);
281
282             let latest_foreign_def_path_hashes = self.latest_foreign_def_path_hashes.lock().clone();
283             let hygiene_encode_context = HygieneEncodeContext::default();
284
285             let mut encoder = CacheEncoder {
286                 tcx,
287                 encoder,
288                 type_shorthands: Default::default(),
289                 predicate_shorthands: Default::default(),
290                 interpret_allocs: Default::default(),
291                 source_map: CachingSourceMapView::new(tcx.sess.source_map()),
292                 file_to_file_index,
293                 hygiene_context: &hygiene_encode_context,
294                 latest_foreign_def_path_hashes,
295             };
296
297             // Encode query results.
298             let mut query_result_index = EncodedQueryResultIndex::new();
299
300             tcx.sess.time("encode_query_results", || {
301                 let enc = &mut encoder;
302                 let qri = &mut query_result_index;
303
304                 macro_rules! encode_queries {
305                     ($($query:ident,)*) => {
306                         $(
307                             encode_query_results::<ty::query::queries::$query<'_>, _>(
308                                 tcx,
309                                 enc,
310                                 qri
311                             )?;
312                         )*
313                     }
314                 }
315
316                 rustc_cached_queries!(encode_queries!);
317
318                 Ok(())
319             })?;
320
321             // Encode diagnostics.
322             let diagnostics_index: EncodedDiagnosticsIndex = self
323                 .current_diagnostics
324                 .borrow()
325                 .iter()
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)?;
332
333                     Ok((dep_node_index, pos))
334                 })
335                 .collect::<Result<_, _>>()?;
336
337             let interpret_alloc_index = {
338                 let mut interpret_alloc_index = Vec::new();
339                 let mut n = 0;
340                 loop {
341                     let new_n = encoder.interpret_allocs.len();
342                     // If we have found new IDs, serialize those too.
343                     if n == new_n {
344                         // Otherwise, abort.
345                         break;
346                     }
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)?;
353                     }
354                     n = new_n;
355                 }
356                 interpret_alloc_index
357             };
358
359             let sorted_cnums = sorted_cnums_including_local_crate(tcx);
360             let prev_cnums: Vec<_> = sorted_cnums
361                 .iter()
362                 .map(|&cnum| {
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)
366                 })
367                 .collect();
368
369             let mut syntax_contexts = FxHashMap::default();
370             let mut expn_ids = FxHashMap::default();
371
372             // Encode all hygiene data (`SyntaxContextData` and `ExpnData`) from the current
373             // session.
374
375             hygiene_encode_context.encode(
376                 &mut encoder,
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);
381                     Ok(())
382                 },
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);
387                     Ok(())
388                 },
389             )?;
390
391             let foreign_def_path_hashes =
392                 std::mem::take(&mut encoder.latest_foreign_def_path_hashes);
393
394             // `Encode the file footer.
395             let footer_pos = encoder.position() as u64;
396             encoder.encode_tagged(
397                 TAG_FILE_FOOTER,
398                 &Footer {
399                     file_index_to_stable_id,
400                     prev_cnums,
401                     query_result_index,
402                     diagnostics_index,
403                     interpret_alloc_index,
404                     syntax_contexts,
405                     expn_data: expn_ids,
406                     foreign_def_path_hashes,
407                 },
408             )?;
409
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())?;
413
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.
416
417             return Ok(());
418
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...
424                 cnums.dedup();
425                 cnums
426             }
427         })
428     }
429
430     /// Loads a diagnostic emitted during the previous compilation session.
431     pub fn load_diagnostics(
432         &self,
433         tcx: TyCtxt<'_>,
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");
438
439         diagnostics.unwrap_or_default()
440     }
441
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.
445     #[inline(never)]
446     #[cold]
447     pub fn store_diagnostics(
448         &self,
449         dep_node_index: DepNodeIndex,
450         diagnostics: ThinVec<Diagnostic>,
451     ) {
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());
455     }
456
457     fn get_raw_def_id(&self, hash: &DefPathHash) -> Option<RawDefId> {
458         self.foreign_def_path_hashes.get(hash).copied()
459     }
460
461     fn try_remap_cnum(&self, tcx: TyCtxt<'_>, cnum: u32) -> Option<CrateNum> {
462         let cnum_map =
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);
465
466         cnum_map[CrateNum::from_u32(cnum)]
467     }
468
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,
471         // so it's fine
472         self.latest_foreign_def_path_hashes
473             .lock()
474             .insert(hash, RawDefId { krate: def_id.krate.as_u32(), index: def_id.index.as_u32() });
475     }
476
477     /// If the given `dep_node`'s hash still exists in the current compilation,
478     /// calls `store_foreign_def_id` with its current `DefId`.
479     ///
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());
494
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);
501             }
502         }
503     }
504
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>(
508         &self,
509         tcx: TyCtxt<'tcx>,
510         dep_node_index: SerializedDepNodeIndex,
511     ) -> Option<T>
512     where
513         T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
514     {
515         self.load_indexed(tcx, dep_node_index, &self.query_result_index, "query result")
516     }
517
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`.
522     #[inline(never)]
523     #[cold]
524     pub fn store_diagnostics_for_anon_node(
525         &self,
526         dep_node_index: DepNodeIndex,
527         diagnostics: ThinVec<Diagnostic>,
528     ) {
529         let mut current_diagnostics = self.current_diagnostics.borrow_mut();
530
531         let x = current_diagnostics.entry(dep_node_index).or_insert(Vec::new());
532
533         x.extend(Into::<Vec<_>>::into(diagnostics));
534     }
535
536     fn load_indexed<'tcx, T>(
537         &self,
538         tcx: TyCtxt<'tcx>,
539         dep_node_index: SerializedDepNodeIndex,
540         index: &FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
541         debug_tag: &'static str,
542     ) -> Option<T>
543     where
544         T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
545     {
546         let pos = index.get(&dep_node_index).cloned()?;
547
548         self.with_decoder(tcx, pos, |decoder| match decode_tagged(decoder, dep_node_index) {
549             Ok(v) => Some(v),
550             Err(e) => bug!("could not decode cached {}: {}", debug_tag, e),
551         })
552     }
553
554     fn with_decoder<'a, 'tcx, T, F: FnOnce(&mut CacheDecoder<'sess, 'tcx>) -> T>(
555         &'sess self,
556         tcx: TyCtxt<'tcx>,
557         pos: AbsoluteBytePos,
558         f: F,
559     ) -> T
560     where
561         T: Decodable<CacheDecoder<'a, 'tcx>>,
562     {
563         let cnum_map =
564             self.cnum_map.get_or_init(|| Self::compute_cnum_map(tcx, &self.prev_cnums[..]));
565
566         let mut decoder = CacheDecoder {
567             tcx,
568             opaque: opaque::Decoder::new(&self.serialized_data[..], pos.to_usize()),
569             source_map: self.source_map,
570             cnum_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,
577         };
578         f(&mut decoder)
579     }
580
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
584     // maps to None.
585     fn compute_cnum_map(
586         tcx: TyCtxt<'_>,
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)
592                 .iter()
593                 .map(|&cnum| {
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)
597                 })
598                 .collect::<FxHashMap<_, _>>();
599
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);
602
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();
606             }
607
608             map[LOCAL_CRATE] = Some(LOCAL_CRATE);
609             map
610         })
611     }
612
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(
617         &self,
618         tcx: TyCtxt<'tcx>,
619         hash: DefPathHash,
620     ) -> Option<DefId> {
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
627                 // crate
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));
631                     return Some(def_id);
632                 }
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
641                 // no longer exists.
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
652                 // queries involved.
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);
659                 opt_def_id
660             }
661         }
662     }
663 }
664
665 //- DECODING -------------------------------------------------------------------
666
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> {
671     tcx: TyCtxt<'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,
681 }
682
683 impl<'a, 'tcx> CacheDecoder<'a, 'tcx> {
684     fn file_index_to_file(&self, index: SourceFileIndex) -> Lrc<SourceFile> {
685         let CacheDecoder {
686             ref file_index_to_file,
687             ref file_index_to_stable_id,
688             ref source_map,
689             ..
690         } = *self;
691
692         file_index_to_file
693             .borrow_mut()
694             .entry(index)
695             .or_insert_with(|| {
696                 let stable_id = file_index_to_stable_id[&index];
697                 source_map
698                     .source_file_by_stable_id(stable_id)
699                     .expect("failed to lookup `SourceFile` in new context")
700             })
701             .clone()
702     }
703 }
704
705 trait DecoderWithPosition: Decoder {
706     fn position(&self) -> usize;
707 }
708
709 impl<'a> DecoderWithPosition for opaque::Decoder<'a> {
710     fn position(&self) -> usize {
711         self.position()
712     }
713 }
714
715 impl<'a, 'tcx> DecoderWithPosition for CacheDecoder<'a, 'tcx> {
716     fn position(&self) -> usize {
717         self.opaque.position()
718     }
719 }
720
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>
724 where
725     T: Decodable<D> + Eq + std::fmt::Debug,
726     V: Decodable<D>,
727     D: DecoderWithPosition,
728 {
729     let start_pos = decoder.position();
730
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();
735
736     let expected_len: u64 = Decodable::decode(decoder)?;
737     assert_eq!((end_pos - start_pos) as u64, expected_len);
738
739     Ok(value)
740 }
741
742 impl<'a, 'tcx> TyDecoder<'tcx> for CacheDecoder<'a, 'tcx> {
743     const CLEAR_CROSS_CRATE: bool = false;
744
745     #[inline]
746     fn tcx(&self) -> TyCtxt<'tcx> {
747         self.tcx
748     }
749
750     #[inline]
751     fn position(&self) -> usize {
752         self.opaque.position()
753     }
754
755     #[inline]
756     fn peek_byte(&self) -> u8 {
757         self.opaque.data[self.opaque.position()]
758     }
759
760     fn cached_ty_for_shorthand<F>(
761         &mut self,
762         shorthand: usize,
763         or_insert_with: F,
764     ) -> Result<Ty<'tcx>, Self::Error>
765     where
766         F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>,
767     {
768         let tcx = self.tcx();
769
770         let cache_key =
771             ty::CReaderCacheKey { cnum: CrateNum::ReservedForIncrCompCache, pos: shorthand };
772
773         if let Some(&ty) = tcx.ty_rcache.borrow().get(&cache_key) {
774             return Ok(ty);
775         }
776
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);
780         Ok(ty)
781     }
782
783     fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
784     where
785         F: FnOnce(&mut Self) -> R,
786     {
787         debug_assert!(pos < self.opaque.data.len());
788
789         let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
790         let old_opaque = mem::replace(&mut self.opaque, new_opaque);
791         let r = f(self);
792         self.opaque = old_opaque;
793         r
794     }
795
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))
798     }
799
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)
803     }
804 }
805
806 crate::implement_ty_decoder!(CacheDecoder<'a, 'tcx>);
807
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)?;
817                 Ok(data)
818             })
819         })
820     }
821 }
822
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(
827             decoder,
828             ExpnDataDecodeMode::incr_comp(decoder.hygiene_context),
829             |this, index| {
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.
832                 let pos = expn_data
833                     .get(&index)
834                     .unwrap_or_else(|| panic!("Bad index {:?} (map {:?})", index, expn_data));
835
836                 this.with_position(pos.to_usize(), |decoder| {
837                     let data: ExpnData = decode_tagged(decoder, TAG_EXPN_DATA)?;
838                     Ok(data)
839                 })
840             },
841         )
842     }
843 }
844
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)?;
848
849         if tag == TAG_INVALID_SPAN {
850             return Ok(DUMMY_SP);
851         } else {
852             debug_assert_eq!(tag, TAG_VALID_SPAN);
853         }
854
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)?;
860
861         let file_lo = decoder.file_index_to_file(file_lo_index);
862         let lo = file_lo.lines[line_lo - 1] + col_lo;
863         let hi = lo + len;
864
865         Ok(Span::new(lo, hi, ctxt))
866     }
867 }
868
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))
873     }
874 }
875
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
879 // context.
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`"))
883     }
884 }
885
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)?;
893
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.
899         Ok(d.tcx()
900             .queries
901             .on_disk_cache
902             .as_ref()
903             .unwrap()
904             .def_path_hash_to_def_id(d.tcx(), def_path_hash)
905             .unwrap())
906     }
907 }
908
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)
912     }
913 }
914
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)
918     }
919 }
920
921 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
922     for &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>>
923 {
924     fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Result<Self, String> {
925         RefDecodable::decode(d)
926     }
927 }
928
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)
932     }
933 }
934
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)
938     }
939 }
940
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)
944     }
945 }
946
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)
950     }
951 }
952
953 //- ENCODING -------------------------------------------------------------------
954
955 /// An encoder that can write the incr. comp. cache.
956 struct CacheEncoder<'a, 'tcx, E: OpaqueEncoder> {
957     tcx: TyCtxt<'tcx>,
958     encoder: &'a mut E,
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>,
966 }
967
968 impl<'a, 'tcx, E> CacheEncoder<'a, 'tcx, E>
969 where
970     E: 'a + OpaqueEncoder,
971 {
972     fn source_file_index(&mut self, source_file: Lrc<SourceFile>) -> SourceFileIndex {
973         self.file_to_file_index[&(&*source_file as *const SourceFile)]
974     }
975
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>>(
982         &mut self,
983         tag: T,
984         value: &V,
985     ) -> Result<(), E::Error> {
986         let start_pos = self.position();
987
988         tag.encode(self)?;
989         value.encode(self)?;
990
991         let end_pos = self.position();
992         ((end_pos - start_pos) as u64).encode(self)
993     }
994 }
995
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)
999     }
1000 }
1001
1002 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for SyntaxContext
1003 where
1004     E: 'a + OpaqueEncoder,
1005 {
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)
1008     }
1009 }
1010
1011 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for ExpnId
1012 where
1013     E: 'a + OpaqueEncoder,
1014 {
1015     fn encode(&self, s: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1016         rustc_span::hygiene::raw_encode_expn_id(
1017             *self,
1018             s.hygiene_context,
1019             ExpnDataEncodeMode::IncrComp,
1020             s,
1021         )
1022     }
1023 }
1024
1025 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for Span
1026 where
1027     E: 'a + OpaqueEncoder,
1028 {
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);
1032         }
1033
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) {
1036             Some(pos) => pos,
1037             None => return TAG_INVALID_SPAN.encode(s),
1038         };
1039
1040         if !file_lo.contains(span_data.hi) {
1041             return TAG_INVALID_SPAN.encode(s);
1042         }
1043
1044         let len = span_data.hi - span_data.lo;
1045
1046         let source_file_index = s.source_file_index(file_lo);
1047
1048         TAG_VALID_SPAN.encode(s)?;
1049         source_file_index.encode(s)?;
1050         line_lo.encode(s)?;
1051         col_lo.encode(s)?;
1052         len.encode(s)?;
1053         span_data.ctxt.encode(s)
1054     }
1055 }
1056
1057 impl<'a, 'tcx, E> TyEncoder<'tcx> for CacheEncoder<'a, 'tcx, E>
1058 where
1059     E: 'a + OpaqueEncoder,
1060 {
1061     const CLEAR_CROSS_CRATE: bool = false;
1062
1063     fn position(&self) -> usize {
1064         self.encoder.encoder_position()
1065     }
1066     fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
1067         &mut self.type_shorthands
1068     }
1069     fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::Predicate<'tcx>, usize> {
1070         &mut self.predicate_shorthands
1071     }
1072     fn encode_alloc_id(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
1073         let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
1074
1075         index.encode(self)
1076     }
1077 }
1078
1079 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for DefId
1080 where
1081     E: 'a + OpaqueEncoder,
1082 {
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(
1090                 def_path_hash,
1091                 RawDefId { krate: self.krate.as_u32(), index: self.index.as_u32() },
1092             );
1093         }
1094         def_path_hash.encode(s)
1095     }
1096 }
1097
1098 impl<'a, 'tcx, E> Encodable<CacheEncoder<'a, 'tcx, E>> for DefIndex
1099 where
1100     E: 'a + OpaqueEncoder,
1101 {
1102     fn encode(&self, _: &mut CacheEncoder<'a, 'tcx, E>) -> Result<(), E::Error> {
1103         bug!("encoding `DefIndex` without context");
1104     }
1105 }
1106
1107 macro_rules! encoder_methods {
1108     ($($name:ident($ty:ty);)*) => {
1109         #[inline]
1110         $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
1111             self.encoder.$name(value)
1112         })*
1113     }
1114 }
1115
1116 impl<'a, 'tcx, E> Encoder for CacheEncoder<'a, 'tcx, E>
1117 where
1118     E: 'a + OpaqueEncoder,
1119 {
1120     type Error = E::Error;
1121
1122     #[inline]
1123     fn emit_unit(&mut self) -> Result<(), Self::Error> {
1124         Ok(())
1125     }
1126
1127     encoder_methods! {
1128         emit_usize(usize);
1129         emit_u128(u128);
1130         emit_u64(u64);
1131         emit_u32(u32);
1132         emit_u16(u16);
1133         emit_u8(u8);
1134
1135         emit_isize(isize);
1136         emit_i128(i128);
1137         emit_i64(i64);
1138         emit_i32(i32);
1139         emit_i16(i16);
1140         emit_i8(i8);
1141
1142         emit_bool(bool);
1143         emit_f64(f64);
1144         emit_f32(f32);
1145         emit_char(char);
1146         emit_str(&str);
1147     }
1148 }
1149
1150 // An integer that will always encode to 8 bytes.
1151 struct IntEncodedWithFixedSize(u64);
1152
1153 impl IntEncodedWithFixedSize {
1154     pub const ENCODED_SIZE: usize = 8;
1155 }
1156
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)?;
1162         }
1163         let end_pos = e.position();
1164         assert_eq!((end_pos - start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
1165         Ok(())
1166     }
1167 }
1168
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();
1173
1174         for i in 0..IntEncodedWithFixedSize::ENCODED_SIZE {
1175             let byte: u8 = Decodable::decode(decoder)?;
1176             value |= (byte as u64) << (i * 8);
1177         }
1178
1179         let end_pos = decoder.position();
1180         assert_eq!((end_pos - start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
1181
1182         Ok(IntEncodedWithFixedSize(value))
1183     }
1184 }
1185
1186 fn encode_query_results<'a, 'tcx, Q, E>(
1187     tcx: TyCtxt<'tcx>,
1188     encoder: &mut CacheEncoder<'a, 'tcx, E>,
1189     query_result_index: &mut EncodedQueryResultIndex,
1190 ) -> Result<(), E::Error>
1191 where
1192     Q: super::QueryDescription<TyCtxt<'tcx>> + super::QueryAccessors<TyCtxt<'tcx>>,
1193     Q::Value: Encodable<CacheEncoder<'a, 'tcx, E>>,
1194     E: 'a + OpaqueEncoder,
1195 {
1196     let _timer = tcx
1197         .sess
1198         .prof
1199         .extra_verbose_generic_activity("encode_query_results_for", std::any::type_name::<Q>());
1200
1201     let state = Q::query_state(tcx);
1202     assert!(state.all_inactive());
1203
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());
1208
1209                 // Record position of the cache entry.
1210                 query_result_index
1211                     .push((dep_node, AbsoluteBytePos::new(encoder.encoder.opaque().position())));
1212
1213                 // Encode the type check tables with the `SerializedDepNodeIndex`
1214                 // as tag.
1215                 encoder.encode_tagged(dep_node, value)?;
1216             }
1217         }
1218         Ok(())
1219     })
1220 }