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