]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/encoder.rs
Remove mir encode calls that didn't actually encode anything
[rust.git] / compiler / rustc_metadata / src / rmeta / encoder.rs
1 use crate::rmeta::table::{FixedSizeEncoding, TableBuilder};
2 use crate::rmeta::*;
3
4 use rustc_ast as ast;
5 use rustc_data_structures::fingerprint::{Fingerprint, FingerprintEncoder};
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
7 use rustc_data_structures::stable_hasher::StableHasher;
8 use rustc_data_structures::sync::{join, Lrc};
9 use rustc_hir as hir;
10 use rustc_hir::def::CtorKind;
11 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
12 use rustc_hir::definitions::DefPathData;
13 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
14 use rustc_hir::itemlikevisit::{ItemLikeVisitor, ParItemLikeVisitor};
15 use rustc_hir::lang_items;
16 use rustc_hir::{AnonConst, GenericParamKind};
17 use rustc_index::bit_set::GrowableBitSet;
18 use rustc_index::vec::Idx;
19 use rustc_middle::hir::map::Map;
20 use rustc_middle::middle::cstore::{EncodedMetadata, ForeignModule, LinkagePreference, NativeLib};
21 use rustc_middle::middle::dependency_format::Linkage;
22 use rustc_middle::middle::exported_symbols::{
23     metadata_symbol_name, ExportedSymbol, SymbolExportLevel,
24 };
25 use rustc_middle::mir::interpret;
26 use rustc_middle::traits::specialization_graph;
27 use rustc_middle::ty::codec::TyEncoder;
28 use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
29 use rustc_serialize::{opaque, Encodable, Encoder};
30 use rustc_session::config::CrateType;
31 use rustc_span::hygiene::{ExpnDataEncodeMode, HygieneEncodeContext, MacroKind};
32 use rustc_span::symbol::{sym, Ident, Symbol};
33 use rustc_span::{self, ExternalSource, FileName, SourceFile, Span, SyntaxContext};
34 use rustc_target::abi::VariantIdx;
35 use std::hash::Hash;
36 use std::num::NonZeroUsize;
37 use std::path::Path;
38 use tracing::{debug, trace};
39
40 pub(super) struct EncodeContext<'a, 'tcx> {
41     opaque: opaque::Encoder,
42     tcx: TyCtxt<'tcx>,
43     feat: &'tcx rustc_feature::Features,
44
45     tables: TableBuilders<'tcx>,
46
47     lazy_state: LazyState,
48     type_shorthands: FxHashMap<Ty<'tcx>, usize>,
49     predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
50
51     interpret_allocs: FxIndexSet<interpret::AllocId>,
52
53     // This is used to speed up Span encoding.
54     // The `usize` is an index into the `MonotonicVec`
55     // that stores the `SourceFile`
56     source_file_cache: (Lrc<SourceFile>, usize),
57     // The indices (into the `SourceMap`'s `MonotonicVec`)
58     // of all of the `SourceFiles` that we need to serialize.
59     // When we serialize a `Span`, we insert the index of its
60     // `SourceFile` into the `GrowableBitSet`.
61     //
62     // This needs to be a `GrowableBitSet` and not a
63     // regular `BitSet` because we may actually import new `SourceFiles`
64     // during metadata encoding, due to executing a query
65     // with a result containing a foreign `Span`.
66     required_source_files: Option<GrowableBitSet<usize>>,
67     is_proc_macro: bool,
68     hygiene_ctxt: &'a HygieneEncodeContext,
69 }
70
71 /// If the current crate is a proc-macro, returns early with `Lazy:empty()`.
72 /// This is useful for skipping the encoding of things that aren't needed
73 /// for proc-macro crates.
74 macro_rules! empty_proc_macro {
75     ($self:ident) => {
76         if $self.is_proc_macro {
77             return Lazy::empty();
78         }
79     };
80 }
81
82 macro_rules! encoder_methods {
83     ($($name:ident($ty:ty);)*) => {
84         $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
85             self.opaque.$name(value)
86         })*
87     }
88 }
89
90 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
91     type Error = <opaque::Encoder as Encoder>::Error;
92
93     #[inline]
94     fn emit_unit(&mut self) -> Result<(), Self::Error> {
95         Ok(())
96     }
97
98     encoder_methods! {
99         emit_usize(usize);
100         emit_u128(u128);
101         emit_u64(u64);
102         emit_u32(u32);
103         emit_u16(u16);
104         emit_u8(u8);
105
106         emit_isize(isize);
107         emit_i128(i128);
108         emit_i64(i64);
109         emit_i32(i32);
110         emit_i16(i16);
111         emit_i8(i8);
112
113         emit_bool(bool);
114         emit_f64(f64);
115         emit_f32(f32);
116         emit_char(char);
117         emit_str(&str);
118     }
119 }
120
121 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
122     for Lazy<T>
123 {
124     fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
125         e.emit_lazy_distance(*self)
126     }
127 }
128
129 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
130     for Lazy<[T]>
131 {
132     fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
133         e.emit_usize(self.meta)?;
134         if self.meta == 0 {
135             return Ok(());
136         }
137         e.emit_lazy_distance(*self)
138     }
139 }
140
141 impl<'a, 'tcx, I: Idx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
142     for Lazy<Table<I, T>>
143 where
144     Option<T>: FixedSizeEncoding,
145 {
146     fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
147         e.emit_usize(self.meta)?;
148         e.emit_lazy_distance(*self)
149     }
150 }
151
152 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum {
153     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
154         if *self != LOCAL_CRATE && s.is_proc_macro {
155             panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self);
156         }
157         s.emit_u32(self.as_u32())
158     }
159 }
160
161 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex {
162     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
163         s.emit_u32(self.as_u32())
164     }
165 }
166
167 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
168     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
169         rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s)
170     }
171 }
172
173 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
174     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
175         rustc_span::hygiene::raw_encode_expn_id(
176             *self,
177             &s.hygiene_ctxt,
178             ExpnDataEncodeMode::Metadata,
179             s,
180         )
181     }
182 }
183
184 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
185     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
186         if *self == rustc_span::DUMMY_SP {
187             return TAG_INVALID_SPAN.encode(s);
188         }
189
190         let span = self.data();
191
192         // The Span infrastructure should make sure that this invariant holds:
193         debug_assert!(span.lo <= span.hi);
194
195         if !s.source_file_cache.0.contains(span.lo) {
196             let source_map = s.tcx.sess.source_map();
197             let source_file_index = source_map.lookup_source_file_idx(span.lo);
198             s.source_file_cache =
199                 (source_map.files()[source_file_index].clone(), source_file_index);
200         }
201
202         if !s.source_file_cache.0.contains(span.hi) {
203             // Unfortunately, macro expansion still sometimes generates Spans
204             // that malformed in this way.
205             return TAG_INVALID_SPAN.encode(s);
206         }
207
208         let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!");
209         // Record the fact that we need to encode the data for this `SourceFile`
210         source_files.insert(s.source_file_cache.1);
211
212         // There are two possible cases here:
213         // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
214         // crate we are writing metadata for. When the metadata for *this* crate gets
215         // deserialized, the deserializer will need to know which crate it originally came
216         // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
217         // be deserialized after the rest of the span data, which tells the deserializer
218         // which crate contains the source map information.
219         // 2. This span comes from our own crate. No special hamdling is needed - we just
220         // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
221         // our own source map information.
222         //
223         // If we're a proc-macro crate, we always treat this as a local `Span`.
224         // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
225         // if we're a proc-macro crate.
226         // This allows us to avoid loading the dependencies of proc-macro crates: all of
227         // the information we need to decode `Span`s is stored in the proc-macro crate.
228         let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro {
229             // To simplify deserialization, we 'rebase' this span onto the crate it originally came from
230             // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values
231             // are relative to the source map information for the 'foreign' crate whose CrateNum
232             // we write into the metadata. This allows `imported_source_files` to binary
233             // search through the 'foreign' crate's source map information, using the
234             // deserialized 'lo' and 'hi' values directly.
235             //
236             // All of this logic ensures that the final result of deserialization is a 'normal'
237             // Span that can be used without any additional trouble.
238             let external_start_pos = {
239                 // Introduce a new scope so that we drop the 'lock()' temporary
240                 match &*s.source_file_cache.0.external_src.lock() {
241                     ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos,
242                     src => panic!("Unexpected external source {:?}", src),
243                 }
244             };
245             let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos;
246             let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos;
247
248             (TAG_VALID_SPAN_FOREIGN, lo, hi)
249         } else {
250             (TAG_VALID_SPAN_LOCAL, span.lo, span.hi)
251         };
252
253         tag.encode(s)?;
254         lo.encode(s)?;
255
256         // Encode length which is usually less than span.hi and profits more
257         // from the variable-length integer encoding that we use.
258         let len = hi - lo;
259         len.encode(s)?;
260
261         // Don't serialize any `SyntaxContext`s from a proc-macro crate,
262         // since we don't load proc-macro dependencies during serialization.
263         // This means that any hygiene information from macros used *within*
264         // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
265         // definition) will be lost.
266         //
267         // This can show up in two ways:
268         //
269         // 1. Any hygiene information associated with identifier of
270         // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
271         // Since proc-macros can only be invoked from a different crate,
272         // real code should never need to care about this.
273         //
274         // 2. Using `Span::def_site` or `Span::mixed_site` will not
275         // include any hygiene information associated with the definition
276         // site. This means that a proc-macro cannot emit a `$crate`
277         // identifier which resolves to one of its dependencies,
278         // which also should never come up in practice.
279         //
280         // Additionally, this affects `Span::parent`, and any other
281         // span inspection APIs that would otherwise allow traversing
282         // the `SyntaxContexts` associated with a span.
283         //
284         // None of these user-visible effects should result in any
285         // cross-crate inconsistencies (getting one behavior in the same
286         // crate, and a different behavior in another crate) due to the
287         // limited surface that proc-macros can expose.
288         //
289         // IMPORTANT: If this is ever changed, be sure to update
290         // `rustc_span::hygiene::raw_encode_expn_id` to handle
291         // encoding `ExpnData` for proc-macro crates.
292         if s.is_proc_macro {
293             SyntaxContext::root().encode(s)?;
294         } else {
295             span.ctxt.encode(s)?;
296         }
297
298         if tag == TAG_VALID_SPAN_FOREIGN {
299             // This needs to be two lines to avoid holding the `s.source_file_cache`
300             // while calling `cnum.encode(s)`
301             let cnum = s.source_file_cache.0.cnum;
302             cnum.encode(s)?;
303         }
304
305         Ok(())
306     }
307 }
308
309 impl<'a, 'tcx> FingerprintEncoder for EncodeContext<'a, 'tcx> {
310     fn encode_fingerprint(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
311         f.encode_opaque(&mut self.opaque)
312     }
313 }
314
315 impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
316     const CLEAR_CROSS_CRATE: bool = true;
317
318     fn position(&self) -> usize {
319         self.opaque.position()
320     }
321
322     fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
323         &mut self.type_shorthands
324     }
325
326     fn predicate_shorthands(&mut self) -> &mut FxHashMap<rustc_middle::ty::Predicate<'tcx>, usize> {
327         &mut self.predicate_shorthands
328     }
329
330     fn encode_alloc_id(
331         &mut self,
332         alloc_id: &rustc_middle::mir::interpret::AllocId,
333     ) -> Result<(), Self::Error> {
334         let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
335
336         index.encode(self)
337     }
338 }
339
340 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [mir::abstract_const::Node<'tcx>] {
341     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
342         (**self).encode(s)
343     }
344 }
345
346 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
347     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
348         (**self).encode(s)
349     }
350 }
351
352 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
353 trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> {
354     fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta;
355 }
356
357 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for &T {
358     fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
359         self.encode(ecx).unwrap()
360     }
361 }
362
363 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for T {
364     fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
365         self.encode(ecx).unwrap()
366     }
367 }
368
369 impl<'a, 'tcx, I, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, [T]> for I
370 where
371     I: IntoIterator,
372     I::Item: EncodeContentsForLazy<'a, 'tcx, T>,
373 {
374     fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize {
375         self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
376     }
377 }
378
379 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would
380 // normally need extra variables to avoid errors about multiple mutable borrows.
381 macro_rules! record {
382     ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
383         {
384             let value = $value;
385             let lazy = $self.lazy(value);
386             $self.$tables.$table.set($def_id.index, lazy);
387         }
388     }};
389 }
390
391 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
392     fn emit_lazy_distance<T: ?Sized + LazyMeta>(
393         &mut self,
394         lazy: Lazy<T>,
395     ) -> Result<(), <Self as Encoder>::Error> {
396         let min_end = lazy.position.get() + T::min_size(lazy.meta);
397         let distance = match self.lazy_state {
398             LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
399             LazyState::NodeStart(start) => {
400                 let start = start.get();
401                 assert!(min_end <= start);
402                 start - min_end
403             }
404             LazyState::Previous(last_min_end) => {
405                 assert!(
406                     last_min_end <= lazy.position,
407                     "make sure that the calls to `lazy*` \
408                      are in the same order as the metadata fields",
409                 );
410                 lazy.position.get() - last_min_end.get()
411             }
412         };
413         self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap());
414         self.emit_usize(distance)
415     }
416
417     fn lazy<T: ?Sized + LazyMeta>(
418         &mut self,
419         value: impl EncodeContentsForLazy<'a, 'tcx, T>,
420     ) -> Lazy<T> {
421         let pos = NonZeroUsize::new(self.position()).unwrap();
422
423         assert_eq!(self.lazy_state, LazyState::NoNode);
424         self.lazy_state = LazyState::NodeStart(pos);
425         let meta = value.encode_contents_for_lazy(self);
426         self.lazy_state = LazyState::NoNode;
427
428         assert!(pos.get() + <T>::min_size(meta) <= self.position());
429
430         Lazy::from_position_and_meta(pos, meta)
431     }
432
433     fn encode_info_for_items(&mut self) {
434         let krate = self.tcx.hir().krate();
435         self.encode_info_for_mod(hir::CRATE_HIR_ID, &krate.item.module, &krate.item.attrs);
436
437         // Proc-macro crates only export proc-macro items, which are looked
438         // up using `proc_macro_data`
439         if self.is_proc_macro {
440             return;
441         }
442
443         krate.visit_all_item_likes(&mut self.as_deep_visitor());
444         for macro_def in krate.exported_macros {
445             self.visit_macro_def(macro_def);
446         }
447     }
448
449     fn encode_def_path_table(&mut self) {
450         let table = self.tcx.hir().definitions().def_path_table();
451         if self.is_proc_macro {
452             for def_index in std::iter::once(CRATE_DEF_INDEX)
453                 .chain(self.tcx.hir().krate().proc_macros.iter().map(|p| p.owner.local_def_index))
454             {
455                 let def_key = self.lazy(table.def_key(def_index));
456                 let def_path_hash = self.lazy(table.def_path_hash(def_index));
457                 self.tables.def_keys.set(def_index, def_key);
458                 self.tables.def_path_hashes.set(def_index, def_path_hash);
459             }
460         } else {
461             for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
462                 let def_key = self.lazy(def_key);
463                 let def_path_hash = self.lazy(def_path_hash);
464                 self.tables.def_keys.set(def_index, def_key);
465                 self.tables.def_path_hashes.set(def_index, def_path_hash);
466             }
467         }
468     }
469
470     fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> {
471         let source_map = self.tcx.sess.source_map();
472         let all_source_files = source_map.files();
473
474         let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
475         // By replacing the `Option` with `None`, we ensure that we can't
476         // accidentally serialize any more `Span`s after the source map encoding
477         // is done.
478         let required_source_files = self.required_source_files.take().unwrap();
479
480         let adapted = all_source_files
481             .iter()
482             .enumerate()
483             .filter(|(idx, source_file)| {
484                 // Only serialize `SourceFile`s that were used
485                 // during the encoding of a `Span`
486                 required_source_files.contains(*idx) &&
487                 // Don't serialize imported `SourceFile`s, unless
488                 // we're in a proc-macro crate.
489                 (!source_file.is_imported() || self.is_proc_macro)
490             })
491             .map(|(_, source_file)| {
492                 let mut adapted = match source_file.name {
493                     // This path of this SourceFile has been modified by
494                     // path-remapping, so we use it verbatim (and avoid
495                     // cloning the whole map in the process).
496                     _ if source_file.name_was_remapped => source_file.clone(),
497
498                     // Otherwise expand all paths to absolute paths because
499                     // any relative paths are potentially relative to a
500                     // wrong directory.
501                     FileName::Real(ref name) => {
502                         let name = name.stable_name();
503                         let mut adapted = (**source_file).clone();
504                         adapted.name = Path::new(&working_dir).join(name).into();
505                         adapted.name_hash = {
506                             let mut hasher: StableHasher = StableHasher::new();
507                             adapted.name.hash(&mut hasher);
508                             hasher.finish::<u128>()
509                         };
510                         Lrc::new(adapted)
511                     }
512
513                     // expanded code, not from a file
514                     _ => source_file.clone(),
515                 };
516
517                 // We're serializing this `SourceFile` into our crate metadata,
518                 // so mark it as coming from this crate.
519                 // This also ensures that we don't try to deserialize the
520                 // `CrateNum` for a proc-macro dependency - since proc macro
521                 // dependencies aren't loaded when we deserialize a proc-macro,
522                 // trying to remap the `CrateNum` would fail.
523                 if self.is_proc_macro {
524                     Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE;
525                 }
526                 adapted
527             })
528             .collect::<Vec<_>>();
529
530         self.lazy(adapted.iter().map(|rc| &**rc))
531     }
532
533     fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
534         let mut i = self.position();
535
536         // Encode the crate deps
537         let crate_deps = self.encode_crate_deps();
538         let dylib_dependency_formats = self.encode_dylib_dependency_formats();
539         let dep_bytes = self.position() - i;
540
541         // Encode the lib features.
542         i = self.position();
543         let lib_features = self.encode_lib_features();
544         let lib_feature_bytes = self.position() - i;
545
546         // Encode the language items.
547         i = self.position();
548         let lang_items = self.encode_lang_items();
549         let lang_items_missing = self.encode_lang_items_missing();
550         let lang_item_bytes = self.position() - i;
551
552         // Encode the diagnostic items.
553         i = self.position();
554         let diagnostic_items = self.encode_diagnostic_items();
555         let diagnostic_item_bytes = self.position() - i;
556
557         // Encode the native libraries used
558         i = self.position();
559         let native_libraries = self.encode_native_libraries();
560         let native_lib_bytes = self.position() - i;
561
562         let foreign_modules = self.encode_foreign_modules();
563
564         // Encode DefPathTable
565         i = self.position();
566         self.encode_def_path_table();
567         let def_path_table_bytes = self.position() - i;
568
569         // Encode the def IDs of impls, for coherence checking.
570         i = self.position();
571         let impls = self.encode_impls();
572         let impl_bytes = self.position() - i;
573
574         let tcx = self.tcx;
575
576         // Encode the items.
577         i = self.position();
578         self.encode_info_for_items();
579         let item_bytes = self.position() - i;
580
581         // Encode the allocation index
582         let interpret_alloc_index = {
583             let mut interpret_alloc_index = Vec::new();
584             let mut n = 0;
585             trace!("beginning to encode alloc ids");
586             loop {
587                 let new_n = self.interpret_allocs.len();
588                 // if we have found new ids, serialize those, too
589                 if n == new_n {
590                     // otherwise, abort
591                     break;
592                 }
593                 trace!("encoding {} further alloc ids", new_n - n);
594                 for idx in n..new_n {
595                     let id = self.interpret_allocs[idx];
596                     let pos = self.position() as u32;
597                     interpret_alloc_index.push(pos);
598                     interpret::specialized_encode_alloc_id(self, tcx, id).unwrap();
599                 }
600                 n = new_n;
601             }
602             self.lazy(interpret_alloc_index)
603         };
604
605         // Encode the proc macro data. This affects 'tables',
606         // so we need to do this before we encode the tables
607         i = self.position();
608         let proc_macro_data = self.encode_proc_macros();
609         let proc_macro_data_bytes = self.position() - i;
610
611         i = self.position();
612         let tables = self.tables.encode(&mut self.opaque);
613         let tables_bytes = self.position() - i;
614
615         // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
616         // this as late as possible to give the prefetching as much time as possible to complete.
617         i = self.position();
618         let exported_symbols = tcx.exported_symbols(LOCAL_CRATE);
619         let exported_symbols = self.encode_exported_symbols(&exported_symbols);
620         let exported_symbols_bytes = self.position() - i;
621
622         // Encode the hygiene data,
623         // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process
624         // of encoding other items (e.g. `optimized_mir`) may cause us to load
625         // data from the incremental cache. If this causes us to deserialize a `Span`,
626         // then we may load additional `SyntaxContext`s into the global `HygieneData`.
627         // Therefore, we need to encode the hygiene data last to ensure that we encode
628         // any `SyntaxContext`s that might be used.
629         i = self.position();
630         let (syntax_contexts, expn_data) = self.encode_hygiene();
631         let hygiene_bytes = self.position() - i;
632
633         // Encode source_map. This needs to be done last,
634         // since encoding `Span`s tells us which `SourceFiles` we actually
635         // need to encode.
636         i = self.position();
637         let source_map = self.encode_source_map();
638         let source_map_bytes = self.position() - i;
639
640         let attrs = tcx.hir().krate_attrs();
641         let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator);
642
643         let root = self.lazy(CrateRoot {
644             name: tcx.crate_name(LOCAL_CRATE),
645             extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
646             triple: tcx.sess.opts.target_triple.clone(),
647             hash: tcx.crate_hash(LOCAL_CRATE),
648             disambiguator: tcx.sess.local_crate_disambiguator(),
649             panic_strategy: tcx.sess.panic_strategy(),
650             edition: tcx.sess.edition(),
651             has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
652             has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
653             has_default_lib_allocator,
654             plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
655             proc_macro_data,
656             compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
657             needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
658             needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
659             no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
660             panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
661             profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
662             symbol_mangling_version: tcx.sess.opts.debugging_opts.get_symbol_mangling_version(),
663
664             crate_deps,
665             dylib_dependency_formats,
666             lib_features,
667             lang_items,
668             diagnostic_items,
669             lang_items_missing,
670             native_libraries,
671             foreign_modules,
672             source_map,
673             impls,
674             exported_symbols,
675             interpret_alloc_index,
676             tables,
677             syntax_contexts,
678             expn_data,
679         });
680
681         let total_bytes = self.position();
682
683         if tcx.sess.meta_stats() {
684             let mut zero_bytes = 0;
685             for e in self.opaque.data.iter() {
686                 if *e == 0 {
687                     zero_bytes += 1;
688                 }
689             }
690
691             println!("metadata stats:");
692             println!("             dep bytes: {}", dep_bytes);
693             println!("     lib feature bytes: {}", lib_feature_bytes);
694             println!("       lang item bytes: {}", lang_item_bytes);
695             println!(" diagnostic item bytes: {}", diagnostic_item_bytes);
696             println!("          native bytes: {}", native_lib_bytes);
697             println!("      source_map bytes: {}", source_map_bytes);
698             println!("            impl bytes: {}", impl_bytes);
699             println!("    exp. symbols bytes: {}", exported_symbols_bytes);
700             println!("  def-path table bytes: {}", def_path_table_bytes);
701             println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
702             println!("            item bytes: {}", item_bytes);
703             println!("           table bytes: {}", tables_bytes);
704             println!("         hygiene bytes: {}", hygiene_bytes);
705             println!("            zero bytes: {}", zero_bytes);
706             println!("           total bytes: {}", total_bytes);
707         }
708
709         root
710     }
711 }
712
713 impl EncodeContext<'a, 'tcx> {
714     fn encode_variances_of(&mut self, def_id: DefId) {
715         debug!("EncodeContext::encode_variances_of({:?})", def_id);
716         record!(self.tables.variances[def_id] <- &self.tcx.variances_of(def_id)[..]);
717     }
718
719     fn encode_item_type(&mut self, def_id: DefId) {
720         debug!("EncodeContext::encode_item_type({:?})", def_id);
721         record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id));
722     }
723
724     fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) {
725         let tcx = self.tcx;
726         let variant = &def.variants[index];
727         let def_id = variant.def_id;
728         debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
729
730         let data = VariantData {
731             ctor_kind: variant.ctor_kind,
732             discr: variant.discr,
733             ctor: variant.ctor_def_id.map(|did| did.index),
734             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
735         };
736
737         record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
738         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
739         record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
740         record!(self.tables.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
741         record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
742         record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
743             assert!(f.did.is_local());
744             f.did.index
745         }));
746         self.encode_ident_span(def_id, variant.ident);
747         self.encode_stability(def_id);
748         self.encode_deprecation(def_id);
749         self.encode_item_type(def_id);
750         if variant.ctor_kind == CtorKind::Fn {
751             // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
752             if let Some(ctor_def_id) = variant.ctor_def_id {
753                 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
754             }
755             // FIXME(eddyb) is this ever used?
756             self.encode_variances_of(def_id);
757         }
758         self.encode_generics(def_id);
759         self.encode_explicit_predicates(def_id);
760         self.encode_inferred_outlives(def_id);
761     }
762
763     fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) {
764         let tcx = self.tcx;
765         let variant = &def.variants[index];
766         let def_id = variant.ctor_def_id.unwrap();
767         debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
768
769         // FIXME(eddyb) encode only the `CtorKind` for constructors.
770         let data = VariantData {
771             ctor_kind: variant.ctor_kind,
772             discr: variant.discr,
773             ctor: Some(def_id.index),
774             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
775         };
776
777         record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
778         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
779         record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
780         self.encode_stability(def_id);
781         self.encode_deprecation(def_id);
782         self.encode_item_type(def_id);
783         if variant.ctor_kind == CtorKind::Fn {
784             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
785             self.encode_variances_of(def_id);
786         }
787         self.encode_generics(def_id);
788         self.encode_explicit_predicates(def_id);
789         self.encode_inferred_outlives(def_id);
790         self.encode_optimized_mir(def_id.expect_local());
791         self.encode_promoted_mir(def_id.expect_local());
792     }
793
794     fn encode_info_for_mod(&mut self, id: hir::HirId, md: &hir::Mod<'_>, attrs: &[ast::Attribute]) {
795         let tcx = self.tcx;
796         let local_def_id = tcx.hir().local_def_id(id);
797         let def_id = local_def_id.to_def_id();
798         debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
799
800         // If we are encoding a proc-macro crates, `encode_info_for_mod` will
801         // only ever get called for the crate root. We still want to encode
802         // the crate root for consistency with other crates (some of the resolver
803         // code uses it). However, we skip encoding anything relating to child
804         // items - we encode information about proc-macros later on.
805         let reexports = if !self.is_proc_macro {
806             match tcx.module_exports(local_def_id) {
807                 Some(exports) => {
808                     let hir = self.tcx.hir();
809                     self.lazy(
810                         exports
811                             .iter()
812                             .map(|export| export.map_id(|id| hir.local_def_id_to_hir_id(id))),
813                     )
814                 }
815                 _ => Lazy::empty(),
816             }
817         } else {
818             Lazy::empty()
819         };
820
821         let data = ModData {
822             reexports,
823             expansion: tcx.hir().definitions().expansion_that_defined(local_def_id),
824         };
825
826         record!(self.tables.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
827         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
828         record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
829         record!(self.tables.attributes[def_id] <- attrs);
830         if self.is_proc_macro {
831             record!(self.tables.children[def_id] <- &[]);
832         } else {
833             record!(self.tables.children[def_id] <- md.item_ids.iter().map(|item_id| {
834                 tcx.hir().local_def_id(item_id.id).local_def_index
835             }));
836         }
837         self.encode_stability(def_id);
838         self.encode_deprecation(def_id);
839     }
840
841     fn encode_field(
842         &mut self,
843         adt_def: &ty::AdtDef,
844         variant_index: VariantIdx,
845         field_index: usize,
846     ) {
847         let tcx = self.tcx;
848         let variant = &adt_def.variants[variant_index];
849         let field = &variant.fields[field_index];
850
851         let def_id = field.did;
852         debug!("EncodeContext::encode_field({:?})", def_id);
853
854         let variant_id = tcx.hir().local_def_id_to_hir_id(variant.def_id.expect_local());
855         let variant_data = tcx.hir().expect_variant_data(variant_id);
856
857         record!(self.tables.kind[def_id] <- EntryKind::Field);
858         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
859         record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
860         record!(self.tables.attributes[def_id] <- variant_data.fields()[field_index].attrs);
861         record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
862         self.encode_ident_span(def_id, field.ident);
863         self.encode_stability(def_id);
864         self.encode_deprecation(def_id);
865         self.encode_item_type(def_id);
866         self.encode_generics(def_id);
867         self.encode_explicit_predicates(def_id);
868         self.encode_inferred_outlives(def_id);
869     }
870
871     fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) {
872         debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
873         let tcx = self.tcx;
874         let variant = adt_def.non_enum_variant();
875
876         let data = VariantData {
877             ctor_kind: variant.ctor_kind,
878             discr: variant.discr,
879             ctor: Some(def_id.index),
880             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
881         };
882
883         record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
884         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
885         record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
886         record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
887         self.encode_stability(def_id);
888         self.encode_deprecation(def_id);
889         self.encode_item_type(def_id);
890         if variant.ctor_kind == CtorKind::Fn {
891             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
892             self.encode_variances_of(def_id);
893         }
894         self.encode_generics(def_id);
895         self.encode_explicit_predicates(def_id);
896         self.encode_inferred_outlives(def_id);
897         self.encode_optimized_mir(def_id.expect_local());
898         self.encode_promoted_mir(def_id.expect_local());
899     }
900
901     fn encode_generics(&mut self, def_id: DefId) {
902         debug!("EncodeContext::encode_generics({:?})", def_id);
903         record!(self.tables.generics[def_id] <- self.tcx.generics_of(def_id));
904     }
905
906     fn encode_explicit_predicates(&mut self, def_id: DefId) {
907         debug!("EncodeContext::encode_explicit_predicates({:?})", def_id);
908         record!(self.tables.explicit_predicates[def_id] <-
909             self.tcx.explicit_predicates_of(def_id));
910     }
911
912     fn encode_inferred_outlives(&mut self, def_id: DefId) {
913         debug!("EncodeContext::encode_inferred_outlives({:?})", def_id);
914         let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
915         if !inferred_outlives.is_empty() {
916             record!(self.tables.inferred_outlives[def_id] <- inferred_outlives);
917         }
918     }
919
920     fn encode_super_predicates(&mut self, def_id: DefId) {
921         debug!("EncodeContext::encode_super_predicates({:?})", def_id);
922         record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
923     }
924
925     fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
926         debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
927         let bounds = self.tcx.explicit_item_bounds(def_id);
928         if !bounds.is_empty() {
929             record!(self.tables.explicit_item_bounds[def_id] <- bounds);
930         }
931     }
932
933     fn encode_info_for_trait_item(&mut self, def_id: DefId) {
934         debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
935         let tcx = self.tcx;
936
937         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
938         let ast_item = tcx.hir().expect_trait_item(hir_id);
939         let trait_item = tcx.associated_item(def_id);
940
941         let container = match trait_item.defaultness {
942             hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
943             hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
944             hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
945         };
946
947         record!(self.tables.kind[def_id] <- match trait_item.kind {
948             ty::AssocKind::Const => {
949                 let rendered = rustc_hir_pretty::to_string(
950                     &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
951                     |s| s.print_trait_item(ast_item)
952                 );
953                 let rendered_const = self.lazy(RenderedConst(rendered));
954
955                 EntryKind::AssocConst(
956                     container,
957                     Default::default(),
958                     rendered_const,
959                 )
960             }
961             ty::AssocKind::Fn => {
962                 let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind {
963                     let param_names = match *m {
964                         hir::TraitFn::Required(ref names) => {
965                             self.encode_fn_param_names(names)
966                         }
967                         hir::TraitFn::Provided(body) => {
968                             self.encode_fn_param_names_for_body(body)
969                         }
970                     };
971                     FnData {
972                         asyncness: m_sig.header.asyncness,
973                         constness: hir::Constness::NotConst,
974                         param_names,
975                     }
976                 } else {
977                     bug!()
978                 };
979                 EntryKind::AssocFn(self.lazy(AssocFnData {
980                     fn_data,
981                     container,
982                     has_self: trait_item.fn_has_self_parameter,
983                 }))
984             }
985             ty::AssocKind::Type => {
986                 self.encode_explicit_item_bounds(def_id);
987                 EntryKind::AssocType(container)
988             }
989         });
990         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
991         record!(self.tables.span[def_id] <- ast_item.span);
992         record!(self.tables.attributes[def_id] <- ast_item.attrs);
993         self.encode_ident_span(def_id, ast_item.ident);
994         self.encode_stability(def_id);
995         self.encode_const_stability(def_id);
996         self.encode_deprecation(def_id);
997         match trait_item.kind {
998             ty::AssocKind::Const | ty::AssocKind::Fn => {
999                 self.encode_item_type(def_id);
1000             }
1001             ty::AssocKind::Type => {
1002                 if trait_item.defaultness.has_value() {
1003                     self.encode_item_type(def_id);
1004                 }
1005             }
1006         }
1007         if trait_item.kind == ty::AssocKind::Fn {
1008             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1009             self.encode_variances_of(def_id);
1010         }
1011         self.encode_generics(def_id);
1012         self.encode_explicit_predicates(def_id);
1013         self.encode_inferred_outlives(def_id);
1014
1015         // This should be kept in sync with `PrefetchVisitor.visit_trait_item`.
1016         self.encode_optimized_mir(def_id.expect_local());
1017         self.encode_promoted_mir(def_id.expect_local());
1018     }
1019
1020     fn metadata_output_only(&self) -> bool {
1021         // MIR optimisation can be skipped when we're just interested in the metadata.
1022         !self.tcx.sess.opts.output_types.should_codegen()
1023     }
1024
1025     fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1026         debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1027         let tcx = self.tcx;
1028
1029         let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1030         let ast_item = self.tcx.hir().expect_impl_item(hir_id);
1031         let impl_item = self.tcx.associated_item(def_id);
1032
1033         let container = match impl_item.defaultness {
1034             hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
1035             hir::Defaultness::Final => AssocContainer::ImplFinal,
1036             hir::Defaultness::Default { has_value: false } => {
1037                 span_bug!(ast_item.span, "impl items always have values (currently)")
1038             }
1039         };
1040
1041         record!(self.tables.kind[def_id] <- match impl_item.kind {
1042             ty::AssocKind::Const => {
1043                 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1044                     let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1045
1046                     EntryKind::AssocConst(
1047                         container,
1048                         qualifs,
1049                         self.encode_rendered_const_for_body(body_id))
1050                 } else {
1051                     bug!()
1052                 }
1053             }
1054             ty::AssocKind::Fn => {
1055                 let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind {
1056                     FnData {
1057                         asyncness: sig.header.asyncness,
1058                         constness: sig.header.constness,
1059                         param_names: self.encode_fn_param_names_for_body(body),
1060                     }
1061                 } else {
1062                     bug!()
1063                 };
1064                 EntryKind::AssocFn(self.lazy(AssocFnData {
1065                     fn_data,
1066                     container,
1067                     has_self: impl_item.fn_has_self_parameter,
1068                 }))
1069             }
1070             ty::AssocKind::Type => EntryKind::AssocType(container)
1071         });
1072         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1073         record!(self.tables.span[def_id] <- ast_item.span);
1074         record!(self.tables.attributes[def_id] <- ast_item.attrs);
1075         self.encode_ident_span(def_id, impl_item.ident);
1076         self.encode_stability(def_id);
1077         self.encode_const_stability(def_id);
1078         self.encode_deprecation(def_id);
1079         self.encode_item_type(def_id);
1080         if impl_item.kind == ty::AssocKind::Fn {
1081             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1082             self.encode_variances_of(def_id);
1083         }
1084         self.encode_generics(def_id);
1085         self.encode_explicit_predicates(def_id);
1086         self.encode_inferred_outlives(def_id);
1087
1088         // The following part should be kept in sync with `PrefetchVisitor.visit_impl_item`.
1089
1090         let mir = match ast_item.kind {
1091             hir::ImplItemKind::Const(..) => true,
1092             hir::ImplItemKind::Fn(ref sig, _) => {
1093                 let generics = self.tcx.generics_of(def_id);
1094                 let needs_inline = (generics.requires_monomorphization(self.tcx)
1095                     || tcx.codegen_fn_attrs(def_id).requests_inline())
1096                     && !self.metadata_output_only();
1097                 let is_const_fn = sig.header.constness == hir::Constness::Const;
1098                 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1099                 needs_inline || is_const_fn || always_encode_mir
1100             }
1101             hir::ImplItemKind::TyAlias(..) => false,
1102         };
1103         if mir {
1104             self.encode_optimized_mir(def_id.expect_local());
1105             self.encode_promoted_mir(def_id.expect_local());
1106         }
1107     }
1108
1109     fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> {
1110         self.lazy(self.tcx.hir().body_param_names(body_id))
1111     }
1112
1113     fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> {
1114         self.lazy(param_names.iter())
1115     }
1116
1117     fn encode_optimized_mir(&mut self, def_id: LocalDefId) {
1118         debug!("EntryBuilder::encode_mir({:?})", def_id);
1119         record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1120
1121         let unused = self.tcx.unused_generic_params(def_id);
1122         if !unused.is_empty() {
1123             record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1124         }
1125
1126         let abstract_const = self.tcx.mir_abstract_const(def_id);
1127         if let Ok(Some(abstract_const)) = abstract_const {
1128             record!(self.tables.mir_abstract_consts[def_id.to_def_id()] <- abstract_const);
1129         }
1130     }
1131
1132     fn encode_promoted_mir(&mut self, def_id: LocalDefId) {
1133         debug!("EncodeContext::encode_promoted_mir({:?})", def_id);
1134         if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1135             record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1136         }
1137     }
1138
1139     // Encodes the inherent implementations of a structure, enumeration, or trait.
1140     fn encode_inherent_implementations(&mut self, def_id: DefId) {
1141         debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1142         let implementations = self.tcx.inherent_impls(def_id);
1143         if !implementations.is_empty() {
1144             record!(self.tables.inherent_impls[def_id] <- implementations.iter().map(|&def_id| {
1145                 assert!(def_id.is_local());
1146                 def_id.index
1147             }));
1148         }
1149     }
1150
1151     fn encode_stability(&mut self, def_id: DefId) {
1152         debug!("EncodeContext::encode_stability({:?})", def_id);
1153
1154         // The query lookup can take a measurable amount of time in crates with many items. Check if
1155         // the stability attributes are even enabled before using their queries.
1156         if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1157             if let Some(stab) = self.tcx.lookup_stability(def_id) {
1158                 record!(self.tables.stability[def_id] <- stab)
1159             }
1160         }
1161     }
1162
1163     fn encode_const_stability(&mut self, def_id: DefId) {
1164         debug!("EncodeContext::encode_const_stability({:?})", def_id);
1165
1166         // The query lookup can take a measurable amount of time in crates with many items. Check if
1167         // the stability attributes are even enabled before using their queries.
1168         if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1169             if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1170                 record!(self.tables.const_stability[def_id] <- stab)
1171             }
1172         }
1173     }
1174
1175     fn encode_deprecation(&mut self, def_id: DefId) {
1176         debug!("EncodeContext::encode_deprecation({:?})", def_id);
1177         if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1178             record!(self.tables.deprecation[def_id] <- depr);
1179         }
1180     }
1181
1182     fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1183         let hir = self.tcx.hir();
1184         let body = hir.body(body_id);
1185         let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1186             s.print_expr(&body.value)
1187         });
1188         let rendered_const = &RenderedConst(rendered);
1189         self.lazy(rendered_const)
1190     }
1191
1192     fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1193         let tcx = self.tcx;
1194
1195         debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1196
1197         self.encode_ident_span(def_id, item.ident);
1198
1199         record!(self.tables.kind[def_id] <- match item.kind {
1200             hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic,
1201             hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic,
1202             hir::ItemKind::Const(_, body_id) => {
1203                 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1204                 EntryKind::Const(
1205                     qualifs,
1206                     self.encode_rendered_const_for_body(body_id)
1207                 )
1208             }
1209             hir::ItemKind::Fn(ref sig, .., body) => {
1210                 let data = FnData {
1211                     asyncness: sig.header.asyncness,
1212                     constness: sig.header.constness,
1213                     param_names: self.encode_fn_param_names_for_body(body),
1214                 };
1215
1216                 EntryKind::Fn(self.lazy(data))
1217             }
1218             hir::ItemKind::Mod(ref m) => {
1219                 return self.encode_info_for_mod(item.hir_id, m, &item.attrs);
1220             }
1221             hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod,
1222             hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1223             hir::ItemKind::TyAlias(..) => EntryKind::Type,
1224             hir::ItemKind::OpaqueTy(..) => {
1225                 self.encode_explicit_item_bounds(def_id);
1226                 EntryKind::OpaqueTy
1227             }
1228             hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1229             hir::ItemKind::Struct(ref struct_def, _) => {
1230                 let adt_def = self.tcx.adt_def(def_id);
1231                 let variant = adt_def.non_enum_variant();
1232
1233                 // Encode def_ids for each field and method
1234                 // for methods, write all the stuff get_trait_method
1235                 // needs to know
1236                 let ctor = struct_def.ctor_hir_id().map(|ctor_hir_id| {
1237                     self.tcx.hir().local_def_id(ctor_hir_id).local_def_index
1238                 });
1239
1240                 EntryKind::Struct(self.lazy(VariantData {
1241                     ctor_kind: variant.ctor_kind,
1242                     discr: variant.discr,
1243                     ctor,
1244                     is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1245                 }), adt_def.repr)
1246             }
1247             hir::ItemKind::Union(..) => {
1248                 let adt_def = self.tcx.adt_def(def_id);
1249                 let variant = adt_def.non_enum_variant();
1250
1251                 EntryKind::Union(self.lazy(VariantData {
1252                     ctor_kind: variant.ctor_kind,
1253                     discr: variant.discr,
1254                     ctor: None,
1255                     is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1256                 }), adt_def.repr)
1257             }
1258             hir::ItemKind::Impl { defaultness, .. } => {
1259                 let trait_ref = self.tcx.impl_trait_ref(def_id);
1260                 let polarity = self.tcx.impl_polarity(def_id);
1261                 let parent = if let Some(trait_ref) = trait_ref {
1262                     let trait_def = self.tcx.trait_def(trait_ref.def_id);
1263                     trait_def.ancestors(self.tcx, def_id).ok()
1264                         .and_then(|mut an| an.nth(1).and_then(|node| {
1265                             match node {
1266                                 specialization_graph::Node::Impl(parent) => Some(parent),
1267                                 _ => None,
1268                             }
1269                         }))
1270                 } else {
1271                     None
1272                 };
1273
1274                 // if this is an impl of `CoerceUnsized`, create its
1275                 // "unsized info", else just store None
1276                 let coerce_unsized_info =
1277                     trait_ref.and_then(|t| {
1278                         if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1279                             Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1280                         } else {
1281                             None
1282                         }
1283                     });
1284
1285                 let data = ImplData {
1286                     polarity,
1287                     defaultness,
1288                     parent_impl: parent,
1289                     coerce_unsized_info,
1290                 };
1291
1292                 EntryKind::Impl(self.lazy(data))
1293             }
1294             hir::ItemKind::Trait(..) => {
1295                 let trait_def = self.tcx.trait_def(def_id);
1296                 let data = TraitData {
1297                     unsafety: trait_def.unsafety,
1298                     paren_sugar: trait_def.paren_sugar,
1299                     has_auto_impl: self.tcx.trait_is_auto(def_id),
1300                     is_marker: trait_def.is_marker,
1301                     specialization_kind: trait_def.specialization_kind,
1302                 };
1303
1304                 EntryKind::Trait(self.lazy(data))
1305             }
1306             hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1307             hir::ItemKind::ExternCrate(_) |
1308             hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1309         });
1310         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1311         record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
1312         record!(self.tables.attributes[def_id] <- item.attrs);
1313         record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
1314         // FIXME(eddyb) there should be a nicer way to do this.
1315         match item.kind {
1316             hir::ItemKind::ForeignMod { items, .. } => record!(self.tables.children[def_id] <-
1317                 items
1318                     .iter()
1319                     .map(|foreign_item| tcx.hir().local_def_id(
1320                         foreign_item.id.hir_id).local_def_index)
1321             ),
1322             hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <-
1323                 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1324                     assert!(v.def_id.is_local());
1325                     v.def_id.index
1326                 })
1327             ),
1328             hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1329                 record!(self.tables.children[def_id] <-
1330                     self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1331                         assert!(f.did.is_local());
1332                         f.did.index
1333                     })
1334                 )
1335             }
1336             hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1337                 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1338                 record!(self.tables.children[def_id] <-
1339                     associated_item_def_ids.iter().map(|&def_id| {
1340                         assert!(def_id.is_local());
1341                         def_id.index
1342                     })
1343                 );
1344             }
1345             _ => {}
1346         }
1347         self.encode_stability(def_id);
1348         self.encode_const_stability(def_id);
1349         self.encode_deprecation(def_id);
1350         match item.kind {
1351             hir::ItemKind::Static(..)
1352             | hir::ItemKind::Const(..)
1353             | hir::ItemKind::Fn(..)
1354             | hir::ItemKind::TyAlias(..)
1355             | hir::ItemKind::OpaqueTy(..)
1356             | hir::ItemKind::Enum(..)
1357             | hir::ItemKind::Struct(..)
1358             | hir::ItemKind::Union(..)
1359             | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1360             _ => {}
1361         }
1362         if let hir::ItemKind::Fn(..) = item.kind {
1363             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1364         }
1365         if let hir::ItemKind::Impl { .. } = item.kind {
1366             if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1367                 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1368             }
1369         }
1370         self.encode_inherent_implementations(def_id);
1371         match item.kind {
1372             hir::ItemKind::Enum(..)
1373             | hir::ItemKind::Struct(..)
1374             | hir::ItemKind::Union(..)
1375             | hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1376             _ => {}
1377         }
1378         match item.kind {
1379             hir::ItemKind::Static(..)
1380             | hir::ItemKind::Const(..)
1381             | hir::ItemKind::Fn(..)
1382             | hir::ItemKind::TyAlias(..)
1383             | hir::ItemKind::Enum(..)
1384             | hir::ItemKind::Struct(..)
1385             | hir::ItemKind::Union(..)
1386             | hir::ItemKind::Impl { .. }
1387             | hir::ItemKind::OpaqueTy(..)
1388             | hir::ItemKind::Trait(..)
1389             | hir::ItemKind::TraitAlias(..) => {
1390                 self.encode_generics(def_id);
1391                 self.encode_explicit_predicates(def_id);
1392                 self.encode_inferred_outlives(def_id);
1393             }
1394             _ => {}
1395         }
1396         match item.kind {
1397             hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => {
1398                 self.encode_super_predicates(def_id);
1399             }
1400             _ => {}
1401         }
1402
1403         // The following part should be kept in sync with `PrefetchVisitor.visit_item`.
1404
1405         let mir = match item.kind {
1406             hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => true,
1407             hir::ItemKind::Fn(ref sig, ..) => {
1408                 let generics = tcx.generics_of(def_id);
1409                 let needs_inline = (generics.requires_monomorphization(tcx)
1410                     || tcx.codegen_fn_attrs(def_id).requests_inline())
1411                     && !self.metadata_output_only();
1412
1413                 let is_const_fn = sig.header.constness == hir::Constness::Const;
1414                 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1415                 needs_inline || is_const_fn || always_encode_mir
1416             }
1417             _ => false,
1418         };
1419         if mir {
1420             self.encode_optimized_mir(def_id.expect_local());
1421             self.encode_promoted_mir(def_id.expect_local());
1422         }
1423     }
1424
1425     /// Serialize the text of exported macros
1426     fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) {
1427         let def_id = self.tcx.hir().local_def_id(macro_def.hir_id).to_def_id();
1428         record!(self.tables.kind[def_id] <- EntryKind::MacroDef(self.lazy(macro_def.ast.clone())));
1429         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1430         record!(self.tables.span[def_id] <- macro_def.span);
1431         record!(self.tables.attributes[def_id] <- macro_def.attrs);
1432         self.encode_ident_span(def_id, macro_def.ident);
1433         self.encode_stability(def_id);
1434         self.encode_deprecation(def_id);
1435     }
1436
1437     fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1438         record!(self.tables.kind[def_id] <- kind);
1439         record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
1440         if encode_type {
1441             self.encode_item_type(def_id);
1442         }
1443     }
1444
1445     fn encode_info_for_closure(&mut self, def_id: LocalDefId) {
1446         debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1447
1448         // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1449         // including on the signature, which is inferred in `typeck.
1450         let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1451         let ty = self.tcx.typeck(def_id).node_type(hir_id);
1452
1453         record!(self.tables.kind[def_id.to_def_id()] <- match ty.kind() {
1454             ty::Generator(..) => {
1455                 let data = self.tcx.generator_kind(def_id).unwrap();
1456                 EntryKind::Generator(data)
1457             }
1458
1459             ty::Closure(..) => EntryKind::Closure,
1460
1461             _ => bug!("closure that is neither generator nor closure"),
1462         });
1463         record!(self.tables.span[def_id.to_def_id()] <- self.tcx.def_span(def_id));
1464         record!(self.tables.attributes[def_id.to_def_id()] <- &self.tcx.get_attrs(def_id.to_def_id())[..]);
1465         self.encode_item_type(def_id.to_def_id());
1466         if let ty::Closure(def_id, substs) = *ty.kind() {
1467             record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1468         }
1469         self.encode_generics(def_id.to_def_id());
1470         self.encode_optimized_mir(def_id);
1471         self.encode_promoted_mir(def_id);
1472     }
1473
1474     fn encode_info_for_anon_const(&mut self, def_id: LocalDefId) {
1475         debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1476         let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1477         let body_id = self.tcx.hir().body_owned_by(id);
1478         let const_data = self.encode_rendered_const_for_body(body_id);
1479         let qualifs = self.tcx.mir_const_qualif(def_id);
1480
1481         record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data));
1482         record!(self.tables.span[def_id.to_def_id()] <- self.tcx.def_span(def_id));
1483         self.encode_item_type(def_id.to_def_id());
1484         self.encode_generics(def_id.to_def_id());
1485         self.encode_explicit_predicates(def_id.to_def_id());
1486         self.encode_inferred_outlives(def_id.to_def_id());
1487         self.encode_optimized_mir(def_id);
1488         self.encode_promoted_mir(def_id);
1489     }
1490
1491     fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
1492         empty_proc_macro!(self);
1493         let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1494         self.lazy(used_libraries.iter().cloned())
1495     }
1496
1497     fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1498         empty_proc_macro!(self);
1499         let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1500         self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned())
1501     }
1502
1503     fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable) {
1504         let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1505         let mut expn_data_table: TableBuilder<_, _> = Default::default();
1506
1507         let _: Result<(), !> = self.hygiene_ctxt.encode(
1508             &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table),
1509             |(this, syntax_contexts, _), index, ctxt_data| {
1510                 syntax_contexts.set(index, this.lazy(ctxt_data));
1511                 Ok(())
1512             },
1513             |(this, _, expn_data_table), index, expn_data| {
1514                 expn_data_table.set(index, this.lazy(expn_data));
1515                 Ok(())
1516             },
1517         );
1518
1519         (syntax_contexts.encode(&mut self.opaque), expn_data_table.encode(&mut self.opaque))
1520     }
1521
1522     fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1523         let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1524         if is_proc_macro {
1525             let tcx = self.tcx;
1526             let hir = tcx.hir();
1527
1528             let proc_macro_decls_static = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap().index;
1529             let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied();
1530             let macros = self.lazy(hir.krate().proc_macros.iter().map(|p| p.owner.local_def_index));
1531
1532             // Normally, this information is encoded when we walk the items
1533             // defined in this crate. However, we skip doing that for proc-macro crates,
1534             // so we manually encode just the information that we need
1535             for proc_macro in &hir.krate().proc_macros {
1536                 let id = proc_macro.owner.local_def_index;
1537                 let mut name = hir.name(*proc_macro);
1538                 let span = hir.span(*proc_macro);
1539                 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1540                 // so downstream crates need access to them.
1541                 let attrs = hir.attrs(*proc_macro);
1542                 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1543                     MacroKind::Bang
1544                 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1545                     MacroKind::Attr
1546                 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1547                     // This unwrap chain should have been checked by the proc-macro harness.
1548                     name = attr.meta_item_list().unwrap()[0]
1549                         .meta_item()
1550                         .unwrap()
1551                         .ident()
1552                         .unwrap()
1553                         .name;
1554                     MacroKind::Derive
1555                 } else {
1556                     bug!("Unknown proc-macro type for item {:?}", id);
1557                 };
1558
1559                 let mut def_key = self.tcx.hir().def_key(proc_macro.owner);
1560                 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1561
1562                 let def_id = DefId::local(id);
1563                 record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind));
1564                 record!(self.tables.attributes[def_id] <- attrs);
1565                 record!(self.tables.def_keys[def_id] <- def_key);
1566                 record!(self.tables.ident_span[def_id] <- span);
1567                 record!(self.tables.span[def_id] <- span);
1568                 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1569                 if let Some(stability) = stability {
1570                     record!(self.tables.stability[def_id] <- stability);
1571                 }
1572             }
1573
1574             Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1575         } else {
1576             None
1577         }
1578     }
1579
1580     fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1581         empty_proc_macro!(self);
1582         let crates = self.tcx.crates();
1583
1584         let mut deps = crates
1585             .iter()
1586             .map(|&cnum| {
1587                 let dep = CrateDep {
1588                     name: self.tcx.original_crate_name(cnum),
1589                     hash: self.tcx.crate_hash(cnum),
1590                     host_hash: self.tcx.crate_host_hash(cnum),
1591                     kind: self.tcx.dep_kind(cnum),
1592                     extra_filename: self.tcx.extra_filename(cnum),
1593                 };
1594                 (cnum, dep)
1595             })
1596             .collect::<Vec<_>>();
1597
1598         deps.sort_by_key(|&(cnum, _)| cnum);
1599
1600         {
1601             // Sanity-check the crate numbers
1602             let mut expected_cnum = 1;
1603             for &(n, _) in &deps {
1604                 assert_eq!(n, CrateNum::new(expected_cnum));
1605                 expected_cnum += 1;
1606             }
1607         }
1608
1609         // We're just going to write a list of crate 'name-hash-version's, with
1610         // the assumption that they are numbered 1 to n.
1611         // FIXME (#2166): This is not nearly enough to support correct versioning
1612         // but is enough to get transitive crate dependencies working.
1613         self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1614     }
1615
1616     fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> {
1617         empty_proc_macro!(self);
1618         let tcx = self.tcx;
1619         let lib_features = tcx.lib_features();
1620         self.lazy(lib_features.to_vec())
1621     }
1622
1623     fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1624         empty_proc_macro!(self);
1625         let tcx = self.tcx;
1626         let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1627         self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1628     }
1629
1630     fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1631         empty_proc_macro!(self);
1632         let tcx = self.tcx;
1633         let lang_items = tcx.lang_items();
1634         let lang_items = lang_items.items().iter();
1635         self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1636             if let Some(def_id) = opt_def_id {
1637                 if def_id.is_local() {
1638                     return Some((def_id.index, i));
1639                 }
1640             }
1641             None
1642         }))
1643     }
1644
1645     fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1646         empty_proc_macro!(self);
1647         let tcx = self.tcx;
1648         self.lazy(&tcx.lang_items().missing)
1649     }
1650
1651     /// Encodes an index, mapping each trait to its (local) implementations.
1652     fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1653         empty_proc_macro!(self);
1654         debug!("EncodeContext::encode_impls()");
1655         let tcx = self.tcx;
1656         let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() };
1657         tcx.hir().krate().visit_all_item_likes(&mut visitor);
1658
1659         let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1660
1661         // Bring everything into deterministic order for hashing
1662         all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1663
1664         let all_impls: Vec<_> = all_impls
1665             .into_iter()
1666             .map(|(trait_def_id, mut impls)| {
1667                 // Bring everything into deterministic order for hashing
1668                 impls.sort_by_cached_key(|&(index, _)| {
1669                     tcx.hir().definitions().def_path_hash(LocalDefId { local_def_index: index })
1670                 });
1671
1672                 TraitImpls {
1673                     trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1674                     impls: self.lazy(&impls),
1675                 }
1676             })
1677             .collect();
1678
1679         self.lazy(&all_impls)
1680     }
1681
1682     // Encodes all symbols exported from this crate into the metadata.
1683     //
1684     // This pass is seeded off the reachability list calculated in the
1685     // middle::reachable module but filters out items that either don't have a
1686     // symbol associated with them (they weren't translated) or if they're an FFI
1687     // definition (as that's not defined in this crate).
1688     fn encode_exported_symbols(
1689         &mut self,
1690         exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1691     ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1692         empty_proc_macro!(self);
1693         // The metadata symbol name is special. It should not show up in
1694         // downstream crates.
1695         let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1696
1697         self.lazy(
1698             exported_symbols
1699                 .iter()
1700                 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1701                     ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1702                     _ => true,
1703                 })
1704                 .cloned(),
1705         )
1706     }
1707
1708     fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1709         empty_proc_macro!(self);
1710         let formats = self.tcx.dependency_formats(LOCAL_CRATE);
1711         for (ty, arr) in formats.iter() {
1712             if *ty != CrateType::Dylib {
1713                 continue;
1714             }
1715             return self.lazy(arr.iter().map(|slot| match *slot {
1716                 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1717
1718                 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1719                 Linkage::Static => Some(LinkagePreference::RequireStatic),
1720             }));
1721         }
1722         Lazy::empty()
1723     }
1724
1725     fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1726         let tcx = self.tcx;
1727
1728         debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1729
1730         record!(self.tables.kind[def_id] <- match nitem.kind {
1731             hir::ForeignItemKind::Fn(_, ref names, _) => {
1732                 let data = FnData {
1733                     asyncness: hir::IsAsync::NotAsync,
1734                     constness: if self.tcx.is_const_fn_raw(def_id) {
1735                         hir::Constness::Const
1736                     } else {
1737                         hir::Constness::NotConst
1738                     },
1739                     param_names: self.encode_fn_param_names(names),
1740                 };
1741                 EntryKind::ForeignFn(self.lazy(data))
1742             }
1743             hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => EntryKind::ForeignMutStatic,
1744             hir::ForeignItemKind::Static(_, hir::Mutability::Not) => EntryKind::ForeignImmStatic,
1745             hir::ForeignItemKind::Type => EntryKind::ForeignType,
1746         });
1747         record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
1748         record!(self.tables.span[def_id] <- nitem.span);
1749         record!(self.tables.attributes[def_id] <- nitem.attrs);
1750         self.encode_ident_span(def_id, nitem.ident);
1751         self.encode_stability(def_id);
1752         self.encode_const_stability(def_id);
1753         self.encode_deprecation(def_id);
1754         self.encode_item_type(def_id);
1755         self.encode_inherent_implementations(def_id);
1756         if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1757             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1758             self.encode_variances_of(def_id);
1759         }
1760         self.encode_generics(def_id);
1761         self.encode_explicit_predicates(def_id);
1762         self.encode_inferred_outlives(def_id);
1763     }
1764 }
1765
1766 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1767 impl Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1768     type Map = Map<'tcx>;
1769
1770     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1771         NestedVisitorMap::OnlyBodies(self.tcx.hir())
1772     }
1773     fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1774         intravisit::walk_expr(self, ex);
1775         self.encode_info_for_expr(ex);
1776     }
1777     fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1778         intravisit::walk_anon_const(self, c);
1779         let def_id = self.tcx.hir().local_def_id(c.hir_id);
1780         self.encode_info_for_anon_const(def_id);
1781     }
1782     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1783         intravisit::walk_item(self, item);
1784         let def_id = self.tcx.hir().local_def_id(item.hir_id);
1785         match item.kind {
1786             hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1787             _ => self.encode_info_for_item(def_id.to_def_id(), item),
1788         }
1789         self.encode_addl_info_for_item(item);
1790     }
1791     fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1792         intravisit::walk_foreign_item(self, ni);
1793         let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1794         self.encode_info_for_foreign_item(def_id.to_def_id(), ni);
1795     }
1796     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1797         intravisit::walk_generics(self, generics);
1798         self.encode_info_for_generics(generics);
1799     }
1800     fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) {
1801         self.encode_info_for_macro_def(macro_def);
1802     }
1803 }
1804
1805 impl EncodeContext<'a, 'tcx> {
1806     fn encode_fields(&mut self, adt_def: &ty::AdtDef) {
1807         for (variant_index, variant) in adt_def.variants.iter_enumerated() {
1808             for (field_index, _field) in variant.fields.iter().enumerate() {
1809                 self.encode_field(adt_def, variant_index, field_index);
1810             }
1811         }
1812     }
1813
1814     fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1815         for param in generics.params {
1816             let def_id = self.tcx.hir().local_def_id(param.hir_id);
1817             match param.kind {
1818                 GenericParamKind::Lifetime { .. } => continue,
1819                 GenericParamKind::Type { ref default, .. } => {
1820                     self.encode_info_for_generic_param(
1821                         def_id.to_def_id(),
1822                         EntryKind::TypeParam,
1823                         default.is_some(),
1824                     );
1825                     if default.is_some() {
1826                         self.encode_stability(def_id.to_def_id());
1827                     }
1828                 }
1829                 GenericParamKind::Const { .. } => {
1830                     self.encode_info_for_generic_param(
1831                         def_id.to_def_id(),
1832                         EntryKind::ConstParam,
1833                         true,
1834                     );
1835                     // FIXME(const_generics_defaults)
1836                 }
1837             }
1838         }
1839     }
1840
1841     fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1842         if let hir::ExprKind::Closure(..) = expr.kind {
1843             let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1844             self.encode_info_for_closure(def_id);
1845         }
1846     }
1847
1848     fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) {
1849         record!(self.tables.ident_span[def_id] <- ident.span);
1850     }
1851
1852     /// In some cases, along with the item itself, we also
1853     /// encode some sub-items. Usually we want some info from the item
1854     /// so it's easier to do that here then to wait until we would encounter
1855     /// normally in the visitor walk.
1856     fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1857         let def_id = self.tcx.hir().local_def_id(item.hir_id);
1858         match item.kind {
1859             hir::ItemKind::Static(..)
1860             | hir::ItemKind::Const(..)
1861             | hir::ItemKind::Fn(..)
1862             | hir::ItemKind::Mod(..)
1863             | hir::ItemKind::ForeignMod { .. }
1864             | hir::ItemKind::GlobalAsm(..)
1865             | hir::ItemKind::ExternCrate(..)
1866             | hir::ItemKind::Use(..)
1867             | hir::ItemKind::TyAlias(..)
1868             | hir::ItemKind::OpaqueTy(..)
1869             | hir::ItemKind::TraitAlias(..) => {
1870                 // no sub-item recording needed in these cases
1871             }
1872             hir::ItemKind::Enum(..) => {
1873                 let def = self.tcx.adt_def(def_id.to_def_id());
1874                 self.encode_fields(def);
1875
1876                 for (i, variant) in def.variants.iter_enumerated() {
1877                     self.encode_enum_variant_info(def, i);
1878
1879                     if let Some(_ctor_def_id) = variant.ctor_def_id {
1880                         self.encode_enum_variant_ctor(def, i);
1881                     }
1882                 }
1883             }
1884             hir::ItemKind::Struct(ref struct_def, _) => {
1885                 let def = self.tcx.adt_def(def_id.to_def_id());
1886                 self.encode_fields(def);
1887
1888                 // If the struct has a constructor, encode it.
1889                 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1890                     let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1891                     self.encode_struct_ctor(def, ctor_def_id.to_def_id());
1892                 }
1893             }
1894             hir::ItemKind::Union(..) => {
1895                 let def = self.tcx.adt_def(def_id.to_def_id());
1896                 self.encode_fields(def);
1897             }
1898             hir::ItemKind::Impl { .. } => {
1899                 for &trait_item_def_id in
1900                     self.tcx.associated_item_def_ids(def_id.to_def_id()).iter()
1901                 {
1902                     self.encode_info_for_impl_item(trait_item_def_id);
1903                 }
1904             }
1905             hir::ItemKind::Trait(..) => {
1906                 for &item_def_id in self.tcx.associated_item_def_ids(def_id.to_def_id()).iter() {
1907                     self.encode_info_for_trait_item(item_def_id);
1908                 }
1909             }
1910         }
1911     }
1912 }
1913
1914 struct ImplVisitor<'tcx> {
1915     tcx: TyCtxt<'tcx>,
1916     impls: FxHashMap<DefId, Vec<(DefIndex, Option<ty::fast_reject::SimplifiedType>)>>,
1917 }
1918
1919 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1920     fn visit_item(&mut self, item: &hir::Item<'_>) {
1921         if let hir::ItemKind::Impl { .. } = item.kind {
1922             let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1923             if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id.to_def_id()) {
1924                 let simplified_self_ty =
1925                     ty::fast_reject::simplify_type(self.tcx, trait_ref.self_ty(), false);
1926
1927                 self.impls
1928                     .entry(trait_ref.def_id)
1929                     .or_default()
1930                     .push((impl_id.local_def_index, simplified_self_ty));
1931             }
1932         }
1933     }
1934
1935     fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
1936
1937     fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
1938         // handled in `visit_item` above
1939     }
1940
1941     fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {}
1942 }
1943
1944 /// Used to prefetch queries which will be needed later by metadata encoding.
1945 /// Only a subset of the queries are actually prefetched to keep this code smaller.
1946 struct PrefetchVisitor<'tcx> {
1947     tcx: TyCtxt<'tcx>,
1948     mir_keys: &'tcx FxHashSet<LocalDefId>,
1949 }
1950
1951 impl<'tcx> PrefetchVisitor<'tcx> {
1952     fn prefetch_mir(&self, def_id: LocalDefId) {
1953         if self.mir_keys.contains(&def_id) {
1954             self.tcx.ensure().optimized_mir(def_id);
1955             self.tcx.ensure().promoted_mir(def_id);
1956         }
1957     }
1958 }
1959
1960 impl<'tcx, 'v> ParItemLikeVisitor<'v> for PrefetchVisitor<'tcx> {
1961     fn visit_item(&self, item: &hir::Item<'_>) {
1962         // This should be kept in sync with `encode_info_for_item`.
1963         let tcx = self.tcx;
1964         match item.kind {
1965             hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
1966                 self.prefetch_mir(tcx.hir().local_def_id(item.hir_id))
1967             }
1968             hir::ItemKind::Fn(ref sig, ..) => {
1969                 let def_id = tcx.hir().local_def_id(item.hir_id);
1970                 let generics = tcx.generics_of(def_id.to_def_id());
1971                 let needs_inline = generics.requires_monomorphization(tcx)
1972                     || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline();
1973                 if needs_inline || sig.header.constness == hir::Constness::Const {
1974                     self.prefetch_mir(def_id)
1975                 }
1976             }
1977             _ => (),
1978         }
1979     }
1980
1981     fn visit_trait_item(&self, trait_item: &'v hir::TraitItem<'v>) {
1982         // This should be kept in sync with `encode_info_for_trait_item`.
1983         self.prefetch_mir(self.tcx.hir().local_def_id(trait_item.hir_id));
1984     }
1985
1986     fn visit_impl_item(&self, impl_item: &'v hir::ImplItem<'v>) {
1987         // This should be kept in sync with `encode_info_for_impl_item`.
1988         let tcx = self.tcx;
1989         match impl_item.kind {
1990             hir::ImplItemKind::Const(..) => {
1991                 self.prefetch_mir(tcx.hir().local_def_id(impl_item.hir_id))
1992             }
1993             hir::ImplItemKind::Fn(ref sig, _) => {
1994                 let def_id = tcx.hir().local_def_id(impl_item.hir_id);
1995                 let generics = tcx.generics_of(def_id.to_def_id());
1996                 let needs_inline = generics.requires_monomorphization(tcx)
1997                     || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline();
1998                 let is_const_fn = sig.header.constness == hir::Constness::Const;
1999                 if needs_inline || is_const_fn {
2000                     self.prefetch_mir(def_id)
2001                 }
2002             }
2003             hir::ImplItemKind::TyAlias(..) => (),
2004         }
2005     }
2006
2007     fn visit_foreign_item(&self, _foreign_item: &'v hir::ForeignItem<'v>) {
2008         // This should be kept in sync with `encode_info_for_foreign_item`.
2009         // Foreign items contain no MIR.
2010     }
2011 }
2012
2013 // NOTE(eddyb) The following comment was preserved for posterity, even
2014 // though it's no longer relevant as EBML (which uses nested & tagged
2015 // "documents") was replaced with a scheme that can't go out of bounds.
2016 //
2017 // And here we run into yet another obscure archive bug: in which metadata
2018 // loaded from archives may have trailing garbage bytes. Awhile back one of
2019 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2020 // and opt) by having ebml generate an out-of-bounds panic when looking at
2021 // metadata.
2022 //
2023 // Upon investigation it turned out that the metadata file inside of an rlib
2024 // (and ar archive) was being corrupted. Some compilations would generate a
2025 // metadata file which would end in a few extra bytes, while other
2026 // compilations would not have these extra bytes appended to the end. These
2027 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2028 // being interpreted causing the out-of-bounds.
2029 //
2030 // The root cause of why these extra bytes were appearing was never
2031 // discovered, and in the meantime the solution we're employing is to insert
2032 // the length of the metadata to the start of the metadata. Later on this
2033 // will allow us to slice the metadata to the precise length that we just
2034 // generated regardless of trailing bytes that end up in it.
2035
2036 pub(super) fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
2037     // Since encoding metadata is not in a query, and nothing is cached,
2038     // there's no need to do dep-graph tracking for any of it.
2039     tcx.dep_graph.assert_ignored();
2040
2041     join(
2042         || encode_metadata_impl(tcx),
2043         || {
2044             if tcx.sess.threads() == 1 {
2045                 return;
2046             }
2047             // Prefetch some queries used by metadata encoding.
2048             // This is not necessary for correctness, but is only done for performance reasons.
2049             // It can be removed if it turns out to cause trouble or be detrimental to performance.
2050             join(
2051                 || {
2052                     if !tcx.sess.opts.output_types.should_codegen() {
2053                         // We won't emit MIR, so don't prefetch it.
2054                         return;
2055                     }
2056                     tcx.hir().krate().par_visit_all_item_likes(&PrefetchVisitor {
2057                         tcx,
2058                         mir_keys: tcx.mir_keys(LOCAL_CRATE),
2059                     });
2060                 },
2061                 || tcx.exported_symbols(LOCAL_CRATE),
2062             );
2063         },
2064     )
2065     .0
2066 }
2067
2068 fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata {
2069     let mut encoder = opaque::Encoder::new(vec![]);
2070     encoder.emit_raw_bytes(METADATA_HEADER);
2071
2072     // Will be filled with the root position after encoding everything.
2073     encoder.emit_raw_bytes(&[0, 0, 0, 0]);
2074
2075     let source_map_files = tcx.sess.source_map().files();
2076     let source_file_cache = (source_map_files[0].clone(), 0);
2077     let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len()));
2078     drop(source_map_files);
2079
2080     let hygiene_ctxt = HygieneEncodeContext::default();
2081
2082     let mut ecx = EncodeContext {
2083         opaque: encoder,
2084         tcx,
2085         feat: tcx.features(),
2086         tables: Default::default(),
2087         lazy_state: LazyState::NoNode,
2088         type_shorthands: Default::default(),
2089         predicate_shorthands: Default::default(),
2090         source_file_cache,
2091         interpret_allocs: Default::default(),
2092         required_source_files,
2093         is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2094         hygiene_ctxt: &hygiene_ctxt,
2095     };
2096
2097     // Encode the rustc version string in a predictable location.
2098     rustc_version().encode(&mut ecx).unwrap();
2099
2100     // Encode all the entries and extra information in the crate,
2101     // culminating in the `CrateRoot` which points to all of it.
2102     let root = ecx.encode_crate_root();
2103
2104     let mut result = ecx.opaque.into_inner();
2105
2106     // Encode the root position.
2107     let header = METADATA_HEADER.len();
2108     let pos = root.position.get();
2109     result[header + 0] = (pos >> 24) as u8;
2110     result[header + 1] = (pos >> 16) as u8;
2111     result[header + 2] = (pos >> 8) as u8;
2112     result[header + 3] = (pos >> 0) as u8;
2113
2114     EncodedMetadata { raw_data: result }
2115 }