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