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