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