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