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