]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/encoder.rs
a0f17a55a8756965f72d5448b80dd8020d760f9a
[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;
37 use syntax_pos::{self, hygiene, 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_raw_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, "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: hygiene::default_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, "compiler_builtins"),
500             needs_allocator: attr::contains_name(&attrs, "needs_allocator"),
501             needs_panic_runtime: attr::contains_name(&attrs, "needs_panic_runtime"),
502             no_builtins: attr::contains_name(&attrs, "no_builtins"),
503             panic_runtime: attr::contains_name(&attrs, "panic_runtime"),
504             profiler_runtime: attr::contains_name(&attrs, "profiler_runtime"),
505             sanitizer_runtime: attr::contains_name(&attrs, "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             ctor: variant.ctor_def_id.map(|did| did.index),
590             ctor_sig: None,
591         };
592
593         let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
594         let enum_vis = &tcx.hir().expect_item_by_hir_id(enum_id).vis;
595
596         Entry {
597             kind: EntryKind::Variant(self.lazy(&data)),
598             visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
599             span: self.lazy(&tcx.def_span(def_id)),
600             attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
601             children: self.lazy_seq(variant.fields.iter().map(|f| {
602                 assert!(f.did.is_local());
603                 f.did.index
604             })),
605             stability: self.encode_stability(def_id),
606             deprecation: self.encode_deprecation(def_id),
607
608             ty: Some(self.encode_item_type(def_id)),
609             inherent_impls: LazySeq::empty(),
610             variances: if variant.ctor_kind == CtorKind::Fn {
611                 self.encode_variances_of(def_id)
612             } else {
613                 LazySeq::empty()
614             },
615             generics: Some(self.encode_generics(def_id)),
616             predicates: Some(self.encode_predicates(def_id)),
617             predicates_defined_on: None,
618
619             mir: self.encode_optimized_mir(def_id),
620         }
621     }
622
623     /// Encode the constructor for the given variant of the given ADT. See
624     /// `encode_enum_variant_info` for an explanation about why the index is untracked.
625     fn encode_enum_variant_ctor(
626         &mut self,
627         (enum_did, Untracked(index)): (DefId, Untracked<VariantIdx>),
628     ) -> Entry<'tcx> {
629         let tcx = self.tcx;
630         let def = tcx.adt_def(enum_did);
631         let variant = &def.variants[index];
632         let def_id = variant.ctor_def_id.unwrap();
633         debug!("IsolatedEncoder::encode_enum_variant_ctor({:?})", def_id);
634
635         let data = VariantData {
636             ctor_kind: variant.ctor_kind,
637             discr: variant.discr,
638             ctor: Some(def_id.index),
639             ctor_sig: if variant.ctor_kind == CtorKind::Fn {
640                 Some(self.lazy(&tcx.fn_sig(def_id)))
641             } else {
642                 None
643             }
644         };
645
646         // Variant constructors have the same visibility as the parent enums, unless marked as
647         // non-exhaustive, in which case they are lowered to `pub(crate)`.
648         let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
649         let enum_vis = &tcx.hir().expect_item_by_hir_id(enum_id).vis;
650         let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx);
651         if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public {
652             ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
653         }
654
655         Entry {
656             kind: EntryKind::Variant(self.lazy(&data)),
657             visibility: self.lazy(&ctor_vis),
658             span: self.lazy(&tcx.def_span(def_id)),
659             attributes: LazySeq::empty(),
660             children: LazySeq::empty(),
661             stability: self.encode_stability(def_id),
662             deprecation: self.encode_deprecation(def_id),
663
664             ty: Some(self.encode_item_type(def_id)),
665             inherent_impls: LazySeq::empty(),
666             variances: if variant.ctor_kind == CtorKind::Fn {
667                 self.encode_variances_of(def_id)
668             } else {
669                 LazySeq::empty()
670             },
671             generics: Some(self.encode_generics(def_id)),
672             predicates: Some(self.encode_predicates(def_id)),
673             predicates_defined_on: None,
674
675             mir: self.encode_optimized_mir(def_id),
676         }
677     }
678
679     fn encode_info_for_mod(&mut self,
680                            FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
681                                                                  &[ast::Attribute],
682                                                                  &hir::Visibility)>)
683                            -> Entry<'tcx> {
684         let tcx = self.tcx;
685         let def_id = tcx.hir().local_def_id_from_hir_id(id);
686         debug!("IsolatedEncoder::encode_info_for_mod({:?})", def_id);
687
688         let data = ModData {
689             reexports: match tcx.module_exports(def_id) {
690                 Some(ref exports) => self.lazy_seq_from_slice(exports.as_slice()),
691                 _ => LazySeq::empty(),
692             },
693         };
694
695         Entry {
696             kind: EntryKind::Mod(self.lazy(&data)),
697             visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
698             span: self.lazy(&tcx.def_span(def_id)),
699             attributes: self.encode_attributes(attrs),
700             children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
701                 tcx.hir().local_def_id_from_hir_id(item_id.id).index
702             })),
703             stability: self.encode_stability(def_id),
704             deprecation: self.encode_deprecation(def_id),
705
706             ty: None,
707             inherent_impls: LazySeq::empty(),
708             variances: LazySeq::empty(),
709             generics: None,
710             predicates: None,
711             predicates_defined_on: None,
712
713             mir: None
714         }
715     }
716
717     /// Encode data for the given field of the given variant of the
718     /// given ADT. The indices of the variant/field are untracked:
719     /// this is ok because we will have to lookup the adt-def by its
720     /// id, and that gives us the right to access any information in
721     /// the adt-def (including, e.g., the length of the various
722     /// vectors).
723     fn encode_field(&mut self,
724                     (adt_def_id, Untracked((variant_index, field_index))): (DefId,
725                                                                             Untracked<(VariantIdx,
726                                                                                        usize)>))
727                     -> Entry<'tcx> {
728         let tcx = self.tcx;
729         let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
730         let field = &variant.fields[field_index];
731
732         let def_id = field.did;
733         debug!("IsolatedEncoder::encode_field({:?})", def_id);
734
735         let variant_id = tcx.hir().as_local_hir_id(variant.def_id).unwrap();
736         let variant_data = tcx.hir().expect_variant_data(variant_id);
737
738         Entry {
739             kind: EntryKind::Field,
740             visibility: self.lazy(&field.vis),
741             span: self.lazy(&tcx.def_span(def_id)),
742             attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
743             children: LazySeq::empty(),
744             stability: self.encode_stability(def_id),
745             deprecation: self.encode_deprecation(def_id),
746
747             ty: Some(self.encode_item_type(def_id)),
748             inherent_impls: LazySeq::empty(),
749             variances: LazySeq::empty(),
750             generics: Some(self.encode_generics(def_id)),
751             predicates: Some(self.encode_predicates(def_id)),
752             predicates_defined_on: None,
753
754             mir: None,
755         }
756     }
757
758     fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
759         debug!("IsolatedEncoder::encode_struct_ctor({:?})", def_id);
760         let tcx = self.tcx;
761         let adt_def = tcx.adt_def(adt_def_id);
762         let variant = adt_def.non_enum_variant();
763
764         let data = VariantData {
765             ctor_kind: variant.ctor_kind,
766             discr: variant.discr,
767             ctor: Some(def_id.index),
768             ctor_sig: if variant.ctor_kind == CtorKind::Fn {
769                 Some(self.lazy(&tcx.fn_sig(def_id)))
770             } else {
771                 None
772             }
773         };
774
775         let struct_id = tcx.hir().as_local_hir_id(adt_def_id).unwrap();
776         let struct_vis = &tcx.hir().expect_item_by_hir_id(struct_id).vis;
777         let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
778         for field in &variant.fields {
779             if ctor_vis.is_at_least(field.vis, tcx) {
780                 ctor_vis = field.vis;
781             }
782         }
783
784         // If the structure is marked as non_exhaustive then lower the visibility
785         // to within the crate.
786         if adt_def.non_enum_variant().is_field_list_non_exhaustive() &&
787             ctor_vis == ty::Visibility::Public
788         {
789             ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
790         }
791
792         let repr_options = get_repr_options(&tcx, adt_def_id);
793
794         Entry {
795             kind: EntryKind::Struct(self.lazy(&data), repr_options),
796             visibility: self.lazy(&ctor_vis),
797             span: self.lazy(&tcx.def_span(def_id)),
798             attributes: LazySeq::empty(),
799             children: LazySeq::empty(),
800             stability: self.encode_stability(def_id),
801             deprecation: self.encode_deprecation(def_id),
802
803             ty: Some(self.encode_item_type(def_id)),
804             inherent_impls: LazySeq::empty(),
805             variances: if variant.ctor_kind == CtorKind::Fn {
806                 self.encode_variances_of(def_id)
807             } else {
808                 LazySeq::empty()
809             },
810             generics: Some(self.encode_generics(def_id)),
811             predicates: Some(self.encode_predicates(def_id)),
812             predicates_defined_on: None,
813
814             mir: self.encode_optimized_mir(def_id),
815         }
816     }
817
818     fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
819         debug!("IsolatedEncoder::encode_generics({:?})", def_id);
820         let tcx = self.tcx;
821         self.lazy(tcx.generics_of(def_id))
822     }
823
824     fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
825         debug!("IsolatedEncoder::encode_predicates({:?})", def_id);
826         let tcx = self.tcx;
827         self.lazy(&tcx.predicates_of(def_id))
828     }
829
830     fn encode_predicates_defined_on(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
831         debug!("IsolatedEncoder::encode_predicates_defined_on({:?})", def_id);
832         let tcx = self.tcx;
833         self.lazy(&tcx.predicates_defined_on(def_id))
834     }
835
836     fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
837         debug!("IsolatedEncoder::encode_info_for_trait_item({:?})", def_id);
838         let tcx = self.tcx;
839
840         let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
841         let ast_item = tcx.hir().expect_trait_item(hir_id);
842         let trait_item = tcx.associated_item(def_id);
843
844         let container = match trait_item.defaultness {
845             hir::Defaultness::Default { has_value: true } =>
846                 AssociatedContainer::TraitWithDefault,
847             hir::Defaultness::Default { has_value: false } =>
848                 AssociatedContainer::TraitRequired,
849             hir::Defaultness::Final =>
850                 span_bug!(ast_item.span, "traits cannot have final items"),
851         };
852
853         let kind = match trait_item.kind {
854             ty::AssociatedKind::Const => {
855                 let const_qualif =
856                     if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
857                         self.const_qualif(0, body)
858                     } else {
859                         ConstQualif { mir: 0, ast_promotable: false }
860                     };
861
862                 let rendered =
863                     hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item));
864                 let rendered_const = self.lazy(&RenderedConst(rendered));
865
866                 EntryKind::AssociatedConst(container, const_qualif, rendered_const)
867             }
868             ty::AssociatedKind::Method => {
869                 let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
870                     let arg_names = match *m {
871                         hir::TraitMethod::Required(ref names) => {
872                             self.encode_fn_arg_names(names)
873                         }
874                         hir::TraitMethod::Provided(body) => {
875                             self.encode_fn_arg_names_for_body(body)
876                         }
877                     };
878                     FnData {
879                         constness: hir::Constness::NotConst,
880                         arg_names,
881                         sig: self.lazy(&tcx.fn_sig(def_id)),
882                     }
883                 } else {
884                     bug!()
885                 };
886                 EntryKind::Method(self.lazy(&MethodData {
887                     fn_data,
888                     container,
889                     has_self: trait_item.method_has_self_argument,
890                 }))
891             }
892             ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
893             ty::AssociatedKind::Existential =>
894                 span_bug!(ast_item.span, "existential type in trait"),
895         };
896
897         Entry {
898             kind,
899             visibility: self.lazy(&trait_item.vis),
900             span: self.lazy(&ast_item.span),
901             attributes: self.encode_attributes(&ast_item.attrs),
902             children: LazySeq::empty(),
903             stability: self.encode_stability(def_id),
904             deprecation: self.encode_deprecation(def_id),
905
906             ty: match trait_item.kind {
907                 ty::AssociatedKind::Const |
908                 ty::AssociatedKind::Method => {
909                     Some(self.encode_item_type(def_id))
910                 }
911                 ty::AssociatedKind::Type => {
912                     if trait_item.defaultness.has_value() {
913                         Some(self.encode_item_type(def_id))
914                     } else {
915                         None
916                     }
917                 }
918                 ty::AssociatedKind::Existential => unreachable!(),
919             },
920             inherent_impls: LazySeq::empty(),
921             variances: if trait_item.kind == ty::AssociatedKind::Method {
922                 self.encode_variances_of(def_id)
923             } else {
924                 LazySeq::empty()
925             },
926             generics: Some(self.encode_generics(def_id)),
927             predicates: Some(self.encode_predicates(def_id)),
928             predicates_defined_on: None,
929
930             mir: self.encode_optimized_mir(def_id),
931         }
932     }
933
934     fn metadata_output_only(&self) -> bool {
935         // MIR optimisation can be skipped when we're just interested in the metadata.
936         !self.tcx.sess.opts.output_types.should_codegen()
937     }
938
939     fn const_qualif(&self, mir: u8, body_id: hir::BodyId) -> ConstQualif {
940         let body_owner_def_id = self.tcx.hir().body_owner_def_id(body_id);
941         let ast_promotable = self.tcx.const_is_rvalue_promotable_to_static(body_owner_def_id);
942
943         ConstQualif { mir, ast_promotable }
944     }
945
946     fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
947         debug!("IsolatedEncoder::encode_info_for_impl_item({:?})", def_id);
948         let tcx = self.tcx;
949
950         let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
951         let ast_item = self.tcx.hir().expect_impl_item(hir_id);
952         let impl_item = self.tcx.associated_item(def_id);
953
954         let container = match impl_item.defaultness {
955             hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
956             hir::Defaultness::Final => AssociatedContainer::ImplFinal,
957             hir::Defaultness::Default { has_value: false } =>
958                 span_bug!(ast_item.span, "impl items always have values (currently)"),
959         };
960
961         let kind = match impl_item.kind {
962             ty::AssociatedKind::Const => {
963                 if let hir::ImplItemKind::Const(_, body_id) = ast_item.node {
964                     let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0;
965
966                     EntryKind::AssociatedConst(container,
967                         self.const_qualif(mir, body_id),
968                         self.encode_rendered_const_for_body(body_id))
969                 } else {
970                     bug!()
971                 }
972             }
973             ty::AssociatedKind::Method => {
974                 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
975                     FnData {
976                         constness: sig.header.constness,
977                         arg_names: self.encode_fn_arg_names_for_body(body),
978                         sig: self.lazy(&tcx.fn_sig(def_id)),
979                     }
980                 } else {
981                     bug!()
982                 };
983                 EntryKind::Method(self.lazy(&MethodData {
984                     fn_data,
985                     container,
986                     has_self: impl_item.method_has_self_argument,
987                 }))
988             }
989             ty::AssociatedKind::Existential => EntryKind::AssociatedExistential(container),
990             ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
991         };
992
993         let mir =
994             match ast_item.node {
995                 hir::ImplItemKind::Const(..) => true,
996                 hir::ImplItemKind::Method(ref sig, _) => {
997                     let generics = self.tcx.generics_of(def_id);
998                     let needs_inline = (generics.requires_monomorphization(self.tcx) ||
999                                         tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1000                                         !self.metadata_output_only();
1001                     let is_const_fn = sig.header.constness == hir::Constness::Const;
1002                     let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1003                     needs_inline || is_const_fn || always_encode_mir
1004                 },
1005                 hir::ImplItemKind::Existential(..) |
1006                 hir::ImplItemKind::Type(..) => false,
1007             };
1008
1009         Entry {
1010             kind,
1011             visibility: self.lazy(&impl_item.vis),
1012             span: self.lazy(&ast_item.span),
1013             attributes: self.encode_attributes(&ast_item.attrs),
1014             children: LazySeq::empty(),
1015             stability: self.encode_stability(def_id),
1016             deprecation: self.encode_deprecation(def_id),
1017
1018             ty: Some(self.encode_item_type(def_id)),
1019             inherent_impls: LazySeq::empty(),
1020             variances: if impl_item.kind == ty::AssociatedKind::Method {
1021                 self.encode_variances_of(def_id)
1022             } else {
1023                 LazySeq::empty()
1024             },
1025             generics: Some(self.encode_generics(def_id)),
1026             predicates: Some(self.encode_predicates(def_id)),
1027             predicates_defined_on: None,
1028
1029             mir: if mir { self.encode_optimized_mir(def_id) } else { None },
1030         }
1031     }
1032
1033     fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
1034                                     -> LazySeq<ast::Name> {
1035         self.tcx.dep_graph.with_ignore(|| {
1036             let body = self.tcx.hir().body(body_id);
1037             self.lazy_seq(body.arguments.iter().map(|arg| {
1038                 match arg.pat.node {
1039                     PatKind::Binding(_, _, ident, _) => ident.name,
1040                     _ => keywords::Invalid.name(),
1041                 }
1042             }))
1043         })
1044     }
1045
1046     fn encode_fn_arg_names(&mut self, param_names: &[ast::Ident]) -> LazySeq<ast::Name> {
1047         self.lazy_seq(param_names.iter().map(|ident| ident.name))
1048     }
1049
1050     fn encode_optimized_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
1051         debug!("EntryBuilder::encode_mir({:?})", def_id);
1052         if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1053             let mir = self.tcx.optimized_mir(def_id);
1054             Some(self.lazy(&mir))
1055         } else {
1056             None
1057         }
1058     }
1059
1060     // Encodes the inherent implementations of a structure, enumeration, or trait.
1061     fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
1062         debug!("IsolatedEncoder::encode_inherent_implementations({:?})", def_id);
1063         let implementations = self.tcx.inherent_impls(def_id);
1064         if implementations.is_empty() {
1065             LazySeq::empty()
1066         } else {
1067             self.lazy_seq(implementations.iter().map(|&def_id| {
1068                 assert!(def_id.is_local());
1069                 def_id.index
1070             }))
1071         }
1072     }
1073
1074     fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
1075         debug!("IsolatedEncoder::encode_stability({:?})", def_id);
1076         self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
1077     }
1078
1079     fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
1080         debug!("IsolatedEncoder::encode_deprecation({:?})", def_id);
1081         self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
1082     }
1083
1084     fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1085         let body = self.tcx.hir().body(body_id);
1086         let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_expr(&body.value));
1087         let rendered_const = &RenderedConst(rendered);
1088         self.lazy(rendered_const)
1089     }
1090
1091     fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
1092         let tcx = self.tcx;
1093
1094         debug!("IsolatedEncoder::encode_info_for_item({:?})", def_id);
1095
1096         let kind = match item.node {
1097             hir::ItemKind::Static(_, hir::MutMutable, _) => EntryKind::MutStatic,
1098             hir::ItemKind::Static(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
1099             hir::ItemKind::Const(_, body_id) => {
1100                 let mir = tcx.at(item.span).mir_const_qualif(def_id).0;
1101                 EntryKind::Const(
1102                     self.const_qualif(mir, body_id),
1103                     self.encode_rendered_const_for_body(body_id)
1104                 )
1105             }
1106             hir::ItemKind::Fn(_, header, .., body) => {
1107                 let data = FnData {
1108                     constness: header.constness,
1109                     arg_names: self.encode_fn_arg_names_for_body(body),
1110                     sig: self.lazy(&tcx.fn_sig(def_id)),
1111                 };
1112
1113                 EntryKind::Fn(self.lazy(&data))
1114             }
1115             hir::ItemKind::Mod(ref m) => {
1116                 return self.encode_info_for_mod(FromId(item.hir_id, (m, &item.attrs, &item.vis)));
1117             }
1118             hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1119             hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1120             hir::ItemKind::Ty(..) => EntryKind::Type,
1121             hir::ItemKind::Existential(..) => EntryKind::Existential,
1122             hir::ItemKind::Enum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
1123             hir::ItemKind::Struct(ref struct_def, _) => {
1124                 let variant = tcx.adt_def(def_id).non_enum_variant();
1125
1126                 // Encode def_ids for each field and method
1127                 // for methods, write all the stuff get_trait_method
1128                 // needs to know
1129                 let ctor = struct_def.ctor_hir_id()
1130                     .map(|ctor_hir_id| tcx.hir().local_def_id_from_hir_id(ctor_hir_id).index);
1131
1132                 let repr_options = get_repr_options(&tcx, def_id);
1133
1134                 EntryKind::Struct(self.lazy(&VariantData {
1135                     ctor_kind: variant.ctor_kind,
1136                     discr: variant.discr,
1137                     ctor,
1138                     ctor_sig: None,
1139                 }), repr_options)
1140             }
1141             hir::ItemKind::Union(..) => {
1142                 let variant = tcx.adt_def(def_id).non_enum_variant();
1143                 let repr_options = get_repr_options(&tcx, def_id);
1144
1145                 EntryKind::Union(self.lazy(&VariantData {
1146                     ctor_kind: variant.ctor_kind,
1147                     discr: variant.discr,
1148                     ctor: None,
1149                     ctor_sig: None,
1150                 }), repr_options)
1151             }
1152             hir::ItemKind::Impl(_, polarity, defaultness, ..) => {
1153                 let trait_ref = tcx.impl_trait_ref(def_id);
1154                 let parent = if let Some(trait_ref) = trait_ref {
1155                     let trait_def = tcx.trait_def(trait_ref.def_id);
1156                     trait_def.ancestors(tcx, def_id).nth(1).and_then(|node| {
1157                         match node {
1158                             specialization_graph::Node::Impl(parent) => Some(parent),
1159                             _ => None,
1160                         }
1161                     })
1162                 } else {
1163                     None
1164                 };
1165
1166                 // if this is an impl of `CoerceUnsized`, create its
1167                 // "unsized info", else just store None
1168                 let coerce_unsized_info =
1169                     trait_ref.and_then(|t| {
1170                         if Some(t.def_id) == tcx.lang_items().coerce_unsized_trait() {
1171                             Some(tcx.at(item.span).coerce_unsized_info(def_id))
1172                         } else {
1173                             None
1174                         }
1175                     });
1176
1177                 let data = ImplData {
1178                     polarity,
1179                     defaultness,
1180                     parent_impl: parent,
1181                     coerce_unsized_info,
1182                     trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
1183                 };
1184
1185                 EntryKind::Impl(self.lazy(&data))
1186             }
1187             hir::ItemKind::Trait(..) => {
1188                 let trait_def = tcx.trait_def(def_id);
1189                 let data = TraitData {
1190                     unsafety: trait_def.unsafety,
1191                     paren_sugar: trait_def.paren_sugar,
1192                     has_auto_impl: tcx.trait_is_auto(def_id),
1193                     is_marker: trait_def.is_marker,
1194                     super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1195                 };
1196
1197                 EntryKind::Trait(self.lazy(&data))
1198             }
1199             hir::ItemKind::TraitAlias(..) => {
1200                 let data = TraitAliasData {
1201                     super_predicates: self.lazy(&tcx.super_predicates_of(def_id)),
1202                 };
1203
1204                 EntryKind::TraitAlias(self.lazy(&data))
1205             }
1206             hir::ItemKind::ExternCrate(_) |
1207             hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1208         };
1209
1210         Entry {
1211             kind,
1212             visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.hir_id, tcx)),
1213             span: self.lazy(&item.span),
1214             attributes: self.encode_attributes(&item.attrs),
1215             children: match item.node {
1216                 hir::ItemKind::ForeignMod(ref fm) => {
1217                     self.lazy_seq(fm.items
1218                         .iter()
1219                         .map(|foreign_item| tcx.hir().local_def_id_from_hir_id(
1220                             foreign_item.hir_id).index))
1221                 }
1222                 hir::ItemKind::Enum(..) => {
1223                     let def = self.tcx.adt_def(def_id);
1224                     self.lazy_seq(def.variants.iter().map(|v| {
1225                         assert!(v.def_id.is_local());
1226                         v.def_id.index
1227                     }))
1228                 }
1229                 hir::ItemKind::Struct(..) |
1230                 hir::ItemKind::Union(..) => {
1231                     let def = self.tcx.adt_def(def_id);
1232                     self.lazy_seq(def.non_enum_variant().fields.iter().map(|f| {
1233                         assert!(f.did.is_local());
1234                         f.did.index
1235                     }))
1236                 }
1237                 hir::ItemKind::Impl(..) |
1238                 hir::ItemKind::Trait(..) => {
1239                     self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
1240                         assert!(def_id.is_local());
1241                         def_id.index
1242                     }))
1243                 }
1244                 _ => LazySeq::empty(),
1245             },
1246             stability: self.encode_stability(def_id),
1247             deprecation: self.encode_deprecation(def_id),
1248
1249             ty: match item.node {
1250                 hir::ItemKind::Static(..) |
1251                 hir::ItemKind::Const(..) |
1252                 hir::ItemKind::Fn(..) |
1253                 hir::ItemKind::Ty(..) |
1254                 hir::ItemKind::Existential(..) |
1255                 hir::ItemKind::Enum(..) |
1256                 hir::ItemKind::Struct(..) |
1257                 hir::ItemKind::Union(..) |
1258                 hir::ItemKind::Impl(..) => Some(self.encode_item_type(def_id)),
1259                 _ => None,
1260             },
1261             inherent_impls: self.encode_inherent_implementations(def_id),
1262             variances: match item.node {
1263                 hir::ItemKind::Enum(..) |
1264                 hir::ItemKind::Struct(..) |
1265                 hir::ItemKind::Union(..) |
1266                 hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1267                 _ => LazySeq::empty(),
1268             },
1269             generics: match item.node {
1270                 hir::ItemKind::Static(..) |
1271                 hir::ItemKind::Const(..) |
1272                 hir::ItemKind::Fn(..) |
1273                 hir::ItemKind::Ty(..) |
1274                 hir::ItemKind::Enum(..) |
1275                 hir::ItemKind::Struct(..) |
1276                 hir::ItemKind::Union(..) |
1277                 hir::ItemKind::Impl(..) |
1278                 hir::ItemKind::Existential(..) |
1279                 hir::ItemKind::Trait(..) => Some(self.encode_generics(def_id)),
1280                 hir::ItemKind::TraitAlias(..) => Some(self.encode_generics(def_id)),
1281                 _ => None,
1282             },
1283             predicates: match item.node {
1284                 hir::ItemKind::Static(..) |
1285                 hir::ItemKind::Const(..) |
1286                 hir::ItemKind::Fn(..) |
1287                 hir::ItemKind::Ty(..) |
1288                 hir::ItemKind::Enum(..) |
1289                 hir::ItemKind::Struct(..) |
1290                 hir::ItemKind::Union(..) |
1291                 hir::ItemKind::Impl(..) |
1292                 hir::ItemKind::Existential(..) |
1293                 hir::ItemKind::Trait(..) |
1294                 hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates(def_id)),
1295                 _ => None,
1296             },
1297
1298             // The only time that `predicates_defined_on` is used (on
1299             // an external item) is for traits, during chalk lowering,
1300             // so only encode it in that case as an efficiency
1301             // hack. (No reason not to expand it in the future if
1302             // necessary.)
1303             predicates_defined_on: match item.node {
1304                 hir::ItemKind::Trait(..) |
1305                 hir::ItemKind::TraitAlias(..) => Some(self.encode_predicates_defined_on(def_id)),
1306                 _ => None, // not *wrong* for other kinds of items, but not needed
1307             },
1308
1309             mir: match item.node {
1310                 hir::ItemKind::Static(..) => {
1311                     self.encode_optimized_mir(def_id)
1312                 }
1313                 hir::ItemKind::Const(..) => self.encode_optimized_mir(def_id),
1314                 hir::ItemKind::Fn(_, header, ..) => {
1315                     let generics = tcx.generics_of(def_id);
1316                     let needs_inline =
1317                         (generics.requires_monomorphization(tcx) ||
1318                          tcx.codegen_fn_attrs(def_id).requests_inline()) &&
1319                             !self.metadata_output_only();
1320                     let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1321                     if needs_inline
1322                         || header.constness == hir::Constness::Const
1323                         || always_encode_mir
1324                     {
1325                         self.encode_optimized_mir(def_id)
1326                     } else {
1327                         None
1328                     }
1329                 }
1330                 _ => None,
1331             },
1332         }
1333     }
1334
1335     /// Serialize the text of exported macros
1336     fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
1337         use syntax::print::pprust;
1338         let def_id = self.tcx.hir().local_def_id_from_hir_id(macro_def.hir_id);
1339         Entry {
1340             kind: EntryKind::MacroDef(self.lazy(&MacroDef {
1341                 body: pprust::tts_to_string(&macro_def.body.trees().collect::<Vec<_>>()),
1342                 legacy: macro_def.legacy,
1343             })),
1344             visibility: self.lazy(&ty::Visibility::Public),
1345             span: self.lazy(&macro_def.span),
1346             attributes: self.encode_attributes(&macro_def.attrs),
1347             stability: self.encode_stability(def_id),
1348             deprecation: self.encode_deprecation(def_id),
1349
1350             children: LazySeq::empty(),
1351             ty: None,
1352             inherent_impls: LazySeq::empty(),
1353             variances: LazySeq::empty(),
1354             generics: None,
1355             predicates: None,
1356             predicates_defined_on: None,
1357             mir: None,
1358         }
1359     }
1360
1361     fn encode_info_for_generic_param(
1362         &mut self,
1363         def_id: DefId,
1364         entry_kind: EntryKind<'tcx>,
1365         encode_type: bool,
1366     ) -> Entry<'tcx> {
1367         let tcx = self.tcx;
1368         Entry {
1369             kind: entry_kind,
1370             visibility: self.lazy(&ty::Visibility::Public),
1371             span: self.lazy(&tcx.def_span(def_id)),
1372             attributes: LazySeq::empty(),
1373             children: LazySeq::empty(),
1374             stability: None,
1375             deprecation: None,
1376             ty: if encode_type { Some(self.encode_item_type(def_id)) } else { None },
1377             inherent_impls: LazySeq::empty(),
1378             variances: LazySeq::empty(),
1379             generics: None,
1380             predicates: None,
1381             predicates_defined_on: None,
1382
1383             mir: None,
1384         }
1385     }
1386
1387     fn encode_info_for_ty_param(
1388         &mut self,
1389         (def_id, Untracked(encode_type)): (DefId, Untracked<bool>),
1390     ) -> Entry<'tcx> {
1391         debug!("IsolatedEncoder::encode_info_for_ty_param({:?})", def_id);
1392         self.encode_info_for_generic_param(def_id, EntryKind::TypeParam, encode_type)
1393     }
1394
1395     fn encode_info_for_const_param(
1396         &mut self,
1397         def_id: DefId,
1398     ) -> Entry<'tcx> {
1399         debug!("IsolatedEncoder::encode_info_for_const_param({:?})", def_id);
1400         self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true)
1401     }
1402
1403     fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
1404         debug!("IsolatedEncoder::encode_info_for_closure({:?})", def_id);
1405         let tcx = self.tcx;
1406
1407         let tables = self.tcx.typeck_tables_of(def_id);
1408         let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1409         let kind = match tables.node_type(hir_id).sty {
1410             ty::Generator(def_id, ..) => {
1411                 let layout = self.tcx.generator_layout(def_id);
1412                 let data = GeneratorData {
1413                     layout: layout.clone(),
1414                 };
1415                 EntryKind::Generator(self.lazy(&data))
1416             }
1417
1418             ty::Closure(def_id, substs) => {
1419                 let sig = substs.closure_sig(def_id, self.tcx);
1420                 let data = ClosureData { sig: self.lazy(&sig) };
1421                 EntryKind::Closure(self.lazy(&data))
1422             }
1423
1424             _ => bug!("closure that is neither generator nor closure")
1425         };
1426
1427         Entry {
1428             kind,
1429             visibility: self.lazy(&ty::Visibility::Public),
1430             span: self.lazy(&tcx.def_span(def_id)),
1431             attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
1432             children: LazySeq::empty(),
1433             stability: None,
1434             deprecation: None,
1435
1436             ty: Some(self.encode_item_type(def_id)),
1437             inherent_impls: LazySeq::empty(),
1438             variances: LazySeq::empty(),
1439             generics: Some(self.encode_generics(def_id)),
1440             predicates: None,
1441             predicates_defined_on: None,
1442
1443             mir: self.encode_optimized_mir(def_id),
1444         }
1445     }
1446
1447     fn encode_info_for_anon_const(&mut self, def_id: DefId) -> Entry<'tcx> {
1448         debug!("IsolatedEncoder::encode_info_for_anon_const({:?})", def_id);
1449         let tcx = self.tcx;
1450         let id = tcx.hir().as_local_hir_id(def_id).unwrap();
1451         let body_id = tcx.hir().body_owned_by(id);
1452         let const_data = self.encode_rendered_const_for_body(body_id);
1453         let mir = tcx.mir_const_qualif(def_id).0;
1454
1455         Entry {
1456             kind: EntryKind::Const(self.const_qualif(mir, body_id), const_data),
1457             visibility: self.lazy(&ty::Visibility::Public),
1458             span: self.lazy(&tcx.def_span(def_id)),
1459             attributes: LazySeq::empty(),
1460             children: LazySeq::empty(),
1461             stability: None,
1462             deprecation: None,
1463
1464             ty: Some(self.encode_item_type(def_id)),
1465             inherent_impls: LazySeq::empty(),
1466             variances: LazySeq::empty(),
1467             generics: Some(self.encode_generics(def_id)),
1468             predicates: Some(self.encode_predicates(def_id)),
1469             predicates_defined_on: None,
1470
1471             mir: self.encode_optimized_mir(def_id),
1472         }
1473     }
1474
1475     fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
1476         // NOTE: This must use lazy_seq_from_slice(), not lazy_seq() because
1477         //       we rely on the HashStable specialization for [Attribute]
1478         //       to properly filter things out.
1479         self.lazy_seq_from_slice(attrs)
1480     }
1481
1482     fn encode_native_libraries(&mut self, _: ()) -> LazySeq<NativeLibrary> {
1483         let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1484         self.lazy_seq(used_libraries.iter().cloned())
1485     }
1486
1487     fn encode_foreign_modules(&mut self, _: ()) -> LazySeq<ForeignModule> {
1488         let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1489         self.lazy_seq(foreign_modules.iter().cloned())
1490     }
1491
1492     fn encode_crate_deps(&mut self, _: ()) -> LazySeq<CrateDep> {
1493         let crates = self.tcx.crates();
1494
1495         let mut deps = crates
1496             .iter()
1497             .map(|&cnum| {
1498                 let dep = CrateDep {
1499                     name: self.tcx.original_crate_name(cnum),
1500                     hash: self.tcx.crate_hash(cnum),
1501                     kind: self.tcx.dep_kind(cnum),
1502                     extra_filename: self.tcx.extra_filename(cnum),
1503                 };
1504                 (cnum, dep)
1505             })
1506             .collect::<Vec<_>>();
1507
1508         deps.sort_by_key(|&(cnum, _)| cnum);
1509
1510         {
1511             // Sanity-check the crate numbers
1512             let mut expected_cnum = 1;
1513             for &(n, _) in &deps {
1514                 assert_eq!(n, CrateNum::new(expected_cnum));
1515                 expected_cnum += 1;
1516             }
1517         }
1518
1519         // We're just going to write a list of crate 'name-hash-version's, with
1520         // the assumption that they are numbered 1 to n.
1521         // FIXME (#2166): This is not nearly enough to support correct versioning
1522         // but is enough to get transitive crate dependencies working.
1523         self.lazy_seq_ref(deps.iter().map(|&(_, ref dep)| dep))
1524     }
1525
1526     fn encode_lib_features(&mut self, _: ()) -> LazySeq<(ast::Name, Option<ast::Name>)> {
1527         let tcx = self.tcx;
1528         let lib_features = tcx.lib_features();
1529         self.lazy_seq(lib_features.to_vec())
1530     }
1531
1532     fn encode_lang_items(&mut self, _: ()) -> LazySeq<(DefIndex, usize)> {
1533         let tcx = self.tcx;
1534         let lang_items = tcx.lang_items();
1535         let lang_items = lang_items.items().iter();
1536         self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1537             if let Some(def_id) = opt_def_id {
1538                 if def_id.is_local() {
1539                     return Some((def_id.index, i));
1540                 }
1541             }
1542             None
1543         }))
1544     }
1545
1546     fn encode_lang_items_missing(&mut self, _: ()) -> LazySeq<lang_items::LangItem> {
1547         let tcx = self.tcx;
1548         self.lazy_seq_ref(&tcx.lang_items().missing)
1549     }
1550
1551     /// Encodes an index, mapping each trait to its (local) implementations.
1552     fn encode_impls(&mut self, _: ()) -> LazySeq<TraitImpls> {
1553         debug!("IsolatedEncoder::encode_impls()");
1554         let tcx = self.tcx;
1555         let mut visitor = ImplVisitor {
1556             tcx,
1557             impls: FxHashMap::default(),
1558         };
1559         tcx.hir().krate().visit_all_item_likes(&mut visitor);
1560
1561         let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1562
1563         // Bring everything into deterministic order for hashing
1564         all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
1565             tcx.def_path_hash(trait_def_id)
1566         });
1567
1568         let all_impls: Vec<_> = all_impls
1569             .into_iter()
1570             .map(|(trait_def_id, mut impls)| {
1571                 // Bring everything into deterministic order for hashing
1572                 impls.sort_by_cached_key(|&def_index| {
1573                     tcx.hir().definitions().def_path_hash(def_index)
1574                 });
1575
1576                 TraitImpls {
1577                     trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1578                     impls: self.lazy_seq_from_slice(&impls[..]),
1579                 }
1580             })
1581             .collect();
1582
1583         self.lazy_seq_from_slice(&all_impls[..])
1584     }
1585
1586     // Encodes all symbols exported from this crate into the metadata.
1587     //
1588     // This pass is seeded off the reachability list calculated in the
1589     // middle::reachable module but filters out items that either don't have a
1590     // symbol associated with them (they weren't translated) or if they're an FFI
1591     // definition (as that's not defined in this crate).
1592     fn encode_exported_symbols(&mut self,
1593                                exported_symbols: &[(ExportedSymbol<'_>, SymbolExportLevel)])
1594                                -> EncodedExportedSymbols {
1595         // The metadata symbol name is special. It should not show up in
1596         // downstream crates.
1597         let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1598
1599         let lazy_seq = self.lazy_seq(exported_symbols
1600             .iter()
1601             .filter(|&&(ref exported_symbol, _)| {
1602                 match *exported_symbol {
1603                     ExportedSymbol::NoDefId(symbol_name) => {
1604                         symbol_name != metadata_symbol_name
1605                     },
1606                     _ => true,
1607                 }
1608             })
1609             .cloned());
1610
1611         EncodedExportedSymbols {
1612             len: lazy_seq.len,
1613             position: lazy_seq.position,
1614         }
1615     }
1616
1617     fn encode_dylib_dependency_formats(&mut self, _: ()) -> LazySeq<Option<LinkagePreference>> {
1618         match self.tcx.sess.dependency_formats.borrow().get(&config::CrateType::Dylib) {
1619             Some(arr) => {
1620                 self.lazy_seq(arr.iter().map(|slot| {
1621                     match *slot {
1622                         Linkage::NotLinked |
1623                         Linkage::IncludedFromDylib => None,
1624
1625                         Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1626                         Linkage::Static => Some(LinkagePreference::RequireStatic),
1627                     }
1628                 }))
1629             }
1630             None => LazySeq::empty(),
1631         }
1632     }
1633
1634     fn encode_info_for_foreign_item(&mut self,
1635                                     (def_id, nitem): (DefId, &hir::ForeignItem))
1636                                     -> Entry<'tcx> {
1637         let tcx = self.tcx;
1638
1639         debug!("IsolatedEncoder::encode_info_for_foreign_item({:?})", def_id);
1640
1641         let kind = match nitem.node {
1642             hir::ForeignItemKind::Fn(_, ref names, _) => {
1643                 let data = FnData {
1644                     constness: hir::Constness::NotConst,
1645                     arg_names: self.encode_fn_arg_names(names),
1646                     sig: self.lazy(&tcx.fn_sig(def_id)),
1647                 };
1648                 EntryKind::ForeignFn(self.lazy(&data))
1649             }
1650             hir::ForeignItemKind::Static(_, hir::MutMutable) => EntryKind::ForeignMutStatic,
1651             hir::ForeignItemKind::Static(_, hir::MutImmutable) => EntryKind::ForeignImmStatic,
1652             hir::ForeignItemKind::Type => EntryKind::ForeignType,
1653         };
1654
1655         Entry {
1656             kind,
1657             visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, tcx)),
1658             span: self.lazy(&nitem.span),
1659             attributes: self.encode_attributes(&nitem.attrs),
1660             children: LazySeq::empty(),
1661             stability: self.encode_stability(def_id),
1662             deprecation: self.encode_deprecation(def_id),
1663
1664             ty: Some(self.encode_item_type(def_id)),
1665             inherent_impls: LazySeq::empty(),
1666             variances: match nitem.node {
1667                 hir::ForeignItemKind::Fn(..) => self.encode_variances_of(def_id),
1668                 _ => LazySeq::empty(),
1669             },
1670             generics: Some(self.encode_generics(def_id)),
1671             predicates: Some(self.encode_predicates(def_id)),
1672             predicates_defined_on: None,
1673
1674             mir: None,
1675         }
1676     }
1677 }
1678
1679 struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
1680     index: IndexBuilder<'a, 'b, 'tcx>,
1681 }
1682
1683 impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
1684     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
1685         NestedVisitorMap::OnlyBodies(&self.index.tcx.hir())
1686     }
1687     fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
1688         intravisit::walk_expr(self, ex);
1689         self.index.encode_info_for_expr(ex);
1690     }
1691     fn visit_item(&mut self, item: &'tcx hir::Item) {
1692         intravisit::walk_item(self, item);
1693         let def_id = self.index.tcx.hir().local_def_id_from_hir_id(item.hir_id);
1694         match item.node {
1695             hir::ItemKind::ExternCrate(_) |
1696             hir::ItemKind::Use(..) => (), // ignore these
1697             _ => self.index.record(def_id, IsolatedEncoder::encode_info_for_item, (def_id, item)),
1698         }
1699         self.index.encode_addl_info_for_item(item);
1700     }
1701     fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
1702         intravisit::walk_foreign_item(self, ni);
1703         let def_id = self.index.tcx.hir().local_def_id_from_hir_id(ni.hir_id);
1704         self.index.record(def_id,
1705                           IsolatedEncoder::encode_info_for_foreign_item,
1706                           (def_id, ni));
1707     }
1708     fn visit_variant(&mut self,
1709                      v: &'tcx hir::Variant,
1710                      g: &'tcx hir::Generics,
1711                      id: hir::HirId) {
1712         intravisit::walk_variant(self, v, g, id);
1713
1714         if let Some(ref discr) = v.node.disr_expr {
1715             let def_id = self.index.tcx.hir().local_def_id_from_hir_id(discr.hir_id);
1716             self.index.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1717         }
1718     }
1719     fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
1720         intravisit::walk_generics(self, generics);
1721         self.index.encode_info_for_generics(generics);
1722     }
1723     fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
1724         intravisit::walk_ty(self, ty);
1725         self.index.encode_info_for_ty(ty);
1726     }
1727     fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
1728         let def_id = self.index.tcx.hir().local_def_id_from_hir_id(macro_def.hir_id);
1729         self.index.record(def_id, IsolatedEncoder::encode_info_for_macro_def, macro_def);
1730     }
1731 }
1732
1733 impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
1734     fn encode_fields(&mut self, adt_def_id: DefId) {
1735         let def = self.tcx.adt_def(adt_def_id);
1736         for (variant_index, variant) in def.variants.iter_enumerated() {
1737             for (field_index, field) in variant.fields.iter().enumerate() {
1738                 self.record(field.did,
1739                             IsolatedEncoder::encode_field,
1740                             (adt_def_id, Untracked((variant_index, field_index))));
1741             }
1742         }
1743     }
1744
1745     fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
1746         for param in &generics.params {
1747             let def_id = self.tcx.hir().local_def_id_from_hir_id(param.hir_id);
1748             match param.kind {
1749                 GenericParamKind::Lifetime { .. } => continue,
1750                 GenericParamKind::Type { ref default, .. } => {
1751                     self.record(
1752                         def_id,
1753                         IsolatedEncoder::encode_info_for_ty_param,
1754                         (def_id, Untracked(default.is_some())),
1755                     );
1756                 }
1757                 GenericParamKind::Const { .. } => {
1758                     self.record(def_id, IsolatedEncoder::encode_info_for_const_param, def_id);
1759                 }
1760             }
1761         }
1762     }
1763
1764     fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
1765         match ty.node {
1766             hir::TyKind::Array(_, ref length) => {
1767                 let def_id = self.tcx.hir().local_def_id_from_hir_id(length.hir_id);
1768                 self.record(def_id, IsolatedEncoder::encode_info_for_anon_const, def_id);
1769             }
1770             _ => {}
1771         }
1772     }
1773
1774     fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
1775         match expr.node {
1776             hir::ExprKind::Closure(..) => {
1777                 let def_id = self.tcx.hir().local_def_id_from_hir_id(expr.hir_id);
1778                 self.record(def_id, IsolatedEncoder::encode_info_for_closure, def_id);
1779             }
1780             _ => {}
1781         }
1782     }
1783
1784     /// In some cases, along with the item itself, we also
1785     /// encode some sub-items. Usually we want some info from the item
1786     /// so it's easier to do that here then to wait until we would encounter
1787     /// normally in the visitor walk.
1788     fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
1789         let def_id = self.tcx.hir().local_def_id_from_hir_id(item.hir_id);
1790         match item.node {
1791             hir::ItemKind::Static(..) |
1792             hir::ItemKind::Const(..) |
1793             hir::ItemKind::Fn(..) |
1794             hir::ItemKind::Mod(..) |
1795             hir::ItemKind::ForeignMod(..) |
1796             hir::ItemKind::GlobalAsm(..) |
1797             hir::ItemKind::ExternCrate(..) |
1798             hir::ItemKind::Use(..) |
1799             hir::ItemKind::Ty(..) |
1800             hir::ItemKind::Existential(..) |
1801             hir::ItemKind::TraitAlias(..) => {
1802                 // no sub-item recording needed in these cases
1803             }
1804             hir::ItemKind::Enum(..) => {
1805                 self.encode_fields(def_id);
1806
1807                 let def = self.tcx.adt_def(def_id);
1808                 for (i, variant) in def.variants.iter_enumerated() {
1809                     self.record(variant.def_id,
1810                                 IsolatedEncoder::encode_enum_variant_info,
1811                                 (def_id, Untracked(i)));
1812
1813                     if let Some(ctor_def_id) = variant.ctor_def_id {
1814                         self.record(ctor_def_id,
1815                                     IsolatedEncoder::encode_enum_variant_ctor,
1816                                     (def_id, Untracked(i)));
1817                     }
1818                 }
1819             }
1820             hir::ItemKind::Struct(ref struct_def, _) => {
1821                 self.encode_fields(def_id);
1822
1823                 // If the struct has a constructor, encode it.
1824                 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1825                     let ctor_def_id = self.tcx.hir().local_def_id_from_hir_id(ctor_hir_id);
1826                     self.record(ctor_def_id,
1827                                 IsolatedEncoder::encode_struct_ctor,
1828                                 (def_id, ctor_def_id));
1829                 }
1830             }
1831             hir::ItemKind::Union(..) => {
1832                 self.encode_fields(def_id);
1833             }
1834             hir::ItemKind::Impl(..) => {
1835                 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1836                     self.record(trait_item_def_id,
1837                                 IsolatedEncoder::encode_info_for_impl_item,
1838                                 trait_item_def_id);
1839                 }
1840             }
1841             hir::ItemKind::Trait(..) => {
1842                 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1843                     self.record(item_def_id,
1844                                 IsolatedEncoder::encode_info_for_trait_item,
1845                                 item_def_id);
1846                 }
1847             }
1848         }
1849     }
1850 }
1851
1852 struct ImplVisitor<'a, 'tcx: 'a> {
1853     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1854     impls: FxHashMap<DefId, Vec<DefIndex>>,
1855 }
1856
1857 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
1858     fn visit_item(&mut self, item: &hir::Item) {
1859         if let hir::ItemKind::Impl(..) = item.node {
1860             let impl_id = self.tcx.hir().local_def_id_from_hir_id(item.hir_id);
1861             if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1862                 self.impls
1863                     .entry(trait_ref.def_id)
1864                     .or_default()
1865                     .push(impl_id.index);
1866             }
1867         }
1868     }
1869
1870     fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}
1871
1872     fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
1873         // handled in `visit_item` above
1874     }
1875 }
1876
1877 // NOTE(eddyb) The following comment was preserved for posterity, even
1878 // though it's no longer relevant as EBML (which uses nested & tagged
1879 // "documents") was replaced with a scheme that can't go out of bounds.
1880 //
1881 // And here we run into yet another obscure archive bug: in which metadata
1882 // loaded from archives may have trailing garbage bytes. Awhile back one of
1883 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1884 // and opt) by having ebml generate an out-of-bounds panic when looking at
1885 // metadata.
1886 //
1887 // Upon investigation it turned out that the metadata file inside of an rlib
1888 // (and ar archive) was being corrupted. Some compilations would generate a
1889 // metadata file which would end in a few extra bytes, while other
1890 // compilations would not have these extra bytes appended to the end. These
1891 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1892 // being interpreted causing the out-of-bounds.
1893 //
1894 // The root cause of why these extra bytes were appearing was never
1895 // discovered, and in the meantime the solution we're employing is to insert
1896 // the length of the metadata to the start of the metadata. Later on this
1897 // will allow us to slice the metadata to the precise length that we just
1898 // generated regardless of trailing bytes that end up in it.
1899
1900 pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
1901                                  -> EncodedMetadata
1902 {
1903     let mut encoder = opaque::Encoder::new(vec![]);
1904     encoder.emit_raw_bytes(METADATA_HEADER);
1905
1906     // Will be filled with the root position after encoding everything.
1907     encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1908
1909     let (root, mut result) = {
1910         let mut ecx = EncodeContext {
1911             opaque: encoder,
1912             tcx,
1913             lazy_state: LazyState::NoNode,
1914             type_shorthands: Default::default(),
1915             predicate_shorthands: Default::default(),
1916             source_file_cache: tcx.sess.source_map().files()[0].clone(),
1917             interpret_allocs: Default::default(),
1918             interpret_allocs_inverse: Default::default(),
1919         };
1920
1921         // Encode the rustc version string in a predictable location.
1922         rustc_version().encode(&mut ecx).unwrap();
1923
1924         // Encode all the entries and extra information in the crate,
1925         // culminating in the `CrateRoot` which points to all of it.
1926         let root = ecx.encode_crate_root();
1927         (root, ecx.opaque.into_inner())
1928     };
1929
1930     // Encode the root position.
1931     let header = METADATA_HEADER.len();
1932     let pos = root.position;
1933     result[header + 0] = (pos >> 24) as u8;
1934     result[header + 1] = (pos >> 16) as u8;
1935     result[header + 2] = (pos >> 8) as u8;
1936     result[header + 3] = (pos >> 0) as u8;
1937
1938     EncodedMetadata { raw_data: result }
1939 }
1940
1941 pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
1942     let ty = tcx.type_of(did);
1943     match ty.sty {
1944         ty::Adt(ref def, _) => return def.repr,
1945         _ => bug!("{} is not an ADT", ty),
1946     }
1947 }