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