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