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