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