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