]> git.lizzy.rs Git - rust.git/blob - src/librustc/ty/query/on_disk_cache.rs
Run `rustfmt --file-lines ...` for changes from previous commits.
[rust.git] / src / librustc / ty / query / on_disk_cache.rs
1 use crate::dep_graph::{DepNodeIndex, SerializedDepNodeIndex};
2 use crate::hir;
3 use crate::hir::def_id::{CrateNum, DefIndex, DefId, LocalDefId, LOCAL_CRATE};
4 use crate::hir::map::definitions::DefPathHash;
5 use crate::ich::{CachingSourceMapView, Fingerprint};
6 use crate::mir::{self, interpret};
7 use crate::mir::interpret::{AllocDecodingSession, AllocDecodingState};
8 use crate::rustc_serialize::{Decodable, Decoder, Encodable, Encoder, opaque,
9                       SpecializedDecoder, SpecializedEncoder,
10                       UseSpecializedDecodable, UseSpecializedEncodable};
11 use crate::session::{CrateDisambiguator, Session};
12 use crate::ty::{self, Ty};
13 use crate::ty::codec::{self as ty_codec, TyDecoder, TyEncoder};
14 use crate::ty::context::TyCtxt;
15 use crate::util::common::{time, time_ext};
16
17 use errors::Diagnostic;
18 use rustc_data_structures::fx::FxHashMap;
19 use rustc_data_structures::thin_vec::ThinVec;
20 use rustc_data_structures::sync::{Lrc, Lock, HashMapExt, Once};
21 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
22 use std::mem;
23 use syntax::ast::NodeId;
24 use syntax::source_map::{SourceMap, StableSourceFileId};
25 use syntax_pos::{BytePos, Span, DUMMY_SP, SourceFile};
26 use syntax_pos::hygiene::{Mark, SyntaxContext, ExpnInfo};
27
28 const TAG_FILE_FOOTER: u128 = 0xC0FFEE_C0FFEE_C0FFEE_C0FFEE_C0FFEE;
29
30 const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0;
31 const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1;
32
33 const TAG_NO_EXPANSION_INFO: u8 = 0;
34 const TAG_EXPANSION_INFO_SHORTHAND: u8 = 1;
35 const TAG_EXPANSION_INFO_INLINE: u8 = 2;
36
37 const TAG_VALID_SPAN: u8 = 0;
38 const TAG_INVALID_SPAN: u8 = 1;
39
40 /// `OnDiskCache` provides an interface to incr. comp. data cached from the
41 /// previous compilation session. This data will eventually include the results
42 /// of a few selected queries (like `typeck_tables_of` and `mir_optimized`) and
43 /// any diagnostics that have been emitted during a query.
44 pub struct OnDiskCache<'sess> {
45
46     // The complete cache data in serialized form.
47     serialized_data: Vec<u8>,
48
49     // This field collects all Diagnostics emitted during the current
50     // compilation session.
51     current_diagnostics: Lock<FxHashMap<DepNodeIndex, Vec<Diagnostic>>>,
52
53     prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
54     cnum_map: Once<IndexVec<CrateNum, Option<CrateNum>>>,
55
56     source_map: &'sess SourceMap,
57     file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
58
59     // These two fields caches that are populated lazily during decoding.
60     file_index_to_file: Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
61     synthetic_expansion_infos: Lock<FxHashMap<AbsoluteBytePos, SyntaxContext>>,
62
63     // A map from dep-node to the position of the cached query result in
64     // `serialized_data`.
65     query_result_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
66
67     // A map from dep-node to the position of any associated diagnostics in
68     // `serialized_data`.
69     prev_diagnostics_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
70
71     alloc_decoding_state: AllocDecodingState,
72 }
73
74 // This type is used only for (de-)serialization.
75 #[derive(RustcEncodable, RustcDecodable)]
76 struct Footer {
77     file_index_to_stable_id: FxHashMap<SourceFileIndex, StableSourceFileId>,
78     prev_cnums: Vec<(u32, String, CrateDisambiguator)>,
79     query_result_index: EncodedQueryResultIndex,
80     diagnostics_index: EncodedQueryResultIndex,
81     // the location of all allocations
82     interpret_alloc_index: Vec<u32>,
83 }
84
85 type EncodedQueryResultIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
86 type EncodedDiagnosticsIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
87 type EncodedDiagnostics = Vec<Diagnostic>;
88
89 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
90 struct SourceFileIndex(u32);
91
92 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, RustcEncodable, RustcDecodable)]
93 struct AbsoluteBytePos(u32);
94
95 impl AbsoluteBytePos {
96     fn new(pos: usize) -> AbsoluteBytePos {
97         debug_assert!(pos <= ::std::u32::MAX as usize);
98         AbsoluteBytePos(pos as u32)
99     }
100
101     fn to_usize(self) -> usize {
102         self.0 as usize
103     }
104 }
105
106 impl<'sess> OnDiskCache<'sess> {
107     /// Creates a new OnDiskCache instance from the serialized data in `data`.
108     pub fn new(sess: &'sess Session, data: Vec<u8>, start_pos: usize) -> OnDiskCache<'sess> {
109         debug_assert!(sess.opts.incremental.is_some());
110
111         // Wrapping in a scope so we can borrow `data`
112         let footer: Footer = {
113             let mut decoder = opaque::Decoder::new(&data[..], start_pos);
114
115             // Decode the *position* of the footer which can be found in the
116             // last 8 bytes of the file.
117             decoder.set_position(data.len() - IntEncodedWithFixedSize::ENCODED_SIZE);
118             let query_result_index_pos = IntEncodedWithFixedSize::decode(&mut decoder)
119                 .expect("Error while trying to decode query result index position.")
120                 .0 as usize;
121
122             // Decoder the file footer which contains all the lookup tables, etc.
123             decoder.set_position(query_result_index_pos);
124             decode_tagged(&mut decoder, TAG_FILE_FOOTER)
125                 .expect("Error while trying to decode query result index position.")
126         };
127
128         OnDiskCache {
129             serialized_data: data,
130             file_index_to_stable_id: footer.file_index_to_stable_id,
131             file_index_to_file: Default::default(),
132             prev_cnums: footer.prev_cnums,
133             cnum_map: Once::new(),
134             source_map: sess.source_map(),
135             current_diagnostics: Default::default(),
136             query_result_index: footer.query_result_index.into_iter().collect(),
137             prev_diagnostics_index: footer.diagnostics_index.into_iter().collect(),
138             synthetic_expansion_infos: Default::default(),
139             alloc_decoding_state: AllocDecodingState::new(footer.interpret_alloc_index),
140         }
141     }
142
143     pub fn new_empty(source_map: &'sess SourceMap) -> OnDiskCache<'sess> {
144         OnDiskCache {
145             serialized_data: Vec::new(),
146             file_index_to_stable_id: Default::default(),
147             file_index_to_file: Default::default(),
148             prev_cnums: vec![],
149             cnum_map: Once::new(),
150             source_map,
151             current_diagnostics: Default::default(),
152             query_result_index: Default::default(),
153             prev_diagnostics_index: Default::default(),
154             synthetic_expansion_infos: Default::default(),
155             alloc_decoding_state: AllocDecodingState::new(Vec::new()),
156         }
157     }
158
159     pub fn serialize<'tcx, E>(
160         &self,
161         tcx: TyCtxt<'tcx, 'tcx>,
162         encoder: &mut E,
163     ) -> Result<(), E::Error>
164     where
165         E: ty_codec::TyEncoder,
166     {
167         // Serializing the DepGraph should not modify it:
168         tcx.dep_graph.with_ignore(|| {
169             // Allocate SourceFileIndices
170             let (file_to_file_index, file_index_to_stable_id) = {
171                 let files = tcx.sess.source_map().files();
172                 let mut file_to_file_index = FxHashMap::with_capacity_and_hasher(
173                     files.len(), Default::default());
174                 let mut file_index_to_stable_id = FxHashMap::with_capacity_and_hasher(
175                     files.len(), Default::default());
176
177                 for (index, file) in files.iter().enumerate() {
178                     let index = SourceFileIndex(index as u32);
179                     let file_ptr: *const SourceFile = &**file as *const _;
180                     file_to_file_index.insert(file_ptr, index);
181                     file_index_to_stable_id.insert(index, StableSourceFileId::new(&file));
182                 }
183
184                 (file_to_file_index, file_index_to_stable_id)
185             };
186
187             let mut encoder = CacheEncoder {
188                 tcx,
189                 encoder,
190                 type_shorthands: Default::default(),
191                 predicate_shorthands: Default::default(),
192                 expn_info_shorthands: Default::default(),
193                 interpret_allocs: Default::default(),
194                 interpret_allocs_inverse: Vec::new(),
195                 source_map: CachingSourceMapView::new(tcx.sess.source_map()),
196                 file_to_file_index,
197             };
198
199             // Load everything into memory so we can write it out to the on-disk
200             // cache. The vast majority of cacheable query results should already
201             // be in memory, so this should be a cheap operation.
202             tcx.dep_graph.exec_cache_promotions(tcx);
203
204             // Encode query results
205             let mut query_result_index = EncodedQueryResultIndex::new();
206
207             time(tcx.sess, "encode query results", || {
208                 use crate::ty::query::queries::*;
209                 let enc = &mut encoder;
210                 let qri = &mut query_result_index;
211
212                 encode_query_results::<type_of<'_>, _>(tcx, enc, qri)?;
213                 encode_query_results::<generics_of<'_>, _>(tcx, enc, qri)?;
214                 encode_query_results::<predicates_of<'_>, _>(tcx, enc, qri)?;
215                 encode_query_results::<used_trait_imports<'_>, _>(tcx, enc, qri)?;
216                 encode_query_results::<typeck_tables_of<'_>, _>(tcx, enc, qri)?;
217                 encode_query_results::<codegen_fulfill_obligation<'_>, _>(tcx, enc, qri)?;
218                 encode_query_results::<optimized_mir<'_>, _>(tcx, enc, qri)?;
219                 encode_query_results::<unsafety_check_result<'_>, _>(tcx, enc, qri)?;
220                 encode_query_results::<borrowck<'_>, _>(tcx, enc, qri)?;
221                 encode_query_results::<mir_borrowck<'_>, _>(tcx, enc, qri)?;
222                 encode_query_results::<mir_const_qualif<'_>, _>(tcx, enc, qri)?;
223                 encode_query_results::<const_is_rvalue_promotable_to_static<'_>, _>(tcx, enc, qri)?;
224                 encode_query_results::<symbol_name<'_>, _>(tcx, enc, qri)?;
225                 encode_query_results::<check_match<'_>, _>(tcx, enc, qri)?;
226                 encode_query_results::<codegen_fn_attrs<'_>, _>(tcx, enc, qri)?;
227                 encode_query_results::<specialization_graph_of<'_>, _>(tcx, enc, qri)?;
228
229                 // const eval is special, it only encodes successfully evaluated constants
230                 use crate::ty::query::QueryAccessors;
231                 let cache = const_eval::query_cache(tcx).borrow();
232                 assert!(cache.active.is_empty());
233                 for (key, entry) in cache.results.iter() {
234                     use crate::ty::query::config::QueryDescription;
235                     if const_eval::cache_on_disk(tcx, key.clone()) {
236                         if let Ok(ref value) = entry.value {
237                             let dep_node = SerializedDepNodeIndex::new(entry.index.index());
238
239                             // Record position of the cache entry
240                             qri.push((dep_node, AbsoluteBytePos::new(enc.position())));
241
242                             // Encode the type check tables with the SerializedDepNodeIndex
243                             // as tag.
244                             enc.encode_tagged(dep_node, value)?;
245                         }
246                     }
247                 }
248
249                 Ok(())
250             })?;
251
252             // Encode diagnostics
253             let diagnostics_index: EncodedDiagnosticsIndex = self.current_diagnostics.borrow()
254                 .iter()
255                 .map(|(dep_node_index, diagnostics)|
256             {
257                 let pos = AbsoluteBytePos::new(encoder.position());
258                 // Let's make sure we get the expected type here:
259                 let diagnostics: &EncodedDiagnostics = diagnostics;
260                 let dep_node_index = SerializedDepNodeIndex::new(dep_node_index.index());
261                 encoder.encode_tagged(dep_node_index, diagnostics)?;
262
263                 Ok((dep_node_index, pos))
264             })
265             .collect::<Result<_, _>>()?;
266
267             let interpret_alloc_index = {
268                 let mut interpret_alloc_index = Vec::new();
269                 let mut n = 0;
270                 loop {
271                     let new_n = encoder.interpret_allocs_inverse.len();
272                     // if we have found new ids, serialize those, too
273                     if n == new_n {
274                         // otherwise, abort
275                         break;
276                     }
277                     interpret_alloc_index.reserve(new_n - n);
278                     for idx in n..new_n {
279                         let id = encoder.interpret_allocs_inverse[idx];
280                         let pos = encoder.position() as u32;
281                         interpret_alloc_index.push(pos);
282                         interpret::specialized_encode_alloc_id(
283                             &mut encoder,
284                             tcx,
285                             id,
286                         )?;
287                     }
288                     n = new_n;
289                 }
290                 interpret_alloc_index
291             };
292
293             let sorted_cnums = sorted_cnums_including_local_crate(tcx);
294             let prev_cnums: Vec<_> = sorted_cnums.iter().map(|&cnum| {
295                 let crate_name = tcx.original_crate_name(cnum).as_str().to_string();
296                 let crate_disambiguator = tcx.crate_disambiguator(cnum);
297                 (cnum.as_u32(), crate_name, crate_disambiguator)
298             }).collect();
299
300             // Encode the file footer
301             let footer_pos = encoder.position() as u64;
302             encoder.encode_tagged(TAG_FILE_FOOTER, &Footer {
303                 file_index_to_stable_id,
304                 prev_cnums,
305                 query_result_index,
306                 diagnostics_index,
307                 interpret_alloc_index,
308             })?;
309
310             // Encode the position of the footer as the last 8 bytes of the
311             // file so we know where to look for it.
312             IntEncodedWithFixedSize(footer_pos).encode(encoder.encoder)?;
313
314             // DO NOT WRITE ANYTHING TO THE ENCODER AFTER THIS POINT! The address
315             // of the footer must be the last thing in the data stream.
316
317             return Ok(());
318
319             fn sorted_cnums_including_local_crate(tcx: TyCtxt<'_, '_>) -> Vec<CrateNum> {
320                 let mut cnums = vec![LOCAL_CRATE];
321                 cnums.extend_from_slice(&tcx.crates()[..]);
322                 cnums.sort_unstable();
323                 // Just to be sure...
324                 cnums.dedup();
325                 cnums
326             }
327         })
328     }
329
330     /// Loads a diagnostic emitted during the previous compilation session.
331     pub fn load_diagnostics<'tcx>(
332         &self,
333         tcx: TyCtxt<'tcx, 'tcx>,
334         dep_node_index: SerializedDepNodeIndex,
335     ) -> Vec<Diagnostic> {
336         let diagnostics: Option<EncodedDiagnostics> = self.load_indexed(
337             tcx,
338             dep_node_index,
339             &self.prev_diagnostics_index,
340             "diagnostics");
341
342         diagnostics.unwrap_or_default()
343     }
344
345     /// Stores a diagnostic emitted during the current compilation session.
346     /// Anything stored like this will be available via `load_diagnostics` in
347     /// the next compilation session.
348     #[inline(never)]
349     #[cold]
350     pub fn store_diagnostics(&self,
351                              dep_node_index: DepNodeIndex,
352                              diagnostics: ThinVec<Diagnostic>) {
353         let mut current_diagnostics = self.current_diagnostics.borrow_mut();
354         let prev = current_diagnostics.insert(dep_node_index, diagnostics.into());
355         debug_assert!(prev.is_none());
356     }
357
358     /// Returns the cached query result if there is something in the cache for
359     /// the given `SerializedDepNodeIndex`; otherwise returns `None`.
360     pub fn try_load_query_result<'tcx, T>(
361         &self,
362         tcx: TyCtxt<'tcx, 'tcx>,
363         dep_node_index: SerializedDepNodeIndex,
364     ) -> Option<T>
365     where
366         T: Decodable,
367     {
368         self.load_indexed(tcx,
369                           dep_node_index,
370                           &self.query_result_index,
371                           "query result")
372     }
373
374     /// Stores a diagnostic emitted during computation of an anonymous query.
375     /// Since many anonymous queries can share the same `DepNode`, we aggregate
376     /// them -- as opposed to regular queries where we assume that there is a
377     /// 1:1 relationship between query-key and `DepNode`.
378     #[inline(never)]
379     #[cold]
380     pub fn store_diagnostics_for_anon_node(&self,
381                                            dep_node_index: DepNodeIndex,
382                                            diagnostics: ThinVec<Diagnostic>) {
383         let mut current_diagnostics = self.current_diagnostics.borrow_mut();
384
385         let x = current_diagnostics.entry(dep_node_index).or_insert(Vec::new());
386
387         x.extend(Into::<Vec<_>>::into(diagnostics));
388     }
389
390     fn load_indexed<'tcx, T>(
391         &self,
392         tcx: TyCtxt<'tcx, 'tcx>,
393         dep_node_index: SerializedDepNodeIndex,
394         index: &FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
395         debug_tag: &'static str,
396     ) -> Option<T>
397     where
398         T: Decodable,
399     {
400         let pos = index.get(&dep_node_index).cloned()?;
401
402         // Initialize the cnum_map using the value from the thread which finishes the closure first
403         self.cnum_map.init_nonlocking_same(|| {
404             Self::compute_cnum_map(tcx, &self.prev_cnums[..])
405         });
406
407         let mut decoder = CacheDecoder {
408             tcx,
409             opaque: opaque::Decoder::new(&self.serialized_data[..], pos.to_usize()),
410             source_map: self.source_map,
411             cnum_map: self.cnum_map.get(),
412             file_index_to_file: &self.file_index_to_file,
413             file_index_to_stable_id: &self.file_index_to_stable_id,
414             synthetic_expansion_infos: &self.synthetic_expansion_infos,
415             alloc_decoding_session: self.alloc_decoding_state.new_decoding_session(),
416         };
417
418         match decode_tagged(&mut decoder, dep_node_index) {
419             Ok(value) => {
420                 Some(value)
421             }
422             Err(e) => {
423                 bug!("Could not decode cached {}: {}", debug_tag, e)
424             }
425         }
426     }
427
428     // This function builds mapping from previous-session-CrateNum to
429     // current-session-CrateNum. There might be CrateNums from the previous
430     // Session that don't occur in the current one. For these, the mapping
431     // maps to None.
432     fn compute_cnum_map(
433         tcx: TyCtxt<'_, '_>,
434         prev_cnums: &[(u32, String, CrateDisambiguator)],
435     ) -> IndexVec<CrateNum, Option<CrateNum>> {
436         tcx.dep_graph.with_ignore(|| {
437             let current_cnums = tcx.all_crate_nums(LOCAL_CRATE).iter().map(|&cnum| {
438                 let crate_name = tcx.original_crate_name(cnum)
439                                     .to_string();
440                 let crate_disambiguator = tcx.crate_disambiguator(cnum);
441                 ((crate_name, crate_disambiguator), cnum)
442             }).collect::<FxHashMap<_,_>>();
443
444             let map_size = prev_cnums.iter()
445                                      .map(|&(cnum, ..)| cnum)
446                                      .max()
447                                      .unwrap_or(0) + 1;
448             let mut map = IndexVec::from_elem_n(None, map_size as usize);
449
450             for &(prev_cnum, ref crate_name, crate_disambiguator) in prev_cnums {
451                 let key = (crate_name.clone(), crate_disambiguator);
452                 map[CrateNum::from_u32(prev_cnum)] = current_cnums.get(&key).cloned();
453             }
454
455             map[LOCAL_CRATE] = Some(LOCAL_CRATE);
456             map
457         })
458     }
459 }
460
461 //- DECODING -------------------------------------------------------------------
462
463 /// A decoder that can read the incr. comp. cache. It is similar to the one
464 /// we use for crate metadata decoding in that it can rebase spans and
465 /// eventually will also handle things that contain `Ty` instances.
466 struct CacheDecoder<'a, 'tcx> {
467     tcx: TyCtxt<'tcx, 'tcx>,
468     opaque: opaque::Decoder<'a>,
469     source_map: &'a SourceMap,
470     cnum_map: &'a IndexVec<CrateNum, Option<CrateNum>>,
471     synthetic_expansion_infos: &'a Lock<FxHashMap<AbsoluteBytePos, SyntaxContext>>,
472     file_index_to_file: &'a Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
473     file_index_to_stable_id: &'a FxHashMap<SourceFileIndex, StableSourceFileId>,
474     alloc_decoding_session: AllocDecodingSession<'a>,
475 }
476
477 impl<'a, 'tcx> CacheDecoder<'a, 'tcx> {
478     fn file_index_to_file(&self, index: SourceFileIndex) -> Lrc<SourceFile> {
479         let CacheDecoder {
480             ref file_index_to_file,
481             ref file_index_to_stable_id,
482             ref source_map,
483             ..
484         } = *self;
485
486         file_index_to_file.borrow_mut().entry(index).or_insert_with(|| {
487             let stable_id = file_index_to_stable_id[&index];
488             source_map.source_file_by_stable_id(stable_id)
489                 .expect("Failed to lookup SourceFile in new context.")
490         }).clone()
491     }
492 }
493
494 trait DecoderWithPosition: Decoder {
495     fn position(&self) -> usize;
496 }
497
498 impl<'a> DecoderWithPosition for opaque::Decoder<'a> {
499     fn position(&self) -> usize {
500         self.position()
501     }
502 }
503
504 impl<'a, 'tcx> DecoderWithPosition for CacheDecoder<'a, 'tcx> {
505     fn position(&self) -> usize {
506         self.opaque.position()
507     }
508 }
509
510 // Decode something that was encoded with encode_tagged() and verify that the
511 // tag matches and the correct amount of bytes was read.
512 fn decode_tagged<'a, 'tcx, D, T, V>(decoder: &mut D,
513                                     expected_tag: T)
514                                     -> Result<V, D::Error>
515     where T: Decodable + Eq + ::std::fmt::Debug,
516           V: Decodable,
517           D: DecoderWithPosition,
518           'tcx: 'a,
519 {
520     let start_pos = decoder.position();
521
522     let actual_tag = T::decode(decoder)?;
523     assert_eq!(actual_tag, expected_tag);
524     let value = V::decode(decoder)?;
525     let end_pos = decoder.position();
526
527     let expected_len: u64 = Decodable::decode(decoder)?;
528     assert_eq!((end_pos - start_pos) as u64, expected_len);
529
530     Ok(value)
531 }
532
533 impl<'a, 'tcx> ty_codec::TyDecoder<'tcx> for CacheDecoder<'a, 'tcx> {
534     #[inline]
535     fn tcx(&self) -> TyCtxt<'tcx, 'tcx> {
536         self.tcx
537     }
538
539     #[inline]
540     fn position(&self) -> usize {
541         self.opaque.position()
542     }
543
544     #[inline]
545     fn peek_byte(&self) -> u8 {
546         self.opaque.data[self.opaque.position()]
547     }
548
549     fn cached_ty_for_shorthand<F>(&mut self,
550                                   shorthand: usize,
551                                   or_insert_with: F)
552                                   -> Result<Ty<'tcx>, Self::Error>
553         where F: FnOnce(&mut Self) -> Result<Ty<'tcx>, Self::Error>
554     {
555         let tcx = self.tcx();
556
557         let cache_key = ty::CReaderCacheKey {
558             cnum: CrateNum::ReservedForIncrCompCache,
559             pos: shorthand,
560         };
561
562         if let Some(&ty) = tcx.rcache.borrow().get(&cache_key) {
563             return Ok(ty);
564         }
565
566         let ty = or_insert_with(self)?;
567         // This may overwrite the entry, but it should overwrite with the same value
568         tcx.rcache.borrow_mut().insert_same(cache_key, ty);
569         Ok(ty)
570     }
571
572     fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
573         where F: FnOnce(&mut Self) -> R
574     {
575         debug_assert!(pos < self.opaque.data.len());
576
577         let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
578         let old_opaque = mem::replace(&mut self.opaque, new_opaque);
579         let r = f(self);
580         self.opaque = old_opaque;
581         r
582     }
583
584     fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum {
585         self.cnum_map[cnum].unwrap_or_else(|| {
586             bug!("Could not find new CrateNum for {:?}", cnum)
587         })
588     }
589 }
590
591 implement_ty_decoder!(CacheDecoder<'a, 'tcx>);
592
593 impl<'a, 'tcx> SpecializedDecoder<interpret::AllocId> for CacheDecoder<'a, 'tcx> {
594     fn specialized_decode(&mut self) -> Result<interpret::AllocId, Self::Error> {
595         let alloc_decoding_session = self.alloc_decoding_session;
596         alloc_decoding_session.decode_alloc_id(self)
597     }
598 }
599
600 impl<'a, 'tcx> SpecializedDecoder<Span> for CacheDecoder<'a, 'tcx> {
601     fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
602         let tag: u8 = Decodable::decode(self)?;
603
604         if tag == TAG_INVALID_SPAN {
605             return Ok(DUMMY_SP);
606         } else {
607             debug_assert_eq!(tag, TAG_VALID_SPAN);
608         }
609
610         let file_lo_index = SourceFileIndex::decode(self)?;
611         let line_lo = usize::decode(self)?;
612         let col_lo = BytePos::decode(self)?;
613         let len = BytePos::decode(self)?;
614
615         let file_lo = self.file_index_to_file(file_lo_index);
616         let lo = file_lo.lines[line_lo - 1] + col_lo;
617         let hi = lo + len;
618
619         let expn_info_tag = u8::decode(self)?;
620
621         let ctxt = match expn_info_tag {
622             TAG_NO_EXPANSION_INFO => {
623                 SyntaxContext::empty()
624             }
625             TAG_EXPANSION_INFO_INLINE => {
626                 let pos = AbsoluteBytePos::new(self.opaque.position());
627                 let expn_info: ExpnInfo = Decodable::decode(self)?;
628                 let ctxt = SyntaxContext::allocate_directly(expn_info);
629                 self.synthetic_expansion_infos.borrow_mut().insert(pos, ctxt);
630                 ctxt
631             }
632             TAG_EXPANSION_INFO_SHORTHAND => {
633                 let pos = AbsoluteBytePos::decode(self)?;
634                 let cached_ctxt = self.synthetic_expansion_infos
635                                       .borrow()
636                                       .get(&pos)
637                                       .cloned();
638
639                 if let Some(ctxt) = cached_ctxt {
640                     ctxt
641                 } else {
642                     let expn_info = self.with_position(pos.to_usize(), |this| {
643                          ExpnInfo::decode(this)
644                     })?;
645                     let ctxt = SyntaxContext::allocate_directly(expn_info);
646                     self.synthetic_expansion_infos.borrow_mut().insert(pos, ctxt);
647                     ctxt
648                 }
649             }
650             _ => {
651                 unreachable!()
652             }
653         };
654
655         Ok(Span::new(lo, hi, ctxt))
656     }
657 }
658
659 // This impl makes sure that we get a runtime error when we try decode a
660 // DefIndex that is not contained in a DefId. Such a case would be problematic
661 // because we would not know how to transform the DefIndex to the current
662 // context.
663 impl<'a, 'tcx> SpecializedDecoder<DefIndex> for CacheDecoder<'a, 'tcx> {
664     fn specialized_decode(&mut self) -> Result<DefIndex, Self::Error> {
665         bug!("Trying to decode DefIndex outside the context of a DefId")
666     }
667 }
668
669 // Both the CrateNum and the DefIndex of a DefId can change in between two
670 // compilation sessions. We use the DefPathHash, which is stable across
671 // sessions, to map the old DefId to the new one.
672 impl<'a, 'tcx> SpecializedDecoder<DefId> for CacheDecoder<'a, 'tcx> {
673     #[inline]
674     fn specialized_decode(&mut self) -> Result<DefId, Self::Error> {
675         // Load the DefPathHash which is was we encoded the DefId as.
676         let def_path_hash = DefPathHash::decode(self)?;
677
678         // Using the DefPathHash, we can lookup the new DefId
679         Ok(self.tcx().def_path_hash_to_def_id.as_ref().unwrap()[&def_path_hash])
680     }
681 }
682
683 impl<'a, 'tcx> SpecializedDecoder<LocalDefId> for CacheDecoder<'a, 'tcx> {
684     #[inline]
685     fn specialized_decode(&mut self) -> Result<LocalDefId, Self::Error> {
686         Ok(LocalDefId::from_def_id(DefId::decode(self)?))
687     }
688 }
689
690 impl<'a, 'tcx> SpecializedDecoder<hir::HirId> for CacheDecoder<'a, 'tcx> {
691     fn specialized_decode(&mut self) -> Result<hir::HirId, Self::Error> {
692         // Load the DefPathHash which is was we encoded the DefIndex as.
693         let def_path_hash = DefPathHash::decode(self)?;
694
695         // Use the DefPathHash to map to the current DefId.
696         let def_id = self.tcx()
697                          .def_path_hash_to_def_id
698                          .as_ref()
699                          .unwrap()[&def_path_hash];
700
701         debug_assert!(def_id.is_local());
702
703         // The ItemLocalId needs no remapping.
704         let local_id = hir::ItemLocalId::decode(self)?;
705
706         // Reconstruct the HirId and look up the corresponding NodeId in the
707         // context of the current session.
708         Ok(hir::HirId {
709             owner: def_id.index,
710             local_id
711         })
712     }
713 }
714
715 // NodeIds are not stable across compilation sessions, so we store them in their
716 // HirId representation. This allows use to map them to the current NodeId.
717 impl<'a, 'tcx> SpecializedDecoder<NodeId> for CacheDecoder<'a, 'tcx> {
718     #[inline]
719     fn specialized_decode(&mut self) -> Result<NodeId, Self::Error> {
720         let hir_id = hir::HirId::decode(self)?;
721         Ok(self.tcx().hir().hir_to_node_id(hir_id))
722     }
723 }
724
725 impl<'a, 'tcx> SpecializedDecoder<Fingerprint> for CacheDecoder<'a, 'tcx> {
726     fn specialized_decode(&mut self) -> Result<Fingerprint, Self::Error> {
727         Fingerprint::decode_opaque(&mut self.opaque)
728     }
729 }
730
731 impl<'a, 'tcx, T: Decodable> SpecializedDecoder<mir::ClearCrossCrate<T>>
732     for CacheDecoder<'a, 'tcx>
733 {
734     #[inline]
735     fn specialized_decode(&mut self) -> Result<mir::ClearCrossCrate<T>, Self::Error> {
736         let discr = u8::decode(self)?;
737
738         match discr {
739             TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(mir::ClearCrossCrate::Clear),
740             TAG_CLEAR_CROSS_CRATE_SET => {
741                 let val = T::decode(self)?;
742                 Ok(mir::ClearCrossCrate::Set(val))
743             }
744             _ => {
745                 unreachable!()
746             }
747         }
748     }
749 }
750
751 //- ENCODING -------------------------------------------------------------------
752
753 struct CacheEncoder<'a, 'tcx, E: ty_codec::TyEncoder> {
754     tcx: TyCtxt<'tcx, 'tcx>,
755     encoder: &'a mut E,
756     type_shorthands: FxHashMap<Ty<'tcx>, usize>,
757     predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
758     expn_info_shorthands: FxHashMap<Mark, AbsoluteBytePos>,
759     interpret_allocs: FxHashMap<interpret::AllocId, usize>,
760     interpret_allocs_inverse: Vec<interpret::AllocId>,
761     source_map: CachingSourceMapView<'tcx>,
762     file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>,
763 }
764
765 impl<'a, 'tcx, E> CacheEncoder<'a, 'tcx, E>
766 where
767     E: 'a + ty_codec::TyEncoder,
768 {
769     fn source_file_index(&mut self, source_file: Lrc<SourceFile>) -> SourceFileIndex {
770         self.file_to_file_index[&(&*source_file as *const SourceFile)]
771     }
772
773     /// Encode something with additional information that allows to do some
774     /// sanity checks when decoding the data again. This method will first
775     /// encode the specified tag, then the given value, then the number of
776     /// bytes taken up by tag and value. On decoding, we can then verify that
777     /// we get the expected tag and read the expected number of bytes.
778     fn encode_tagged<T: Encodable, V: Encodable>(&mut self,
779                                                  tag: T,
780                                                  value: &V)
781                                                  -> Result<(), E::Error>
782     {
783         let start_pos = self.position();
784
785         tag.encode(self)?;
786         value.encode(self)?;
787
788         let end_pos = self.position();
789         ((end_pos - start_pos) as u64).encode(self)
790     }
791 }
792
793 impl<'a, 'tcx, E> SpecializedEncoder<interpret::AllocId> for CacheEncoder<'a, 'tcx, E>
794 where
795     E: 'a + ty_codec::TyEncoder,
796 {
797     fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
798         use std::collections::hash_map::Entry;
799         let index = match self.interpret_allocs.entry(*alloc_id) {
800             Entry::Occupied(e) => *e.get(),
801             Entry::Vacant(e) => {
802                 let idx = self.interpret_allocs_inverse.len();
803                 self.interpret_allocs_inverse.push(*alloc_id);
804                 e.insert(idx);
805                 idx
806             },
807         };
808
809         index.encode(self)
810     }
811 }
812
813 impl<'a, 'tcx, E> SpecializedEncoder<Span> for CacheEncoder<'a, 'tcx, E>
814 where
815     E: 'a + ty_codec::TyEncoder,
816 {
817     fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
818
819         if *span == DUMMY_SP {
820             return TAG_INVALID_SPAN.encode(self);
821         }
822
823         let span_data = span.data();
824
825         if span_data.hi < span_data.lo {
826             return TAG_INVALID_SPAN.encode(self);
827         }
828
829         let (file_lo, line_lo, col_lo) = match self.source_map
830                                                    .byte_pos_to_line_and_col(span_data.lo) {
831             Some(pos) => pos,
832             None => return TAG_INVALID_SPAN.encode(self)
833         };
834
835         if !file_lo.contains(span_data.hi) {
836             return TAG_INVALID_SPAN.encode(self);
837         }
838
839         let len = span_data.hi - span_data.lo;
840
841         let source_file_index = self.source_file_index(file_lo);
842
843         TAG_VALID_SPAN.encode(self)?;
844         source_file_index.encode(self)?;
845         line_lo.encode(self)?;
846         col_lo.encode(self)?;
847         len.encode(self)?;
848
849         if span_data.ctxt == SyntaxContext::empty() {
850             TAG_NO_EXPANSION_INFO.encode(self)
851         } else {
852             let (mark, expn_info) = span_data.ctxt.outer_and_expn_info();
853             if let Some(expn_info) = expn_info {
854                 if let Some(pos) = self.expn_info_shorthands.get(&mark).cloned() {
855                     TAG_EXPANSION_INFO_SHORTHAND.encode(self)?;
856                     pos.encode(self)
857                 } else {
858                     TAG_EXPANSION_INFO_INLINE.encode(self)?;
859                     let pos = AbsoluteBytePos::new(self.position());
860                     self.expn_info_shorthands.insert(mark, pos);
861                     expn_info.encode(self)
862                 }
863             } else {
864                 TAG_NO_EXPANSION_INFO.encode(self)
865             }
866         }
867     }
868 }
869
870 impl<'a, 'tcx, E> ty_codec::TyEncoder for CacheEncoder<'a, 'tcx, E>
871 where
872     E: 'a + ty_codec::TyEncoder,
873 {
874     #[inline]
875     fn position(&self) -> usize {
876         self.encoder.position()
877     }
878 }
879
880 impl<'a, 'tcx, E> SpecializedEncoder<CrateNum> for CacheEncoder<'a, 'tcx, E>
881 where
882     E: 'a + ty_codec::TyEncoder,
883 {
884     #[inline]
885     fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
886         self.emit_u32(cnum.as_u32())
887     }
888 }
889
890 impl<'a, 'tcx, E> SpecializedEncoder<Ty<'tcx>> for CacheEncoder<'a, 'tcx, E>
891 where
892     E: 'a + ty_codec::TyEncoder,
893 {
894     #[inline]
895     fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
896         ty_codec::encode_with_shorthand(self, ty,
897             |encoder| &mut encoder.type_shorthands)
898     }
899 }
900
901 impl<'a, 'tcx, E> SpecializedEncoder<ty::GenericPredicates<'tcx>> for CacheEncoder<'a, 'tcx, E>
902 where
903     E: 'a + ty_codec::TyEncoder,
904 {
905     #[inline]
906     fn specialized_encode(&mut self,
907                           predicates: &ty::GenericPredicates<'tcx>)
908                           -> Result<(), Self::Error> {
909         ty_codec::encode_predicates(self, predicates,
910             |encoder| &mut encoder.predicate_shorthands)
911     }
912 }
913
914 impl<'a, 'tcx, E> SpecializedEncoder<hir::HirId> for CacheEncoder<'a, 'tcx, E>
915 where
916     E: 'a + ty_codec::TyEncoder,
917 {
918     #[inline]
919     fn specialized_encode(&mut self, id: &hir::HirId) -> Result<(), Self::Error> {
920         let hir::HirId {
921             owner,
922             local_id,
923         } = *id;
924
925         let def_path_hash = self.tcx.hir().definitions().def_path_hash(owner);
926
927         def_path_hash.encode(self)?;
928         local_id.encode(self)
929     }
930 }
931
932 impl<'a, 'tcx, E> SpecializedEncoder<DefId> for CacheEncoder<'a, 'tcx, E>
933 where
934     E: 'a + ty_codec::TyEncoder,
935 {
936     #[inline]
937     fn specialized_encode(&mut self, id: &DefId) -> Result<(), Self::Error> {
938         let def_path_hash = self.tcx.def_path_hash(*id);
939         def_path_hash.encode(self)
940     }
941 }
942
943 impl<'a, 'tcx, E> SpecializedEncoder<LocalDefId> for CacheEncoder<'a, 'tcx, E>
944 where
945     E: 'a + ty_codec::TyEncoder,
946 {
947     #[inline]
948     fn specialized_encode(&mut self, id: &LocalDefId) -> Result<(), Self::Error> {
949         id.to_def_id().encode(self)
950     }
951 }
952
953 impl<'a, 'tcx, E> SpecializedEncoder<DefIndex> for CacheEncoder<'a, 'tcx, E>
954 where
955     E: 'a + ty_codec::TyEncoder,
956 {
957     fn specialized_encode(&mut self, _: &DefIndex) -> Result<(), Self::Error> {
958         bug!("Encoding DefIndex without context.")
959     }
960 }
961
962 // NodeIds are not stable across compilation sessions, so we store them in their
963 // HirId representation. This allows use to map them to the current NodeId.
964 impl<'a, 'tcx, E> SpecializedEncoder<NodeId> for CacheEncoder<'a, 'tcx, E>
965 where
966     E: 'a + ty_codec::TyEncoder,
967 {
968     #[inline]
969     fn specialized_encode(&mut self, node_id: &NodeId) -> Result<(), Self::Error> {
970         let hir_id = self.tcx.hir().node_to_hir_id(*node_id);
971         hir_id.encode(self)
972     }
973 }
974
975 impl<'a, 'tcx> SpecializedEncoder<Fingerprint> for CacheEncoder<'a, 'tcx, opaque::Encoder> {
976     fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
977         f.encode_opaque(&mut self.encoder)
978     }
979 }
980
981 impl<'a, 'tcx, E, T> SpecializedEncoder<mir::ClearCrossCrate<T>> for CacheEncoder<'a, 'tcx, E>
982 where
983     E: 'a + ty_codec::TyEncoder,
984     T: Encodable,
985 {
986     #[inline]
987     fn specialized_encode(&mut self,
988                           val: &mir::ClearCrossCrate<T>)
989                           -> Result<(), Self::Error> {
990         match *val {
991             mir::ClearCrossCrate::Clear => {
992                 TAG_CLEAR_CROSS_CRATE_CLEAR.encode(self)
993             }
994             mir::ClearCrossCrate::Set(ref val) => {
995                 TAG_CLEAR_CROSS_CRATE_SET.encode(self)?;
996                 val.encode(self)
997             }
998         }
999     }
1000 }
1001
1002 macro_rules! encoder_methods {
1003     ($($name:ident($ty:ty);)*) => {
1004         $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
1005             self.encoder.$name(value)
1006         })*
1007     }
1008 }
1009
1010 impl<'a, 'tcx, E> Encoder for CacheEncoder<'a, 'tcx, E>
1011 where
1012     E: 'a + ty_codec::TyEncoder,
1013 {
1014     type Error = E::Error;
1015
1016     fn emit_unit(&mut self) -> Result<(), Self::Error> {
1017         Ok(())
1018     }
1019
1020     encoder_methods! {
1021         emit_usize(usize);
1022         emit_u128(u128);
1023         emit_u64(u64);
1024         emit_u32(u32);
1025         emit_u16(u16);
1026         emit_u8(u8);
1027
1028         emit_isize(isize);
1029         emit_i128(i128);
1030         emit_i64(i64);
1031         emit_i32(i32);
1032         emit_i16(i16);
1033         emit_i8(i8);
1034
1035         emit_bool(bool);
1036         emit_f64(f64);
1037         emit_f32(f32);
1038         emit_char(char);
1039         emit_str(&str);
1040     }
1041 }
1042
1043 // An integer that will always encode to 8 bytes.
1044 struct IntEncodedWithFixedSize(u64);
1045
1046 impl IntEncodedWithFixedSize {
1047     pub const ENCODED_SIZE: usize = 8;
1048 }
1049
1050 impl UseSpecializedEncodable for IntEncodedWithFixedSize {}
1051 impl UseSpecializedDecodable for IntEncodedWithFixedSize {}
1052
1053 impl SpecializedEncoder<IntEncodedWithFixedSize> for opaque::Encoder {
1054     fn specialized_encode(&mut self, x: &IntEncodedWithFixedSize) -> Result<(), Self::Error> {
1055         let start_pos = self.position();
1056         for i in 0 .. IntEncodedWithFixedSize::ENCODED_SIZE {
1057             ((x.0 >> i * 8) as u8).encode(self)?;
1058         }
1059         let end_pos = self.position();
1060         assert_eq!((end_pos - start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
1061         Ok(())
1062     }
1063 }
1064
1065 impl<'a> SpecializedDecoder<IntEncodedWithFixedSize> for opaque::Decoder<'a> {
1066     fn specialized_decode(&mut self) -> Result<IntEncodedWithFixedSize, Self::Error> {
1067         let mut value: u64 = 0;
1068         let start_pos = self.position();
1069
1070         for i in 0 .. IntEncodedWithFixedSize::ENCODED_SIZE {
1071             let byte: u8 = Decodable::decode(self)?;
1072             value |= (byte as u64) << (i * 8);
1073         }
1074
1075         let end_pos = self.position();
1076         assert_eq!((end_pos - start_pos), IntEncodedWithFixedSize::ENCODED_SIZE);
1077
1078         Ok(IntEncodedWithFixedSize(value))
1079     }
1080 }
1081
1082 fn encode_query_results<'a, 'tcx, Q, E>(
1083     tcx: TyCtxt<'tcx, 'tcx>,
1084     encoder: &mut CacheEncoder<'a, 'tcx, E>,
1085     query_result_index: &mut EncodedQueryResultIndex,
1086 ) -> Result<(), E::Error>
1087 where
1088     Q: super::config::QueryDescription<'tcx>,
1089     E: 'a + TyEncoder,
1090     Q::Value: Encodable,
1091 {
1092     let desc = &format!("encode_query_results for {}",
1093         unsafe { ::std::intrinsics::type_name::<Q>() });
1094
1095     time_ext(tcx.sess.time_extended(), Some(tcx.sess), desc, || {
1096         let map = Q::query_cache(tcx).borrow();
1097         assert!(map.active.is_empty());
1098         for (key, entry) in map.results.iter() {
1099             if Q::cache_on_disk(tcx, key.clone()) {
1100                 let dep_node = SerializedDepNodeIndex::new(entry.index.index());
1101
1102                 // Record position of the cache entry
1103                 query_result_index.push((dep_node, AbsoluteBytePos::new(encoder.position())));
1104
1105                 // Encode the type check tables with the SerializedDepNodeIndex
1106                 // as tag.
1107                 encoder.encode_tagged(dep_node, &entry.value)?;
1108             }
1109         }
1110
1111         Ok(())
1112     })
1113 }