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