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