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