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