]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/encoder.rs
Auto merge of #82043 - tmiasko:may-have-side-effect, r=kennytm
[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             panic_strategy: tcx.sess.panic_strategy(),
657             edition: tcx.sess.edition(),
658             has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
659             has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
660             has_default_lib_allocator,
661             plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
662             proc_macro_data,
663             compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
664             needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
665             needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
666             no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
667             panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
668             profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
669             symbol_mangling_version: tcx.sess.opts.debugging_opts.get_symbol_mangling_version(),
670
671             crate_deps,
672             dylib_dependency_formats,
673             lib_features,
674             lang_items,
675             diagnostic_items,
676             lang_items_missing,
677             native_libraries,
678             foreign_modules,
679             source_map,
680             impls,
681             exported_symbols,
682             interpret_alloc_index,
683             tables,
684             syntax_contexts,
685             expn_data,
686         });
687
688         let total_bytes = self.position();
689
690         if tcx.sess.meta_stats() {
691             let mut zero_bytes = 0;
692             for e in self.opaque.data.iter() {
693                 if *e == 0 {
694                     zero_bytes += 1;
695                 }
696             }
697
698             eprintln!("metadata stats:");
699             eprintln!("             dep bytes: {}", dep_bytes);
700             eprintln!("     lib feature bytes: {}", lib_feature_bytes);
701             eprintln!("       lang item bytes: {}", lang_item_bytes);
702             eprintln!(" diagnostic item bytes: {}", diagnostic_item_bytes);
703             eprintln!("          native bytes: {}", native_lib_bytes);
704             eprintln!("      source_map bytes: {}", source_map_bytes);
705             eprintln!("            impl bytes: {}", impl_bytes);
706             eprintln!("    exp. symbols bytes: {}", exported_symbols_bytes);
707             eprintln!("  def-path table bytes: {}", def_path_table_bytes);
708             eprintln!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
709             eprintln!("             mir bytes: {}", mir_bytes);
710             eprintln!("            item bytes: {}", item_bytes);
711             eprintln!("           table bytes: {}", tables_bytes);
712             eprintln!("         hygiene bytes: {}", hygiene_bytes);
713             eprintln!("            zero bytes: {}", zero_bytes);
714             eprintln!("           total bytes: {}", total_bytes);
715         }
716
717         root
718     }
719 }
720
721 fn should_encode_visibility(def_kind: DefKind) -> bool {
722     match def_kind {
723         DefKind::Mod
724         | DefKind::Struct
725         | DefKind::Union
726         | DefKind::Enum
727         | DefKind::Variant
728         | DefKind::Trait
729         | DefKind::TyAlias
730         | DefKind::ForeignTy
731         | DefKind::TraitAlias
732         | DefKind::AssocTy
733         | DefKind::Fn
734         | DefKind::Const
735         | DefKind::Static
736         | DefKind::Ctor(..)
737         | DefKind::AssocFn
738         | DefKind::AssocConst
739         | DefKind::Macro(..)
740         | DefKind::Use
741         | DefKind::ForeignMod
742         | DefKind::OpaqueTy
743         | DefKind::Impl
744         | DefKind::Field => true,
745         DefKind::TyParam
746         | DefKind::ConstParam
747         | DefKind::LifetimeParam
748         | DefKind::AnonConst
749         | DefKind::GlobalAsm
750         | DefKind::Closure
751         | DefKind::Generator
752         | DefKind::ExternCrate => false,
753     }
754 }
755
756 fn should_encode_stability(def_kind: DefKind) -> bool {
757     match def_kind {
758         DefKind::Mod
759         | DefKind::Ctor(..)
760         | DefKind::Variant
761         | DefKind::Field
762         | DefKind::Struct
763         | DefKind::AssocTy
764         | DefKind::AssocFn
765         | DefKind::AssocConst
766         | DefKind::TyParam
767         | DefKind::ConstParam
768         | DefKind::Static
769         | DefKind::Const
770         | DefKind::Fn
771         | DefKind::ForeignMod
772         | DefKind::TyAlias
773         | DefKind::OpaqueTy
774         | DefKind::Enum
775         | DefKind::Union
776         | DefKind::Impl
777         | DefKind::Trait
778         | DefKind::TraitAlias
779         | DefKind::Macro(..)
780         | DefKind::ForeignTy => true,
781         DefKind::Use
782         | DefKind::LifetimeParam
783         | DefKind::AnonConst
784         | DefKind::GlobalAsm
785         | DefKind::Closure
786         | DefKind::Generator
787         | DefKind::ExternCrate => false,
788     }
789 }
790
791 /// Whether we should encode MIR.
792 ///
793 /// Computing, optimizing and encoding the MIR is a relatively expensive operation.
794 /// We want to avoid this work when not required. Therefore:
795 /// - we only compute `mir_for_ctfe` on items with const-eval semantics;
796 /// - we skip `optimized_mir` for check runs.
797 ///
798 /// Return a pair, resp. for CTFE and for LLVM.
799 fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) {
800     match tcx.def_kind(def_id) {
801         // Constructors
802         DefKind::Ctor(_, _) => {
803             let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
804                 || tcx.sess.opts.debugging_opts.always_encode_mir;
805             (true, mir_opt_base)
806         }
807         // Constants
808         DefKind::AnonConst | DefKind::AssocConst | DefKind::Static | DefKind::Const => {
809             (true, false)
810         }
811         // Full-fledged functions
812         DefKind::AssocFn | DefKind::Fn => {
813             let generics = tcx.generics_of(def_id);
814             let needs_inline = (generics.requires_monomorphization(tcx)
815                 || tcx.codegen_fn_attrs(def_id).requests_inline())
816                 && tcx.sess.opts.output_types.should_codegen();
817             // Only check the presence of the `const` modifier.
818             let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id());
819             let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir;
820             (is_const_fn, needs_inline || always_encode_mir)
821         }
822         // Closures can't be const fn.
823         DefKind::Closure => {
824             let generics = tcx.generics_of(def_id);
825             let needs_inline = (generics.requires_monomorphization(tcx)
826                 || tcx.codegen_fn_attrs(def_id).requests_inline())
827                 && tcx.sess.opts.output_types.should_codegen();
828             let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir;
829             (false, needs_inline || always_encode_mir)
830         }
831         // Generators require optimized MIR to compute layout.
832         DefKind::Generator => (false, true),
833         // The others don't have MIR.
834         _ => (false, false),
835     }
836 }
837
838 impl EncodeContext<'a, 'tcx> {
839     fn encode_def_ids(&mut self) {
840         if self.is_proc_macro {
841             return;
842         }
843         let tcx = self.tcx;
844         let hir = tcx.hir();
845         for local_id in hir.iter_local_def_id() {
846             let def_id = local_id.to_def_id();
847             let def_kind = tcx.opt_def_kind(local_id);
848             let def_kind = if let Some(def_kind) = def_kind { def_kind } else { continue };
849             record!(self.tables.def_kind[def_id] <- match def_kind {
850                 // Replace Ctor by the enclosing object to avoid leaking details in children crates.
851                 DefKind::Ctor(CtorOf::Struct, _) => DefKind::Struct,
852                 DefKind::Ctor(CtorOf::Variant, _) => DefKind::Variant,
853                 def_kind => def_kind,
854             });
855             record!(self.tables.span[def_id] <- tcx.def_span(def_id));
856             record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id));
857             record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
858             if should_encode_visibility(def_kind) {
859                 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
860             }
861             if should_encode_stability(def_kind) {
862                 self.encode_stability(def_id);
863                 self.encode_const_stability(def_id);
864                 self.encode_deprecation(def_id);
865             }
866         }
867     }
868
869     fn encode_variances_of(&mut self, def_id: DefId) {
870         debug!("EncodeContext::encode_variances_of({:?})", def_id);
871         record!(self.tables.variances[def_id] <- self.tcx.variances_of(def_id));
872     }
873
874     fn encode_item_type(&mut self, def_id: DefId) {
875         debug!("EncodeContext::encode_item_type({:?})", def_id);
876         record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id));
877     }
878
879     fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) {
880         let tcx = self.tcx;
881         let variant = &def.variants[index];
882         let def_id = variant.def_id;
883         debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
884
885         let data = VariantData {
886             ctor_kind: variant.ctor_kind,
887             discr: variant.discr,
888             ctor: variant.ctor_def_id.map(|did| did.index),
889             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
890         };
891
892         record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
893         record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
894             assert!(f.did.is_local());
895             f.did.index
896         }));
897         self.encode_ident_span(def_id, variant.ident);
898         self.encode_item_type(def_id);
899         if variant.ctor_kind == CtorKind::Fn {
900             // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
901             if let Some(ctor_def_id) = variant.ctor_def_id {
902                 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
903             }
904             // FIXME(eddyb) is this ever used?
905             self.encode_variances_of(def_id);
906         }
907         self.encode_generics(def_id);
908         self.encode_explicit_predicates(def_id);
909         self.encode_inferred_outlives(def_id);
910     }
911
912     fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) {
913         let tcx = self.tcx;
914         let variant = &def.variants[index];
915         let def_id = variant.ctor_def_id.unwrap();
916         debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
917
918         // FIXME(eddyb) encode only the `CtorKind` for constructors.
919         let data = VariantData {
920             ctor_kind: variant.ctor_kind,
921             discr: variant.discr,
922             ctor: Some(def_id.index),
923             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
924         };
925
926         record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
927         self.encode_item_type(def_id);
928         if variant.ctor_kind == CtorKind::Fn {
929             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
930             self.encode_variances_of(def_id);
931         }
932         self.encode_generics(def_id);
933         self.encode_explicit_predicates(def_id);
934         self.encode_inferred_outlives(def_id);
935     }
936
937     fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) {
938         let tcx = self.tcx;
939         let def_id = local_def_id.to_def_id();
940         debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
941
942         // If we are encoding a proc-macro crates, `encode_info_for_mod` will
943         // only ever get called for the crate root. We still want to encode
944         // the crate root for consistency with other crates (some of the resolver
945         // code uses it). However, we skip encoding anything relating to child
946         // items - we encode information about proc-macros later on.
947         let reexports = if !self.is_proc_macro {
948             match tcx.module_exports(local_def_id) {
949                 Some(exports) => {
950                     let hir = self.tcx.hir();
951                     self.lazy(
952                         exports
953                             .iter()
954                             .map(|export| export.map_id(|id| hir.local_def_id_to_hir_id(id))),
955                     )
956                 }
957                 _ => Lazy::empty(),
958             }
959         } else {
960             Lazy::empty()
961         };
962
963         let data = ModData {
964             reexports,
965             expansion: tcx.hir().definitions().expansion_that_defined(local_def_id),
966         };
967
968         record!(self.tables.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
969         if self.is_proc_macro {
970             record!(self.tables.children[def_id] <- &[]);
971         } else {
972             record!(self.tables.children[def_id] <- md.item_ids.iter().map(|item_id| {
973                 item_id.def_id.local_def_index
974             }));
975         }
976     }
977
978     fn encode_field(
979         &mut self,
980         adt_def: &ty::AdtDef,
981         variant_index: VariantIdx,
982         field_index: usize,
983     ) {
984         let variant = &adt_def.variants[variant_index];
985         let field = &variant.fields[field_index];
986
987         let def_id = field.did;
988         debug!("EncodeContext::encode_field({:?})", def_id);
989
990         record!(self.tables.kind[def_id] <- EntryKind::Field);
991         self.encode_ident_span(def_id, field.ident);
992         self.encode_item_type(def_id);
993         self.encode_generics(def_id);
994         self.encode_explicit_predicates(def_id);
995         self.encode_inferred_outlives(def_id);
996     }
997
998     fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) {
999         debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
1000         let tcx = self.tcx;
1001         let variant = adt_def.non_enum_variant();
1002
1003         let data = VariantData {
1004             ctor_kind: variant.ctor_kind,
1005             discr: variant.discr,
1006             ctor: Some(def_id.index),
1007             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1008         };
1009
1010         record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
1011         self.encode_item_type(def_id);
1012         if variant.ctor_kind == CtorKind::Fn {
1013             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1014             self.encode_variances_of(def_id);
1015         }
1016         self.encode_generics(def_id);
1017         self.encode_explicit_predicates(def_id);
1018         self.encode_inferred_outlives(def_id);
1019     }
1020
1021     fn encode_generics(&mut self, def_id: DefId) {
1022         debug!("EncodeContext::encode_generics({:?})", def_id);
1023         record!(self.tables.generics[def_id] <- self.tcx.generics_of(def_id));
1024     }
1025
1026     fn encode_explicit_predicates(&mut self, def_id: DefId) {
1027         debug!("EncodeContext::encode_explicit_predicates({:?})", def_id);
1028         record!(self.tables.explicit_predicates[def_id] <-
1029             self.tcx.explicit_predicates_of(def_id));
1030     }
1031
1032     fn encode_inferred_outlives(&mut self, def_id: DefId) {
1033         debug!("EncodeContext::encode_inferred_outlives({:?})", def_id);
1034         let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1035         if !inferred_outlives.is_empty() {
1036             record!(self.tables.inferred_outlives[def_id] <- inferred_outlives);
1037         }
1038     }
1039
1040     fn encode_super_predicates(&mut self, def_id: DefId) {
1041         debug!("EncodeContext::encode_super_predicates({:?})", def_id);
1042         record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
1043     }
1044
1045     fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1046         debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1047         let bounds = self.tcx.explicit_item_bounds(def_id);
1048         if !bounds.is_empty() {
1049             record!(self.tables.explicit_item_bounds[def_id] <- bounds);
1050         }
1051     }
1052
1053     fn encode_info_for_trait_item(&mut self, def_id: DefId) {
1054         debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
1055         let tcx = self.tcx;
1056
1057         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1058         let ast_item = tcx.hir().expect_trait_item(hir_id);
1059         let trait_item = tcx.associated_item(def_id);
1060
1061         let container = match trait_item.defaultness {
1062             hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
1063             hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
1064             hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
1065         };
1066
1067         match trait_item.kind {
1068             ty::AssocKind::Const => {
1069                 let rendered = rustc_hir_pretty::to_string(
1070                     &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
1071                     |s| s.print_trait_item(ast_item),
1072                 );
1073                 let rendered_const = self.lazy(RenderedConst(rendered));
1074
1075                 record!(self.tables.kind[def_id] <- EntryKind::AssocConst(
1076                     container,
1077                     Default::default(),
1078                     rendered_const,
1079                 ));
1080             }
1081             ty::AssocKind::Fn => {
1082                 let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind {
1083                     let param_names = match *m {
1084                         hir::TraitFn::Required(ref names) => self.encode_fn_param_names(names),
1085                         hir::TraitFn::Provided(body) => self.encode_fn_param_names_for_body(body),
1086                     };
1087                     FnData {
1088                         asyncness: m_sig.header.asyncness,
1089                         constness: hir::Constness::NotConst,
1090                         param_names,
1091                     }
1092                 } else {
1093                     bug!()
1094                 };
1095                 record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData {
1096                     fn_data,
1097                     container,
1098                     has_self: trait_item.fn_has_self_parameter,
1099                 })));
1100             }
1101             ty::AssocKind::Type => {
1102                 self.encode_explicit_item_bounds(def_id);
1103                 record!(self.tables.kind[def_id] <- EntryKind::AssocType(container));
1104             }
1105         }
1106         self.encode_ident_span(def_id, ast_item.ident);
1107         match trait_item.kind {
1108             ty::AssocKind::Const | ty::AssocKind::Fn => {
1109                 self.encode_item_type(def_id);
1110             }
1111             ty::AssocKind::Type => {
1112                 if trait_item.defaultness.has_value() {
1113                     self.encode_item_type(def_id);
1114                 }
1115             }
1116         }
1117         if trait_item.kind == ty::AssocKind::Fn {
1118             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1119             self.encode_variances_of(def_id);
1120         }
1121         self.encode_generics(def_id);
1122         self.encode_explicit_predicates(def_id);
1123         self.encode_inferred_outlives(def_id);
1124     }
1125
1126     fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1127         debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1128         let tcx = self.tcx;
1129
1130         let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1131         let ast_item = self.tcx.hir().expect_impl_item(hir_id);
1132         let impl_item = self.tcx.associated_item(def_id);
1133
1134         let container = match impl_item.defaultness {
1135             hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
1136             hir::Defaultness::Final => AssocContainer::ImplFinal,
1137             hir::Defaultness::Default { has_value: false } => {
1138                 span_bug!(ast_item.span, "impl items always have values (currently)")
1139             }
1140         };
1141
1142         match impl_item.kind {
1143             ty::AssocKind::Const => {
1144                 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1145                     let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1146
1147                     record!(self.tables.kind[def_id] <- EntryKind::AssocConst(
1148                         container,
1149                         qualifs,
1150                         self.encode_rendered_const_for_body(body_id))
1151                     );
1152                 } else {
1153                     bug!()
1154                 }
1155             }
1156             ty::AssocKind::Fn => {
1157                 let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind {
1158                     FnData {
1159                         asyncness: sig.header.asyncness,
1160                         constness: sig.header.constness,
1161                         param_names: self.encode_fn_param_names_for_body(body),
1162                     }
1163                 } else {
1164                     bug!()
1165                 };
1166                 record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData {
1167                     fn_data,
1168                     container,
1169                     has_self: impl_item.fn_has_self_parameter,
1170                 })));
1171             }
1172             ty::AssocKind::Type => {
1173                 record!(self.tables.kind[def_id] <- EntryKind::AssocType(container));
1174             }
1175         }
1176         self.encode_ident_span(def_id, impl_item.ident);
1177         self.encode_item_type(def_id);
1178         if impl_item.kind == ty::AssocKind::Fn {
1179             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1180             self.encode_variances_of(def_id);
1181         }
1182         self.encode_generics(def_id);
1183         self.encode_explicit_predicates(def_id);
1184         self.encode_inferred_outlives(def_id);
1185     }
1186
1187     fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> {
1188         self.lazy(self.tcx.hir().body_param_names(body_id))
1189     }
1190
1191     fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> {
1192         self.lazy(param_names.iter())
1193     }
1194
1195     fn encode_mir(&mut self) {
1196         if self.is_proc_macro {
1197             return;
1198         }
1199
1200         let mut keys_and_jobs = self
1201             .tcx
1202             .mir_keys(LOCAL_CRATE)
1203             .iter()
1204             .filter_map(|&def_id| {
1205                 let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id);
1206                 if encode_const || encode_opt {
1207                     Some((def_id, encode_const, encode_opt))
1208                 } else {
1209                     None
1210                 }
1211             })
1212             .collect::<Vec<_>>();
1213         // Sort everything to ensure a stable order for diagnotics.
1214         keys_and_jobs.sort_by_key(|&(def_id, _, _)| def_id);
1215         for (def_id, encode_const, encode_opt) in keys_and_jobs.into_iter() {
1216             debug_assert!(encode_const || encode_opt);
1217
1218             debug!("EntryBuilder::encode_mir({:?})", def_id);
1219             if encode_opt {
1220                 record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1221             }
1222             if encode_const {
1223                 record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id));
1224
1225                 let abstract_const = self.tcx.mir_abstract_const(def_id);
1226                 if let Ok(Some(abstract_const)) = abstract_const {
1227                     record!(self.tables.mir_abstract_consts[def_id.to_def_id()] <- abstract_const);
1228                 }
1229             }
1230             record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1231
1232             let unused = self.tcx.unused_generic_params(def_id);
1233             if !unused.is_empty() {
1234                 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1235             }
1236         }
1237     }
1238
1239     // Encodes the inherent implementations of a structure, enumeration, or trait.
1240     fn encode_inherent_implementations(&mut self, def_id: DefId) {
1241         debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1242         let implementations = self.tcx.inherent_impls(def_id);
1243         if !implementations.is_empty() {
1244             record!(self.tables.inherent_impls[def_id] <- implementations.iter().map(|&def_id| {
1245                 assert!(def_id.is_local());
1246                 def_id.index
1247             }));
1248         }
1249     }
1250
1251     fn encode_stability(&mut self, def_id: DefId) {
1252         debug!("EncodeContext::encode_stability({:?})", def_id);
1253
1254         // The query lookup can take a measurable amount of time in crates with many items. Check if
1255         // the stability attributes are even enabled before using their queries.
1256         if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1257             if let Some(stab) = self.tcx.lookup_stability(def_id) {
1258                 record!(self.tables.stability[def_id] <- stab)
1259             }
1260         }
1261     }
1262
1263     fn encode_const_stability(&mut self, def_id: DefId) {
1264         debug!("EncodeContext::encode_const_stability({:?})", def_id);
1265
1266         // The query lookup can take a measurable amount of time in crates with many items. Check if
1267         // the stability attributes are even enabled before using their queries.
1268         if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1269             if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1270                 record!(self.tables.const_stability[def_id] <- stab)
1271             }
1272         }
1273     }
1274
1275     fn encode_deprecation(&mut self, def_id: DefId) {
1276         debug!("EncodeContext::encode_deprecation({:?})", def_id);
1277         if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1278             record!(self.tables.deprecation[def_id] <- depr);
1279         }
1280     }
1281
1282     fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1283         let hir = self.tcx.hir();
1284         let body = hir.body(body_id);
1285         let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1286             s.print_expr(&body.value)
1287         });
1288         let rendered_const = &RenderedConst(rendered);
1289         self.lazy(rendered_const)
1290     }
1291
1292     fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1293         let tcx = self.tcx;
1294
1295         debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1296
1297         self.encode_ident_span(def_id, item.ident);
1298
1299         let entry_kind = match item.kind {
1300             hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic,
1301             hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic,
1302             hir::ItemKind::Const(_, body_id) => {
1303                 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1304                 EntryKind::Const(qualifs, self.encode_rendered_const_for_body(body_id))
1305             }
1306             hir::ItemKind::Fn(ref sig, .., body) => {
1307                 let data = FnData {
1308                     asyncness: sig.header.asyncness,
1309                     constness: sig.header.constness,
1310                     param_names: self.encode_fn_param_names_for_body(body),
1311                 };
1312
1313                 EntryKind::Fn(self.lazy(data))
1314             }
1315             hir::ItemKind::Mod(ref m) => {
1316                 return self.encode_info_for_mod(item.def_id, m);
1317             }
1318             hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod,
1319             hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1320             hir::ItemKind::TyAlias(..) => EntryKind::Type,
1321             hir::ItemKind::OpaqueTy(..) => {
1322                 self.encode_explicit_item_bounds(def_id);
1323                 EntryKind::OpaqueTy
1324             }
1325             hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1326             hir::ItemKind::Struct(ref struct_def, _) => {
1327                 let adt_def = self.tcx.adt_def(def_id);
1328                 let variant = adt_def.non_enum_variant();
1329
1330                 // Encode def_ids for each field and method
1331                 // for methods, write all the stuff get_trait_method
1332                 // needs to know
1333                 let ctor = struct_def
1334                     .ctor_hir_id()
1335                     .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index);
1336
1337                 EntryKind::Struct(
1338                     self.lazy(VariantData {
1339                         ctor_kind: variant.ctor_kind,
1340                         discr: variant.discr,
1341                         ctor,
1342                         is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1343                     }),
1344                     adt_def.repr,
1345                 )
1346             }
1347             hir::ItemKind::Union(..) => {
1348                 let adt_def = self.tcx.adt_def(def_id);
1349                 let variant = adt_def.non_enum_variant();
1350
1351                 EntryKind::Union(
1352                     self.lazy(VariantData {
1353                         ctor_kind: variant.ctor_kind,
1354                         discr: variant.discr,
1355                         ctor: None,
1356                         is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1357                     }),
1358                     adt_def.repr,
1359                 )
1360             }
1361             hir::ItemKind::Impl(hir::Impl { defaultness, .. }) => {
1362                 let trait_ref = self.tcx.impl_trait_ref(def_id);
1363                 let polarity = self.tcx.impl_polarity(def_id);
1364                 let parent = if let Some(trait_ref) = trait_ref {
1365                     let trait_def = self.tcx.trait_def(trait_ref.def_id);
1366                     trait_def.ancestors(self.tcx, def_id).ok().and_then(|mut an| {
1367                         an.nth(1).and_then(|node| match node {
1368                             specialization_graph::Node::Impl(parent) => Some(parent),
1369                             _ => None,
1370                         })
1371                     })
1372                 } else {
1373                     None
1374                 };
1375
1376                 // if this is an impl of `CoerceUnsized`, create its
1377                 // "unsized info", else just store None
1378                 let coerce_unsized_info = trait_ref.and_then(|t| {
1379                     if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1380                         Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1381                     } else {
1382                         None
1383                     }
1384                 });
1385
1386                 let data =
1387                     ImplData { polarity, defaultness, parent_impl: parent, coerce_unsized_info };
1388
1389                 EntryKind::Impl(self.lazy(data))
1390             }
1391             hir::ItemKind::Trait(..) => {
1392                 let trait_def = self.tcx.trait_def(def_id);
1393                 let data = TraitData {
1394                     unsafety: trait_def.unsafety,
1395                     paren_sugar: trait_def.paren_sugar,
1396                     has_auto_impl: self.tcx.trait_is_auto(def_id),
1397                     is_marker: trait_def.is_marker,
1398                     specialization_kind: trait_def.specialization_kind,
1399                 };
1400
1401                 EntryKind::Trait(self.lazy(data))
1402             }
1403             hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1404             hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {
1405                 bug!("cannot encode info for item {:?}", item)
1406             }
1407         };
1408         record!(self.tables.kind[def_id] <- entry_kind);
1409         // FIXME(eddyb) there should be a nicer way to do this.
1410         match item.kind {
1411             hir::ItemKind::ForeignMod { items, .. } => record!(self.tables.children[def_id] <-
1412                 items
1413                     .iter()
1414                     .map(|foreign_item| foreign_item.id.def_id.local_def_index)
1415             ),
1416             hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <-
1417                 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1418                     assert!(v.def_id.is_local());
1419                     v.def_id.index
1420                 })
1421             ),
1422             hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1423                 record!(self.tables.children[def_id] <-
1424                     self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1425                         assert!(f.did.is_local());
1426                         f.did.index
1427                     })
1428                 )
1429             }
1430             hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1431                 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1432                 record!(self.tables.children[def_id] <-
1433                     associated_item_def_ids.iter().map(|&def_id| {
1434                         assert!(def_id.is_local());
1435                         def_id.index
1436                     })
1437                 );
1438             }
1439             _ => {}
1440         }
1441         match item.kind {
1442             hir::ItemKind::Static(..)
1443             | hir::ItemKind::Const(..)
1444             | hir::ItemKind::Fn(..)
1445             | hir::ItemKind::TyAlias(..)
1446             | hir::ItemKind::OpaqueTy(..)
1447             | hir::ItemKind::Enum(..)
1448             | hir::ItemKind::Struct(..)
1449             | hir::ItemKind::Union(..)
1450             | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1451             _ => {}
1452         }
1453         if let hir::ItemKind::Fn(..) = item.kind {
1454             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1455         }
1456         if let hir::ItemKind::Impl { .. } = item.kind {
1457             if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1458                 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1459             }
1460         }
1461         self.encode_inherent_implementations(def_id);
1462         match item.kind {
1463             hir::ItemKind::Enum(..)
1464             | hir::ItemKind::Struct(..)
1465             | hir::ItemKind::Union(..)
1466             | hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1467             _ => {}
1468         }
1469         match item.kind {
1470             hir::ItemKind::Static(..)
1471             | hir::ItemKind::Const(..)
1472             | hir::ItemKind::Fn(..)
1473             | hir::ItemKind::TyAlias(..)
1474             | hir::ItemKind::Enum(..)
1475             | hir::ItemKind::Struct(..)
1476             | hir::ItemKind::Union(..)
1477             | hir::ItemKind::Impl { .. }
1478             | hir::ItemKind::OpaqueTy(..)
1479             | hir::ItemKind::Trait(..)
1480             | hir::ItemKind::TraitAlias(..) => {
1481                 self.encode_generics(def_id);
1482                 self.encode_explicit_predicates(def_id);
1483                 self.encode_inferred_outlives(def_id);
1484             }
1485             _ => {}
1486         }
1487         match item.kind {
1488             hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => {
1489                 self.encode_super_predicates(def_id);
1490             }
1491             _ => {}
1492         }
1493     }
1494
1495     /// Serialize the text of exported macros
1496     fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) {
1497         let def_id = macro_def.def_id.to_def_id();
1498         record!(self.tables.kind[def_id] <- EntryKind::MacroDef(self.lazy(macro_def.ast.clone())));
1499         self.encode_ident_span(def_id, macro_def.ident);
1500     }
1501
1502     fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1503         record!(self.tables.kind[def_id] <- kind);
1504         if encode_type {
1505             self.encode_item_type(def_id);
1506         }
1507     }
1508
1509     fn encode_info_for_closure(&mut self, def_id: LocalDefId) {
1510         debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1511
1512         // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1513         // including on the signature, which is inferred in `typeck.
1514         let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1515         let ty = self.tcx.typeck(def_id).node_type(hir_id);
1516
1517         match ty.kind() {
1518             ty::Generator(..) => {
1519                 let data = self.tcx.generator_kind(def_id).unwrap();
1520                 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Generator(data));
1521             }
1522
1523             ty::Closure(..) => {
1524                 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Closure);
1525             }
1526
1527             _ => bug!("closure that is neither generator nor closure"),
1528         }
1529         self.encode_item_type(def_id.to_def_id());
1530         if let ty::Closure(def_id, substs) = *ty.kind() {
1531             record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1532         }
1533         self.encode_generics(def_id.to_def_id());
1534     }
1535
1536     fn encode_info_for_anon_const(&mut self, def_id: LocalDefId) {
1537         debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1538         let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1539         let body_id = self.tcx.hir().body_owned_by(id);
1540         let const_data = self.encode_rendered_const_for_body(body_id);
1541         let qualifs = self.tcx.mir_const_qualif(def_id);
1542
1543         record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data));
1544         self.encode_item_type(def_id.to_def_id());
1545         self.encode_generics(def_id.to_def_id());
1546         self.encode_explicit_predicates(def_id.to_def_id());
1547         self.encode_inferred_outlives(def_id.to_def_id());
1548     }
1549
1550     fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
1551         empty_proc_macro!(self);
1552         let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1553         self.lazy(used_libraries.iter().cloned())
1554     }
1555
1556     fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1557         empty_proc_macro!(self);
1558         let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1559         self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned())
1560     }
1561
1562     fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable) {
1563         let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1564         let mut expn_data_table: TableBuilder<_, _> = Default::default();
1565
1566         let _: Result<(), !> = self.hygiene_ctxt.encode(
1567             &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table),
1568             |(this, syntax_contexts, _), index, ctxt_data| {
1569                 syntax_contexts.set(index, this.lazy(ctxt_data));
1570                 Ok(())
1571             },
1572             |(this, _, expn_data_table), index, expn_data| {
1573                 expn_data_table.set(index, this.lazy(expn_data));
1574                 Ok(())
1575             },
1576         );
1577
1578         (syntax_contexts.encode(&mut self.opaque), expn_data_table.encode(&mut self.opaque))
1579     }
1580
1581     fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1582         let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1583         if is_proc_macro {
1584             let tcx = self.tcx;
1585             let hir = tcx.hir();
1586
1587             let proc_macro_decls_static = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap().index;
1588             let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied();
1589             let macros = self.lazy(hir.krate().proc_macros.iter().map(|p| p.owner.local_def_index));
1590
1591             record!(self.tables.def_kind[LOCAL_CRATE.as_def_id()] <- DefKind::Mod);
1592             record!(self.tables.span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1593             record!(self.tables.attributes[LOCAL_CRATE.as_def_id()] <- tcx.get_attrs(LOCAL_CRATE.as_def_id()));
1594             record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- tcx.visibility(LOCAL_CRATE.as_def_id()));
1595             if let Some(stability) = stability {
1596                 record!(self.tables.stability[LOCAL_CRATE.as_def_id()] <- stability);
1597             }
1598             self.encode_deprecation(LOCAL_CRATE.as_def_id());
1599
1600             // Normally, this information is encoded when we walk the items
1601             // defined in this crate. However, we skip doing that for proc-macro crates,
1602             // so we manually encode just the information that we need
1603             for proc_macro in &hir.krate().proc_macros {
1604                 let id = proc_macro.owner.local_def_index;
1605                 let mut name = hir.name(*proc_macro);
1606                 let span = hir.span(*proc_macro);
1607                 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1608                 // so downstream crates need access to them.
1609                 let attrs = hir.attrs(*proc_macro);
1610                 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1611                     MacroKind::Bang
1612                 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1613                     MacroKind::Attr
1614                 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1615                     // This unwrap chain should have been checked by the proc-macro harness.
1616                     name = attr.meta_item_list().unwrap()[0]
1617                         .meta_item()
1618                         .unwrap()
1619                         .ident()
1620                         .unwrap()
1621                         .name;
1622                     MacroKind::Derive
1623                 } else {
1624                     bug!("Unknown proc-macro type for item {:?}", id);
1625                 };
1626
1627                 let mut def_key = self.tcx.hir().def_key(proc_macro.owner);
1628                 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1629
1630                 let def_id = DefId::local(id);
1631                 record!(self.tables.def_kind[def_id] <- DefKind::Macro(macro_kind));
1632                 record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind));
1633                 record!(self.tables.attributes[def_id] <- attrs);
1634                 record!(self.tables.def_keys[def_id] <- def_key);
1635                 record!(self.tables.ident_span[def_id] <- span);
1636                 record!(self.tables.span[def_id] <- span);
1637                 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1638                 if let Some(stability) = stability {
1639                     record!(self.tables.stability[def_id] <- stability);
1640                 }
1641             }
1642
1643             Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1644         } else {
1645             None
1646         }
1647     }
1648
1649     fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1650         empty_proc_macro!(self);
1651         let crates = self.tcx.crates();
1652
1653         let mut deps = crates
1654             .iter()
1655             .map(|&cnum| {
1656                 let dep = CrateDep {
1657                     name: self.tcx.original_crate_name(cnum),
1658                     hash: self.tcx.crate_hash(cnum),
1659                     host_hash: self.tcx.crate_host_hash(cnum),
1660                     kind: self.tcx.dep_kind(cnum),
1661                     extra_filename: self.tcx.extra_filename(cnum),
1662                 };
1663                 (cnum, dep)
1664             })
1665             .collect::<Vec<_>>();
1666
1667         deps.sort_by_key(|&(cnum, _)| cnum);
1668
1669         {
1670             // Sanity-check the crate numbers
1671             let mut expected_cnum = 1;
1672             for &(n, _) in &deps {
1673                 assert_eq!(n, CrateNum::new(expected_cnum));
1674                 expected_cnum += 1;
1675             }
1676         }
1677
1678         // We're just going to write a list of crate 'name-hash-version's, with
1679         // the assumption that they are numbered 1 to n.
1680         // FIXME (#2166): This is not nearly enough to support correct versioning
1681         // but is enough to get transitive crate dependencies working.
1682         self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1683     }
1684
1685     fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> {
1686         empty_proc_macro!(self);
1687         let tcx = self.tcx;
1688         let lib_features = tcx.lib_features();
1689         self.lazy(lib_features.to_vec())
1690     }
1691
1692     fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1693         empty_proc_macro!(self);
1694         let tcx = self.tcx;
1695         let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1696         self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1697     }
1698
1699     fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1700         empty_proc_macro!(self);
1701         let tcx = self.tcx;
1702         let lang_items = tcx.lang_items();
1703         let lang_items = lang_items.items().iter();
1704         self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1705             if let Some(def_id) = opt_def_id {
1706                 if def_id.is_local() {
1707                     return Some((def_id.index, i));
1708                 }
1709             }
1710             None
1711         }))
1712     }
1713
1714     fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1715         empty_proc_macro!(self);
1716         let tcx = self.tcx;
1717         self.lazy(&tcx.lang_items().missing)
1718     }
1719
1720     /// Encodes an index, mapping each trait to its (local) implementations.
1721     fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1722         empty_proc_macro!(self);
1723         debug!("EncodeContext::encode_impls()");
1724         let tcx = self.tcx;
1725         let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() };
1726         tcx.hir().krate().visit_all_item_likes(&mut visitor);
1727
1728         let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1729
1730         // Bring everything into deterministic order for hashing
1731         all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1732
1733         let all_impls: Vec<_> = all_impls
1734             .into_iter()
1735             .map(|(trait_def_id, mut impls)| {
1736                 // Bring everything into deterministic order for hashing
1737                 impls.sort_by_cached_key(|&(index, _)| {
1738                     tcx.hir().definitions().def_path_hash(LocalDefId { local_def_index: index })
1739                 });
1740
1741                 TraitImpls {
1742                     trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1743                     impls: self.lazy(&impls),
1744                 }
1745             })
1746             .collect();
1747
1748         self.lazy(&all_impls)
1749     }
1750
1751     // Encodes all symbols exported from this crate into the metadata.
1752     //
1753     // This pass is seeded off the reachability list calculated in the
1754     // middle::reachable module but filters out items that either don't have a
1755     // symbol associated with them (they weren't translated) or if they're an FFI
1756     // definition (as that's not defined in this crate).
1757     fn encode_exported_symbols(
1758         &mut self,
1759         exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1760     ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1761         empty_proc_macro!(self);
1762         // The metadata symbol name is special. It should not show up in
1763         // downstream crates.
1764         let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1765
1766         self.lazy(
1767             exported_symbols
1768                 .iter()
1769                 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1770                     ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1771                     _ => true,
1772                 })
1773                 .cloned(),
1774         )
1775     }
1776
1777     fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1778         empty_proc_macro!(self);
1779         let formats = self.tcx.dependency_formats(LOCAL_CRATE);
1780         for (ty, arr) in formats.iter() {
1781             if *ty != CrateType::Dylib {
1782                 continue;
1783             }
1784             return self.lazy(arr.iter().map(|slot| match *slot {
1785                 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1786
1787                 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1788                 Linkage::Static => Some(LinkagePreference::RequireStatic),
1789             }));
1790         }
1791         Lazy::empty()
1792     }
1793
1794     fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1795         let tcx = self.tcx;
1796
1797         debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1798
1799         match nitem.kind {
1800             hir::ForeignItemKind::Fn(_, ref names, _) => {
1801                 let data = FnData {
1802                     asyncness: hir::IsAsync::NotAsync,
1803                     constness: if self.tcx.is_const_fn_raw(def_id) {
1804                         hir::Constness::Const
1805                     } else {
1806                         hir::Constness::NotConst
1807                     },
1808                     param_names: self.encode_fn_param_names(names),
1809                 };
1810                 record!(self.tables.kind[def_id] <- EntryKind::ForeignFn(self.lazy(data)));
1811             }
1812             hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => {
1813                 record!(self.tables.kind[def_id] <- EntryKind::ForeignMutStatic);
1814             }
1815             hir::ForeignItemKind::Static(_, hir::Mutability::Not) => {
1816                 record!(self.tables.kind[def_id] <- EntryKind::ForeignImmStatic);
1817             }
1818             hir::ForeignItemKind::Type => {
1819                 record!(self.tables.kind[def_id] <- EntryKind::ForeignType);
1820             }
1821         }
1822         self.encode_ident_span(def_id, nitem.ident);
1823         self.encode_item_type(def_id);
1824         self.encode_inherent_implementations(def_id);
1825         if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1826             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1827             self.encode_variances_of(def_id);
1828         }
1829         self.encode_generics(def_id);
1830         self.encode_explicit_predicates(def_id);
1831         self.encode_inferred_outlives(def_id);
1832     }
1833 }
1834
1835 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1836 impl Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1837     type Map = Map<'tcx>;
1838
1839     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1840         NestedVisitorMap::OnlyBodies(self.tcx.hir())
1841     }
1842     fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1843         intravisit::walk_expr(self, ex);
1844         self.encode_info_for_expr(ex);
1845     }
1846     fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1847         intravisit::walk_anon_const(self, c);
1848         let def_id = self.tcx.hir().local_def_id(c.hir_id);
1849         self.encode_info_for_anon_const(def_id);
1850     }
1851     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1852         intravisit::walk_item(self, item);
1853         match item.kind {
1854             hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1855             _ => self.encode_info_for_item(item.def_id.to_def_id(), item),
1856         }
1857         self.encode_addl_info_for_item(item);
1858     }
1859     fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1860         intravisit::walk_foreign_item(self, ni);
1861         self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni);
1862     }
1863     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1864         intravisit::walk_generics(self, generics);
1865         self.encode_info_for_generics(generics);
1866     }
1867     fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) {
1868         self.encode_info_for_macro_def(macro_def);
1869     }
1870 }
1871
1872 impl EncodeContext<'a, 'tcx> {
1873     fn encode_fields(&mut self, adt_def: &ty::AdtDef) {
1874         for (variant_index, variant) in adt_def.variants.iter_enumerated() {
1875             for (field_index, _field) in variant.fields.iter().enumerate() {
1876                 self.encode_field(adt_def, variant_index, field_index);
1877             }
1878         }
1879     }
1880
1881     fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1882         for param in generics.params {
1883             let def_id = self.tcx.hir().local_def_id(param.hir_id);
1884             match param.kind {
1885                 GenericParamKind::Lifetime { .. } => continue,
1886                 GenericParamKind::Type { default, .. } => {
1887                     self.encode_info_for_generic_param(
1888                         def_id.to_def_id(),
1889                         EntryKind::TypeParam,
1890                         default.is_some(),
1891                     );
1892                 }
1893                 GenericParamKind::Const { .. } => {
1894                     self.encode_info_for_generic_param(
1895                         def_id.to_def_id(),
1896                         EntryKind::ConstParam,
1897                         true,
1898                     );
1899                     // FIXME(const_generics_defaults)
1900                 }
1901             }
1902         }
1903     }
1904
1905     fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1906         if let hir::ExprKind::Closure(..) = expr.kind {
1907             let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1908             self.encode_info_for_closure(def_id);
1909         }
1910     }
1911
1912     fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) {
1913         record!(self.tables.ident_span[def_id] <- ident.span);
1914     }
1915
1916     /// In some cases, along with the item itself, we also
1917     /// encode some sub-items. Usually we want some info from the item
1918     /// so it's easier to do that here then to wait until we would encounter
1919     /// normally in the visitor walk.
1920     fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1921         match item.kind {
1922             hir::ItemKind::Static(..)
1923             | hir::ItemKind::Const(..)
1924             | hir::ItemKind::Fn(..)
1925             | hir::ItemKind::Mod(..)
1926             | hir::ItemKind::ForeignMod { .. }
1927             | hir::ItemKind::GlobalAsm(..)
1928             | hir::ItemKind::ExternCrate(..)
1929             | hir::ItemKind::Use(..)
1930             | hir::ItemKind::TyAlias(..)
1931             | hir::ItemKind::OpaqueTy(..)
1932             | hir::ItemKind::TraitAlias(..) => {
1933                 // no sub-item recording needed in these cases
1934             }
1935             hir::ItemKind::Enum(..) => {
1936                 let def = self.tcx.adt_def(item.def_id.to_def_id());
1937                 self.encode_fields(def);
1938
1939                 for (i, variant) in def.variants.iter_enumerated() {
1940                     self.encode_enum_variant_info(def, i);
1941
1942                     if let Some(_ctor_def_id) = variant.ctor_def_id {
1943                         self.encode_enum_variant_ctor(def, i);
1944                     }
1945                 }
1946             }
1947             hir::ItemKind::Struct(ref struct_def, _) => {
1948                 let def = self.tcx.adt_def(item.def_id.to_def_id());
1949                 self.encode_fields(def);
1950
1951                 // If the struct has a constructor, encode it.
1952                 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1953                     let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1954                     self.encode_struct_ctor(def, ctor_def_id.to_def_id());
1955                 }
1956             }
1957             hir::ItemKind::Union(..) => {
1958                 let def = self.tcx.adt_def(item.def_id.to_def_id());
1959                 self.encode_fields(def);
1960             }
1961             hir::ItemKind::Impl { .. } => {
1962                 for &trait_item_def_id in
1963                     self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
1964                 {
1965                     self.encode_info_for_impl_item(trait_item_def_id);
1966                 }
1967             }
1968             hir::ItemKind::Trait(..) => {
1969                 for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
1970                 {
1971                     self.encode_info_for_trait_item(item_def_id);
1972                 }
1973             }
1974         }
1975     }
1976 }
1977
1978 struct ImplVisitor<'tcx> {
1979     tcx: TyCtxt<'tcx>,
1980     impls: FxHashMap<DefId, Vec<(DefIndex, Option<ty::fast_reject::SimplifiedType>)>>,
1981 }
1982
1983 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1984     fn visit_item(&mut self, item: &hir::Item<'_>) {
1985         if let hir::ItemKind::Impl { .. } = item.kind {
1986             if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) {
1987                 let simplified_self_ty =
1988                     ty::fast_reject::simplify_type(self.tcx, trait_ref.self_ty(), false);
1989
1990                 self.impls
1991                     .entry(trait_ref.def_id)
1992                     .or_default()
1993                     .push((item.def_id.local_def_index, simplified_self_ty));
1994             }
1995         }
1996     }
1997
1998     fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
1999
2000     fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
2001         // handled in `visit_item` above
2002     }
2003
2004     fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {}
2005 }
2006
2007 /// Used to prefetch queries which will be needed later by metadata encoding.
2008 /// Only a subset of the queries are actually prefetched to keep this code smaller.
2009 fn prefetch_mir(tcx: TyCtxt<'_>) {
2010     if !tcx.sess.opts.output_types.should_codegen() {
2011         // We won't emit MIR, so don't prefetch it.
2012         return;
2013     }
2014
2015     par_iter(tcx.mir_keys(LOCAL_CRATE)).for_each(|&def_id| {
2016         let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
2017
2018         if encode_const {
2019             tcx.ensure().mir_for_ctfe(def_id);
2020         }
2021         if encode_opt {
2022             tcx.ensure().optimized_mir(def_id);
2023         }
2024         if encode_opt || encode_const {
2025             tcx.ensure().promoted_mir(def_id);
2026         }
2027     })
2028 }
2029
2030 // NOTE(eddyb) The following comment was preserved for posterity, even
2031 // though it's no longer relevant as EBML (which uses nested & tagged
2032 // "documents") was replaced with a scheme that can't go out of bounds.
2033 //
2034 // And here we run into yet another obscure archive bug: in which metadata
2035 // loaded from archives may have trailing garbage bytes. Awhile back one of
2036 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2037 // and opt) by having ebml generate an out-of-bounds panic when looking at
2038 // metadata.
2039 //
2040 // Upon investigation it turned out that the metadata file inside of an rlib
2041 // (and ar archive) was being corrupted. Some compilations would generate a
2042 // metadata file which would end in a few extra bytes, while other
2043 // compilations would not have these extra bytes appended to the end. These
2044 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2045 // being interpreted causing the out-of-bounds.
2046 //
2047 // The root cause of why these extra bytes were appearing was never
2048 // discovered, and in the meantime the solution we're employing is to insert
2049 // the length of the metadata to the start of the metadata. Later on this
2050 // will allow us to slice the metadata to the precise length that we just
2051 // generated regardless of trailing bytes that end up in it.
2052
2053 pub(super) fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
2054     // Since encoding metadata is not in a query, and nothing is cached,
2055     // there's no need to do dep-graph tracking for any of it.
2056     tcx.dep_graph.assert_ignored();
2057
2058     join(
2059         || encode_metadata_impl(tcx),
2060         || {
2061             if tcx.sess.threads() == 1 {
2062                 return;
2063             }
2064             // Prefetch some queries used by metadata encoding.
2065             // This is not necessary for correctness, but is only done for performance reasons.
2066             // It can be removed if it turns out to cause trouble or be detrimental to performance.
2067             join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2068         },
2069     )
2070     .0
2071 }
2072
2073 fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata {
2074     let mut encoder = opaque::Encoder::new(vec![]);
2075     encoder.emit_raw_bytes(METADATA_HEADER);
2076
2077     // Will be filled with the root position after encoding everything.
2078     encoder.emit_raw_bytes(&[0, 0, 0, 0]);
2079
2080     let source_map_files = tcx.sess.source_map().files();
2081     let source_file_cache = (source_map_files[0].clone(), 0);
2082     let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len()));
2083     drop(source_map_files);
2084
2085     let hygiene_ctxt = HygieneEncodeContext::default();
2086
2087     let mut ecx = EncodeContext {
2088         opaque: encoder,
2089         tcx,
2090         feat: tcx.features(),
2091         tables: Default::default(),
2092         lazy_state: LazyState::NoNode,
2093         type_shorthands: Default::default(),
2094         predicate_shorthands: Default::default(),
2095         source_file_cache,
2096         interpret_allocs: Default::default(),
2097         required_source_files,
2098         is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2099         hygiene_ctxt: &hygiene_ctxt,
2100     };
2101
2102     // Encode the rustc version string in a predictable location.
2103     rustc_version().encode(&mut ecx).unwrap();
2104
2105     // Encode all the entries and extra information in the crate,
2106     // culminating in the `CrateRoot` which points to all of it.
2107     let root = ecx.encode_crate_root();
2108
2109     let mut result = ecx.opaque.into_inner();
2110
2111     // Encode the root position.
2112     let header = METADATA_HEADER.len();
2113     let pos = root.position.get();
2114     result[header + 0] = (pos >> 24) as u8;
2115     result[header + 1] = (pos >> 16) as u8;
2116     result[header + 2] = (pos >> 8) as u8;
2117     result[header + 3] = (pos >> 0) as u8;
2118
2119     EncodedMetadata { raw_data: result }
2120 }