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