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