2 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
3 use rustc_data_structures::memmap::Mmap;
4 use rustc_data_structures::sync::{HashMapExt, Lock, Lrc, RwLock};
5 use rustc_data_structures::unhash::UnhashMap;
6 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, StableCrateId, LOCAL_CRATE};
7 use rustc_hir::definitions::DefPathHash;
8 use rustc_index::vec::{Idx, IndexVec};
9 use rustc_middle::dep_graph::{DepNodeIndex, SerializedDepNodeIndex};
10 use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState};
11 use rustc_middle::mir::{self, interpret};
12 use rustc_middle::ty::codec::{RefDecodable, TyDecoder, TyEncoder};
13 use rustc_middle::ty::{self, Ty, TyCtxt};
14 use rustc_query_system::dep_graph::DepContext;
15 use rustc_query_system::query::{QueryCache, QueryContext, QuerySideEffects};
16 use rustc_serialize::{
17 opaque::{FileEncodeResult, FileEncoder, IntEncodedWithFixedSize, MemDecoder},
18 Decodable, Decoder, Encodable, Encoder,
20 use rustc_session::Session;
21 use rustc_span::hygiene::{
22 ExpnId, HygieneDecodeContext, HygieneEncodeContext, SyntaxContext, SyntaxContextData,
24 use rustc_span::source_map::{SourceMap, StableSourceFileId};
25 use rustc_span::{BytePos, ExpnData, ExpnHash, Pos, SourceFile, Span};
26 use rustc_span::{CachingSourceMapView, Symbol};
27 use std::collections::hash_map::Entry;
31 const TAG_FILE_FOOTER: u128 = 0xC0FFEE_C0FFEE_C0FFEE_C0FFEE_C0FFEE;
33 // A normal span encoded with both location information and a `SyntaxContext`
34 const TAG_FULL_SPAN: u8 = 0;
35 // A partial span with no location information, encoded only with a `SyntaxContext`
36 const TAG_PARTIAL_SPAN: u8 = 1;
37 const TAG_RELATIVE_SPAN: u8 = 2;
39 const TAG_SYNTAX_CONTEXT: u8 = 0;
40 const TAG_EXPN_DATA: u8 = 1;
42 // Tags for encoding Symbol's
43 const SYMBOL_STR: u8 = 0;
44 const SYMBOL_OFFSET: u8 = 1;
46 /// Provides an interface to incremental compilation data cached from the
47 /// previous compilation session. This data will eventually include the results
48 /// of a few selected queries (like `typeck` and `mir_optimized`) and
49 /// any side effects that have been emitted during a query.
50 pub struct OnDiskCache<'sess> {
51 // The complete cache data in serialized form.
52 serialized_data: RwLock<Option<Mmap>>,
54 // Collects all `QuerySideEffects` created during the current compilation
56 current_side_effects: Lock<FxHashMap<DepNodeIndex, QuerySideEffects>>,
58 source_map: &'sess SourceMap,
59 file_index_to_stable_id: FxHashMap<SourceFileIndex, EncodedSourceFileId>,
61 // Caches that are populated lazily during decoding.
62 file_index_to_file: Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
64 // A map from dep-node to the position of the cached query result in
66 query_result_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
68 // A map from dep-node to the position of any associated `QuerySideEffects` in
70 prev_side_effects_index: FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
72 alloc_decoding_state: AllocDecodingState,
74 // A map from syntax context ids to the position of their associated
75 // `SyntaxContextData`. We use a `u32` instead of a `SyntaxContext`
76 // to represent the fact that we are storing *encoded* ids. When we decode
77 // a `SyntaxContext`, a new id will be allocated from the global `HygieneData`,
78 // which will almost certainly be different than the serialized id.
79 syntax_contexts: FxHashMap<u32, AbsoluteBytePos>,
80 // A map from the `DefPathHash` of an `ExpnId` to the position
81 // of their associated `ExpnData`. Ideally, we would store a `DefId`,
82 // but we need to decode this before we've constructed a `TyCtxt` (which
83 // makes it difficult to decode a `DefId`).
85 // Note that these `DefPathHashes` correspond to both local and foreign
86 // `ExpnData` (e.g `ExpnData.krate` may not be `LOCAL_CRATE`). Alternatively,
87 // we could look up the `ExpnData` from the metadata of foreign crates,
88 // but it seemed easier to have `OnDiskCache` be independent of the `CStore`.
89 expn_data: UnhashMap<ExpnHash, AbsoluteBytePos>,
90 // Additional information used when decoding hygiene data.
91 hygiene_context: HygieneDecodeContext,
92 // Maps `ExpnHash`es to their raw value from the *previous*
93 // compilation session. This is used as an initial 'guess' when
94 // we try to map an `ExpnHash` to its value in the current
95 // compilation session.
96 foreign_expn_data: UnhashMap<ExpnHash, u32>,
99 // This type is used only for serialization and deserialization.
100 #[derive(Encodable, Decodable)]
102 file_index_to_stable_id: FxHashMap<SourceFileIndex, EncodedSourceFileId>,
103 query_result_index: EncodedDepNodeIndex,
104 side_effects_index: EncodedDepNodeIndex,
105 // The location of all allocations.
106 interpret_alloc_index: Vec<u32>,
107 // See `OnDiskCache.syntax_contexts`
108 syntax_contexts: FxHashMap<u32, AbsoluteBytePos>,
109 // See `OnDiskCache.expn_data`
110 expn_data: UnhashMap<ExpnHash, AbsoluteBytePos>,
111 foreign_expn_data: UnhashMap<ExpnHash, u32>,
114 pub type EncodedDepNodeIndex = Vec<(SerializedDepNodeIndex, AbsoluteBytePos)>;
116 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Encodable, Decodable)]
117 struct SourceFileIndex(u32);
119 #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Encodable, Decodable)]
120 pub struct AbsoluteBytePos(u32);
122 impl AbsoluteBytePos {
123 fn new(pos: usize) -> AbsoluteBytePos {
124 debug_assert!(pos <= u32::MAX as usize);
125 AbsoluteBytePos(pos as u32)
128 fn to_usize(self) -> usize {
133 /// An `EncodedSourceFileId` is the same as a `StableSourceFileId` except that
134 /// the source crate is represented as a [StableCrateId] instead of as a
135 /// `CrateNum`. This way `EncodedSourceFileId` can be encoded and decoded
136 /// without any additional context, i.e. with a simple `opaque::Decoder` (which
137 /// is the only thing available when decoding the cache's [Footer].
138 #[derive(Encodable, Decodable, Clone, Debug)]
139 struct EncodedSourceFileId {
141 stable_crate_id: StableCrateId,
144 impl EncodedSourceFileId {
145 fn translate(&self, tcx: TyCtxt<'_>) -> StableSourceFileId {
146 let cnum = tcx.stable_crate_id_to_crate_num(self.stable_crate_id);
147 StableSourceFileId { file_name_hash: self.file_name_hash, cnum }
150 fn new(tcx: TyCtxt<'_>, file: &SourceFile) -> EncodedSourceFileId {
151 let source_file_id = StableSourceFileId::new(file);
152 EncodedSourceFileId {
153 file_name_hash: source_file_id.file_name_hash,
154 stable_crate_id: tcx.stable_crate_id(source_file_id.cnum),
159 impl<'sess> rustc_middle::ty::OnDiskCache<'sess> for OnDiskCache<'sess> {
160 /// Creates a new `OnDiskCache` instance from the serialized data in `data`.
161 fn new(sess: &'sess Session, data: Mmap, start_pos: usize) -> Self {
162 debug_assert!(sess.opts.incremental.is_some());
164 // Wrap in a scope so we can borrow `data`.
165 let footer: Footer = {
166 let mut decoder = MemDecoder::new(&data, start_pos);
168 // Decode the *position* of the footer, which can be found in the
169 // last 8 bytes of the file.
170 decoder.set_position(data.len() - IntEncodedWithFixedSize::ENCODED_SIZE);
171 let footer_pos = IntEncodedWithFixedSize::decode(&mut decoder).0 as usize;
173 // Decode the file footer, which contains all the lookup tables, etc.
174 decoder.set_position(footer_pos);
176 decode_tagged(&mut decoder, TAG_FILE_FOOTER)
180 serialized_data: RwLock::new(Some(data)),
181 file_index_to_stable_id: footer.file_index_to_stable_id,
182 file_index_to_file: Default::default(),
183 source_map: sess.source_map(),
184 current_side_effects: Default::default(),
185 query_result_index: footer.query_result_index.into_iter().collect(),
186 prev_side_effects_index: footer.side_effects_index.into_iter().collect(),
187 alloc_decoding_state: AllocDecodingState::new(footer.interpret_alloc_index),
188 syntax_contexts: footer.syntax_contexts,
189 expn_data: footer.expn_data,
190 foreign_expn_data: footer.foreign_expn_data,
191 hygiene_context: Default::default(),
195 fn new_empty(source_map: &'sess SourceMap) -> Self {
197 serialized_data: RwLock::new(None),
198 file_index_to_stable_id: Default::default(),
199 file_index_to_file: Default::default(),
201 current_side_effects: Default::default(),
202 query_result_index: Default::default(),
203 prev_side_effects_index: Default::default(),
204 alloc_decoding_state: AllocDecodingState::new(Vec::new()),
205 syntax_contexts: FxHashMap::default(),
206 expn_data: UnhashMap::default(),
207 foreign_expn_data: UnhashMap::default(),
208 hygiene_context: Default::default(),
212 /// Execute all cache promotions and release the serialized backing Mmap.
214 /// Cache promotions require invoking queries, which needs to read the serialized data.
215 /// In order to serialize the new on-disk cache, the former on-disk cache file needs to be
216 /// deleted, hence we won't be able to refer to its memmapped data.
217 fn drop_serialized_data(&self, tcx: TyCtxt<'_>) {
218 // Load everything into memory so we can write it out to the on-disk
219 // cache. The vast majority of cacheable query results should already
220 // be in memory, so this should be a cheap operation.
221 // Do this *before* we clone 'latest_foreign_def_path_hashes', since
222 // loading existing queries may cause us to create new DepNodes, which
223 // may in turn end up invoking `store_foreign_def_id_hash`
224 tcx.dep_graph.exec_cache_promotions(tcx);
226 *self.serialized_data.write() = None;
229 fn serialize<'tcx>(&self, tcx: TyCtxt<'tcx>, encoder: FileEncoder) -> FileEncodeResult {
230 // Serializing the `DepGraph` should not modify it.
231 tcx.dep_graph.with_ignore(|| {
232 // Allocate `SourceFileIndex`es.
233 let (file_to_file_index, file_index_to_stable_id) = {
234 let files = tcx.sess.source_map().files();
235 let mut file_to_file_index =
236 FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
237 let mut file_index_to_stable_id =
238 FxHashMap::with_capacity_and_hasher(files.len(), Default::default());
240 for (index, file) in files.iter().enumerate() {
241 let index = SourceFileIndex(index as u32);
242 let file_ptr: *const SourceFile = &**file as *const _;
243 file_to_file_index.insert(file_ptr, index);
244 let source_file_id = EncodedSourceFileId::new(tcx, &file);
245 file_index_to_stable_id.insert(index, source_file_id);
248 (file_to_file_index, file_index_to_stable_id)
251 let hygiene_encode_context = HygieneEncodeContext::default();
253 let mut encoder = CacheEncoder {
256 type_shorthands: Default::default(),
257 predicate_shorthands: Default::default(),
258 interpret_allocs: Default::default(),
259 source_map: CachingSourceMapView::new(tcx.sess.source_map()),
261 hygiene_context: &hygiene_encode_context,
262 symbol_table: Default::default(),
265 // Encode query results.
266 let mut query_result_index = EncodedDepNodeIndex::new();
268 tcx.sess.time("encode_query_results", || {
269 let enc = &mut encoder;
270 let qri = &mut query_result_index;
271 QueryCtxt::from_tcx(tcx).encode_query_results(enc, qri);
274 // Encode side effects.
275 let side_effects_index: EncodedDepNodeIndex = self
276 .current_side_effects
279 .map(|(dep_node_index, side_effects)| {
280 let pos = AbsoluteBytePos::new(encoder.position());
281 let dep_node_index = SerializedDepNodeIndex::new(dep_node_index.index());
282 encoder.encode_tagged(dep_node_index, side_effects);
284 (dep_node_index, pos)
288 let interpret_alloc_index = {
289 let mut interpret_alloc_index = Vec::new();
292 let new_n = encoder.interpret_allocs.len();
293 // If we have found new IDs, serialize those too.
298 interpret_alloc_index.reserve(new_n - n);
299 for idx in n..new_n {
300 let id = encoder.interpret_allocs[idx];
301 let pos = encoder.position() as u32;
302 interpret_alloc_index.push(pos);
303 interpret::specialized_encode_alloc_id(&mut encoder, tcx, id);
307 interpret_alloc_index
310 let mut syntax_contexts = FxHashMap::default();
311 let mut expn_data = UnhashMap::default();
312 let mut foreign_expn_data = UnhashMap::default();
314 // Encode all hygiene data (`SyntaxContextData` and `ExpnData`) from the current
317 hygiene_encode_context.encode(
319 |encoder, index, ctxt_data| {
320 let pos = AbsoluteBytePos::new(encoder.position());
321 encoder.encode_tagged(TAG_SYNTAX_CONTEXT, ctxt_data);
322 syntax_contexts.insert(index, pos);
324 |encoder, expn_id, data, hash| {
325 if expn_id.krate == LOCAL_CRATE {
326 let pos = AbsoluteBytePos::new(encoder.position());
327 encoder.encode_tagged(TAG_EXPN_DATA, data);
328 expn_data.insert(hash, pos);
330 foreign_expn_data.insert(hash, expn_id.local_id.as_u32());
335 // `Encode the file footer.
336 let footer_pos = encoder.position() as u64;
337 encoder.encode_tagged(
340 file_index_to_stable_id,
343 interpret_alloc_index,
350 // Encode the position of the footer as the last 8 bytes of the
351 // file so we know where to look for it.
352 IntEncodedWithFixedSize(footer_pos).encode(&mut encoder.encoder);
354 // DO NOT WRITE ANYTHING TO THE ENCODER AFTER THIS POINT! The address
355 // of the footer must be the last thing in the data stream.
362 impl<'sess> OnDiskCache<'sess> {
363 pub fn as_dyn(&self) -> &dyn rustc_middle::ty::OnDiskCache<'sess> {
367 /// Loads a `QuerySideEffects` created during the previous compilation session.
368 pub fn load_side_effects(
371 dep_node_index: SerializedDepNodeIndex,
372 ) -> QuerySideEffects {
373 let side_effects: Option<QuerySideEffects> =
374 self.load_indexed(tcx, dep_node_index, &self.prev_side_effects_index);
376 side_effects.unwrap_or_default()
379 /// Stores a `QuerySideEffects` emitted during the current compilation session.
380 /// Anything stored like this will be available via `load_side_effects` in
381 /// the next compilation session.
384 pub fn store_side_effects(&self, dep_node_index: DepNodeIndex, side_effects: QuerySideEffects) {
385 let mut current_side_effects = self.current_side_effects.borrow_mut();
386 let prev = current_side_effects.insert(dep_node_index, side_effects);
387 debug_assert!(prev.is_none());
390 /// Returns the cached query result if there is something in the cache for
391 /// the given `SerializedDepNodeIndex`; otherwise returns `None`.
392 pub fn try_load_query_result<'tcx, T>(
395 dep_node_index: SerializedDepNodeIndex,
398 T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
400 self.load_indexed(tcx, dep_node_index, &self.query_result_index)
403 /// Stores side effect emitted during computation of an anonymous query.
404 /// Since many anonymous queries can share the same `DepNode`, we aggregate
405 /// them -- as opposed to regular queries where we assume that there is a
406 /// 1:1 relationship between query-key and `DepNode`.
409 pub fn store_side_effects_for_anon_node(
411 dep_node_index: DepNodeIndex,
412 side_effects: QuerySideEffects,
414 let mut current_side_effects = self.current_side_effects.borrow_mut();
416 let x = current_side_effects.entry(dep_node_index).or_default();
417 x.append(side_effects);
420 fn load_indexed<'tcx, T>(
423 dep_node_index: SerializedDepNodeIndex,
424 index: &FxHashMap<SerializedDepNodeIndex, AbsoluteBytePos>,
427 T: for<'a> Decodable<CacheDecoder<'a, 'tcx>>,
429 let pos = index.get(&dep_node_index).cloned()?;
431 self.with_decoder(tcx, pos, |decoder| Some(decode_tagged(decoder, dep_node_index)))
434 fn with_decoder<'a, 'tcx, T, F: for<'s> FnOnce(&mut CacheDecoder<'s, 'tcx>) -> T>(
437 pos: AbsoluteBytePos,
441 T: Decodable<CacheDecoder<'a, 'tcx>>,
443 let serialized_data = self.serialized_data.read();
444 let mut decoder = CacheDecoder {
446 opaque: MemDecoder::new(serialized_data.as_deref().unwrap_or(&[]), pos.to_usize()),
447 source_map: self.source_map,
448 file_index_to_file: &self.file_index_to_file,
449 file_index_to_stable_id: &self.file_index_to_stable_id,
450 alloc_decoding_session: self.alloc_decoding_state.new_decoding_session(),
451 syntax_contexts: &self.syntax_contexts,
452 expn_data: &self.expn_data,
453 foreign_expn_data: &self.foreign_expn_data,
454 hygiene_context: &self.hygiene_context,
460 //- DECODING -------------------------------------------------------------------
462 /// A decoder that can read from the incremental compilation cache. It is similar to the one
463 /// we use for crate metadata decoding in that it can rebase spans and eventually
464 /// will also handle things that contain `Ty` instances.
465 pub struct CacheDecoder<'a, 'tcx> {
467 opaque: MemDecoder<'a>,
468 source_map: &'a SourceMap,
469 file_index_to_file: &'a Lock<FxHashMap<SourceFileIndex, Lrc<SourceFile>>>,
470 file_index_to_stable_id: &'a FxHashMap<SourceFileIndex, EncodedSourceFileId>,
471 alloc_decoding_session: AllocDecodingSession<'a>,
472 syntax_contexts: &'a FxHashMap<u32, AbsoluteBytePos>,
473 expn_data: &'a UnhashMap<ExpnHash, AbsoluteBytePos>,
474 foreign_expn_data: &'a UnhashMap<ExpnHash, u32>,
475 hygiene_context: &'a HygieneDecodeContext,
478 impl<'a, 'tcx> CacheDecoder<'a, 'tcx> {
479 fn file_index_to_file(&self, index: SourceFileIndex) -> Lrc<SourceFile> {
482 ref file_index_to_file,
483 ref file_index_to_stable_id,
492 let stable_id = file_index_to_stable_id[&index].translate(tcx);
494 // If this `SourceFile` is from a foreign crate, then make sure
495 // that we've imported all of the source files from that crate.
496 // This has usually already been done during macro invocation.
497 // However, when encoding query results like `TypeckResults`,
498 // we might encode an `AdtDef` for a foreign type (because it
499 // was referenced in the body of the function). There is no guarantee
500 // that we will load the source files from that crate during macro
501 // expansion, so we use `import_source_files` to ensure that the foreign
502 // source files are actually imported before we call `source_file_by_stable_id`.
503 if stable_id.cnum != LOCAL_CRATE {
504 self.tcx.cstore_untracked().import_source_files(self.tcx.sess, stable_id.cnum);
508 .source_file_by_stable_id(stable_id)
509 .expect("failed to lookup `SourceFile` in new context")
515 trait DecoderWithPosition: Decoder {
516 fn position(&self) -> usize;
519 impl<'a> DecoderWithPosition for MemDecoder<'a> {
520 fn position(&self) -> usize {
525 impl<'a, 'tcx> DecoderWithPosition for CacheDecoder<'a, 'tcx> {
526 fn position(&self) -> usize {
527 self.opaque.position()
531 // Decodes something that was encoded with `encode_tagged()` and verify that the
532 // tag matches and the correct amount of bytes was read.
533 fn decode_tagged<D, T, V>(decoder: &mut D, expected_tag: T) -> V
535 T: Decodable<D> + Eq + std::fmt::Debug,
537 D: DecoderWithPosition,
539 let start_pos = decoder.position();
541 let actual_tag = T::decode(decoder);
542 assert_eq!(actual_tag, expected_tag);
543 let value = V::decode(decoder);
544 let end_pos = decoder.position();
546 let expected_len: u64 = Decodable::decode(decoder);
547 assert_eq!((end_pos - start_pos) as u64, expected_len);
552 impl<'a, 'tcx> TyDecoder for CacheDecoder<'a, 'tcx> {
553 type I = TyCtxt<'tcx>;
554 const CLEAR_CROSS_CRATE: bool = false;
557 fn interner(&self) -> TyCtxt<'tcx> {
562 fn position(&self) -> usize {
563 self.opaque.position()
567 fn peek_byte(&self) -> u8 {
568 self.opaque.data[self.opaque.position()]
571 fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx>
573 F: FnOnce(&mut Self) -> Ty<'tcx>,
577 let cache_key = ty::CReaderCacheKey { cnum: None, pos: shorthand };
579 if let Some(&ty) = tcx.ty_rcache.borrow().get(&cache_key) {
583 let ty = or_insert_with(self);
584 // This may overwrite the entry, but it should overwrite with the same value.
585 tcx.ty_rcache.borrow_mut().insert_same(cache_key, ty);
589 fn with_position<F, R>(&mut self, pos: usize, f: F) -> R
591 F: FnOnce(&mut Self) -> R,
593 debug_assert!(pos < self.opaque.data.len());
595 let new_opaque = MemDecoder::new(self.opaque.data, pos);
596 let old_opaque = mem::replace(&mut self.opaque, new_opaque);
598 self.opaque = old_opaque;
602 fn decode_alloc_id(&mut self) -> interpret::AllocId {
603 let alloc_decoding_session = self.alloc_decoding_session;
604 alloc_decoding_session.decode_alloc_id(self)
608 rustc_middle::implement_ty_decoder!(CacheDecoder<'a, 'tcx>);
610 // This ensures that the `Decodable<opaque::Decoder>::decode` specialization for `Vec<u8>` is used
611 // when a `CacheDecoder` is passed to `Decodable::decode`. Unfortunately, we have to manually opt
612 // into specializations this way, given how `CacheDecoder` and the decoding traits currently work.
613 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Vec<u8> {
614 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
615 Decodable::decode(&mut d.opaque)
619 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for SyntaxContext {
620 fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Self {
621 let syntax_contexts = decoder.syntax_contexts;
622 rustc_span::hygiene::decode_syntax_context(decoder, decoder.hygiene_context, |this, id| {
623 // This closure is invoked if we haven't already decoded the data for the `SyntaxContext` we are deserializing.
624 // We look up the position of the associated `SyntaxData` and decode it.
625 let pos = syntax_contexts.get(&id).unwrap();
626 this.with_position(pos.to_usize(), |decoder| {
627 let data: SyntaxContextData = decode_tagged(decoder, TAG_SYNTAX_CONTEXT);
634 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for ExpnId {
635 fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Self {
636 let hash = ExpnHash::decode(decoder);
638 return ExpnId::root();
641 if let Some(expn_id) = ExpnId::from_hash(hash) {
645 let krate = decoder.tcx.stable_crate_id_to_crate_num(hash.stable_crate_id());
647 let expn_id = if krate == LOCAL_CRATE {
648 // We look up the position of the associated `ExpnData` and decode it.
652 .unwrap_or_else(|| panic!("Bad hash {:?} (map {:?})", hash, decoder.expn_data));
654 let data: ExpnData = decoder
655 .with_position(pos.to_usize(), |decoder| decode_tagged(decoder, TAG_EXPN_DATA));
656 let expn_id = rustc_span::hygiene::register_local_expn_id(data, hash);
658 #[cfg(debug_assertions)]
660 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
661 let local_hash: u64 = decoder.tcx.with_stable_hashing_context(|mut hcx| {
662 let mut hasher = StableHasher::new();
663 expn_id.expn_data().hash_stable(&mut hcx, &mut hasher);
666 debug_assert_eq!(hash.local_hash(), local_hash);
671 let index_guess = decoder.foreign_expn_data[&hash];
672 decoder.tcx.cstore_untracked().expn_hash_to_expn_id(
680 debug_assert_eq!(expn_id.krate, krate);
685 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Span {
686 fn decode(decoder: &mut CacheDecoder<'a, 'tcx>) -> Self {
687 let ctxt = SyntaxContext::decode(decoder);
688 let parent = Option::<LocalDefId>::decode(decoder);
689 let tag: u8 = Decodable::decode(decoder);
691 if tag == TAG_PARTIAL_SPAN {
692 return Span::new(BytePos(0), BytePos(0), ctxt, parent);
693 } else if tag == TAG_RELATIVE_SPAN {
694 let dlo = u32::decode(decoder);
695 let dto = u32::decode(decoder);
697 let enclosing = decoder.tcx.source_span_untracked(parent.unwrap()).data_untracked();
698 let span = Span::new(
699 enclosing.lo + BytePos::from_u32(dlo),
700 enclosing.lo + BytePos::from_u32(dto),
707 debug_assert_eq!(tag, TAG_FULL_SPAN);
710 let file_lo_index = SourceFileIndex::decode(decoder);
711 let line_lo = usize::decode(decoder);
712 let col_lo = BytePos::decode(decoder);
713 let len = BytePos::decode(decoder);
715 let file_lo = decoder.file_index_to_file(file_lo_index);
716 let lo = file_lo.lines(|lines| lines[line_lo - 1] + col_lo);
719 Span::new(lo, hi, ctxt, parent)
723 // copy&paste impl from rustc_metadata
724 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for Symbol {
725 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
726 let tag = d.read_u8();
730 let s = d.read_str();
735 let pos = d.read_usize();
736 let old_pos = d.opaque.position();
738 // move to str ofset and read
739 d.opaque.set_position(pos);
740 let s = d.read_str();
741 let sym = Symbol::intern(s);
744 d.opaque.set_position(old_pos);
753 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for CrateNum {
754 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
755 let stable_id = StableCrateId::decode(d);
756 let cnum = d.tcx.stable_crate_id_to_crate_num(stable_id);
761 // This impl makes sure that we get a runtime error when we try decode a
762 // `DefIndex` that is not contained in a `DefId`. Such a case would be problematic
763 // because we would not know how to transform the `DefIndex` to the current
765 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for DefIndex {
766 fn decode(_d: &mut CacheDecoder<'a, 'tcx>) -> DefIndex {
767 panic!("trying to decode `DefIndex` outside the context of a `DefId`")
771 // Both the `CrateNum` and the `DefIndex` of a `DefId` can change in between two
772 // compilation sessions. We use the `DefPathHash`, which is stable across
773 // sessions, to map the old `DefId` to the new one.
774 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for DefId {
775 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
776 // Load the `DefPathHash` which is was we encoded the `DefId` as.
777 let def_path_hash = DefPathHash::decode(d);
779 // Using the `DefPathHash`, we can lookup the new `DefId`.
780 // Subtle: We only encode a `DefId` as part of a query result.
781 // If we get to this point, then all of the query inputs were green,
782 // which means that the definition with this hash is guaranteed to
783 // still exist in the current compilation session.
784 d.tcx.def_path_hash_to_def_id(def_path_hash, &mut || {
785 panic!("Failed to convert DefPathHash {:?}", def_path_hash)
790 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx FxHashSet<LocalDefId> {
791 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
792 RefDecodable::decode(d)
796 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>>
797 for &'tcx IndexVec<mir::Promoted, mir::Body<'tcx>>
799 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
800 RefDecodable::decode(d)
804 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [ty::abstract_const::Node<'tcx>] {
805 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
806 RefDecodable::decode(d)
810 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
811 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
812 RefDecodable::decode(d)
816 impl<'a, 'tcx> Decodable<CacheDecoder<'a, 'tcx>> for &'tcx [rustc_ast::InlineAsmTemplatePiece] {
817 fn decode(d: &mut CacheDecoder<'a, 'tcx>) -> Self {
818 RefDecodable::decode(d)
822 macro_rules! impl_ref_decoder {
823 (<$tcx:tt> $($ty:ty,)*) => {
824 $(impl<'a, $tcx> Decodable<CacheDecoder<'a, $tcx>> for &$tcx [$ty] {
825 fn decode(d: &mut CacheDecoder<'a, $tcx>) -> Self {
826 RefDecodable::decode(d)
832 impl_ref_decoder! {<'tcx>
834 rustc_ast::Attribute,
835 rustc_span::symbol::Ident,
837 rustc_span::def_id::DefId,
838 rustc_span::def_id::LocalDefId,
839 (rustc_middle::middle::exported_symbols::ExportedSymbol<'tcx>, rustc_middle::middle::exported_symbols::SymbolExportInfo),
842 //- ENCODING -------------------------------------------------------------------
844 /// An encoder that can write to the incremental compilation cache.
845 pub struct CacheEncoder<'a, 'tcx> {
847 encoder: FileEncoder,
848 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
849 predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
850 interpret_allocs: FxIndexSet<interpret::AllocId>,
851 source_map: CachingSourceMapView<'tcx>,
852 file_to_file_index: FxHashMap<*const SourceFile, SourceFileIndex>,
853 hygiene_context: &'a HygieneEncodeContext,
854 symbol_table: FxHashMap<Symbol, usize>,
857 impl<'a, 'tcx> CacheEncoder<'a, 'tcx> {
858 fn source_file_index(&mut self, source_file: Lrc<SourceFile>) -> SourceFileIndex {
859 self.file_to_file_index[&(&*source_file as *const SourceFile)]
862 /// Encode something with additional information that allows to do some
863 /// sanity checks when decoding the data again. This method will first
864 /// encode the specified tag, then the given value, then the number of
865 /// bytes taken up by tag and value. On decoding, we can then verify that
866 /// we get the expected tag and read the expected number of bytes.
867 fn encode_tagged<T: Encodable<Self>, V: Encodable<Self>>(&mut self, tag: T, value: &V) {
868 let start_pos = self.position();
873 let end_pos = self.position();
874 ((end_pos - start_pos) as u64).encode(self);
877 fn finish(self) -> Result<usize, io::Error> {
878 self.encoder.finish()
882 impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx>> for SyntaxContext {
883 fn encode(&self, s: &mut CacheEncoder<'a, 'tcx>) {
884 rustc_span::hygiene::raw_encode_syntax_context(*self, s.hygiene_context, s);
888 impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx>> for ExpnId {
889 fn encode(&self, s: &mut CacheEncoder<'a, 'tcx>) {
890 s.hygiene_context.schedule_expn_data_for_encoding(*self);
891 self.expn_hash().encode(s);
895 impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx>> for Span {
896 fn encode(&self, s: &mut CacheEncoder<'a, 'tcx>) {
897 let span_data = self.data_untracked();
898 span_data.ctxt.encode(s);
899 span_data.parent.encode(s);
901 if span_data.is_dummy() {
902 return TAG_PARTIAL_SPAN.encode(s);
905 if let Some(parent) = span_data.parent {
906 let enclosing = s.tcx.source_span(parent).data_untracked();
907 if enclosing.contains(span_data) {
908 TAG_RELATIVE_SPAN.encode(s);
909 (span_data.lo - enclosing.lo).to_u32().encode(s);
910 (span_data.hi - enclosing.lo).to_u32().encode(s);
915 let pos = s.source_map.byte_pos_to_line_and_col(span_data.lo);
916 let partial_span = match &pos {
917 Some((file_lo, _, _)) => !file_lo.contains(span_data.hi),
922 return TAG_PARTIAL_SPAN.encode(s);
925 let (file_lo, line_lo, col_lo) = pos.unwrap();
927 let len = span_data.hi - span_data.lo;
929 let source_file_index = s.source_file_index(file_lo);
931 TAG_FULL_SPAN.encode(s);
932 source_file_index.encode(s);
939 // copy&paste impl from rustc_metadata
940 impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx>> for Symbol {
941 fn encode(&self, s: &mut CacheEncoder<'a, 'tcx>) {
942 match s.symbol_table.entry(*self) {
943 Entry::Vacant(o) => {
944 s.encoder.emit_u8(SYMBOL_STR);
945 let pos = s.encoder.position();
947 s.emit_str(self.as_str());
949 Entry::Occupied(o) => {
950 let x = o.get().clone();
951 s.emit_u8(SYMBOL_OFFSET);
958 impl<'a, 'tcx> TyEncoder for CacheEncoder<'a, 'tcx> {
959 type I = TyCtxt<'tcx>;
960 const CLEAR_CROSS_CRATE: bool = false;
962 fn position(&self) -> usize {
963 self.encoder.position()
965 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
966 &mut self.type_shorthands
968 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
969 &mut self.predicate_shorthands
971 fn encode_alloc_id(&mut self, alloc_id: &interpret::AllocId) {
972 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
978 impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx>> for CrateNum {
979 fn encode(&self, s: &mut CacheEncoder<'a, 'tcx>) {
980 s.tcx.stable_crate_id(*self).encode(s);
984 impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx>> for DefId {
985 fn encode(&self, s: &mut CacheEncoder<'a, 'tcx>) {
986 s.tcx.def_path_hash(*self).encode(s);
990 impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx>> for DefIndex {
991 fn encode(&self, _: &mut CacheEncoder<'a, 'tcx>) {
992 bug!("encoding `DefIndex` without context");
996 macro_rules! encoder_methods {
997 ($($name:ident($ty:ty);)*) => {
999 $(fn $name(&mut self, value: $ty) {
1000 self.encoder.$name(value)
1005 impl<'a, 'tcx> Encoder for CacheEncoder<'a, 'tcx> {
1026 emit_raw_bytes(&[u8]);
1030 // This ensures that the `Encodable<opaque::FileEncoder>::encode` specialization for byte slices
1031 // is used when a `CacheEncoder` having an `opaque::FileEncoder` is passed to `Encodable::encode`.
1032 // Unfortunately, we have to manually opt into specializations this way, given how `CacheEncoder`
1033 // and the encoding traits currently work.
1034 impl<'a, 'tcx> Encodable<CacheEncoder<'a, 'tcx>> for [u8] {
1035 fn encode(&self, e: &mut CacheEncoder<'a, 'tcx>) {
1036 self.encode(&mut e.encoder);
1040 pub fn encode_query_results<'a, 'tcx, CTX, Q>(
1042 encoder: &mut CacheEncoder<'a, 'tcx>,
1043 query_result_index: &mut EncodedDepNodeIndex,
1045 CTX: QueryContext + 'tcx,
1046 Q: super::QueryDescription<CTX>,
1047 Q::Value: Encodable<CacheEncoder<'a, 'tcx>>,
1052 .extra_verbose_generic_activity("encode_query_results_for", std::any::type_name::<Q>());
1054 assert!(Q::query_state(tcx).all_inactive());
1055 let cache = Q::query_cache(tcx);
1056 cache.iter(&mut |key, value, dep_node| {
1057 if Q::cache_on_disk(*tcx.dep_context(), &key) {
1058 let dep_node = SerializedDepNodeIndex::new(dep_node.index());
1060 // Record position of the cache entry.
1061 query_result_index.push((dep_node, AbsoluteBytePos::new(encoder.encoder.position())));
1063 // Encode the type check tables with the `SerializedDepNodeIndex`
1065 encoder.encode_tagged(dep_node, value);