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