1 use crate::rmeta::table::FixedSizeEncoding;
4 use rustc::hir::map::definitions::DefPathTable;
5 use rustc::hir::map::Map;
6 use rustc::middle::cstore::{EncodedMetadata, ForeignModule, LinkagePreference, NativeLibrary};
7 use rustc::middle::dependency_format::Linkage;
8 use rustc::middle::exported_symbols::{metadata_symbol_name, ExportedSymbol, SymbolExportLevel};
9 use rustc::middle::lang_items;
10 use rustc::mir::{self, interpret};
11 use rustc::traits::specialization_graph;
12 use rustc::ty::codec::{self as ty_codec, TyEncoder};
13 use rustc::ty::layout::VariantIdx;
14 use rustc::ty::{self, SymbolName, Ty, TyCtxt};
15 use rustc_data_structures::fingerprint::Fingerprint;
16 use rustc_hir::def::CtorKind;
17 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
18 use rustc_hir::{AnonConst, GenericParamKind};
19 use rustc_index::vec::Idx;
21 use rustc::session::config::{self, CrateType};
22 use rustc_data_structures::fx::FxHashMap;
23 use rustc_data_structures::stable_hasher::StableHasher;
24 use rustc_data_structures::sync::Lrc;
25 use rustc_serialize::{opaque, Encodable, Encoder, SpecializedEncoder};
27 use log::{debug, trace};
28 use rustc_span::source_map::Spanned;
29 use rustc_span::symbol::{kw, sym, Ident, Symbol};
30 use rustc_span::{self, FileName, SourceFile, Span};
32 use std::num::NonZeroUsize;
37 use syntax::expand::is_proc_macro_attr;
40 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
41 use rustc_hir::itemlikevisit::ItemLikeVisitor;
43 struct EncodeContext<'tcx> {
44 opaque: opaque::Encoder,
47 per_def: PerDefTableBuilders<'tcx>,
49 lazy_state: LazyState,
50 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
51 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
53 interpret_allocs: FxHashMap<interpret::AllocId, usize>,
54 interpret_allocs_inverse: Vec<interpret::AllocId>,
56 // This is used to speed up Span encoding.
57 source_file_cache: Lrc<SourceFile>,
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)
68 impl<'tcx> Encoder for EncodeContext<'tcx> {
69 type Error = <opaque::Encoder as Encoder>::Error;
71 fn emit_unit(&mut self) -> Result<(), Self::Error> {
98 impl<'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'tcx> {
99 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
100 self.emit_lazy_distance(*lazy)
104 impl<'tcx, T> SpecializedEncoder<Lazy<[T]>> for EncodeContext<'tcx> {
105 fn specialized_encode(&mut self, lazy: &Lazy<[T]>) -> Result<(), Self::Error> {
106 self.emit_usize(lazy.meta)?;
110 self.emit_lazy_distance(*lazy)
114 impl<'tcx, I: Idx, T> SpecializedEncoder<Lazy<Table<I, T>>> for EncodeContext<'tcx>
116 Option<T>: FixedSizeEncoding,
118 fn specialized_encode(&mut self, lazy: &Lazy<Table<I, T>>) -> Result<(), Self::Error> {
119 self.emit_usize(lazy.meta)?;
120 self.emit_lazy_distance(*lazy)
124 impl<'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'tcx> {
126 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
127 self.emit_u32(cnum.as_u32())
131 impl<'tcx> SpecializedEncoder<DefId> for EncodeContext<'tcx> {
133 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
134 let DefId { krate, index } = *def_id;
141 impl<'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'tcx> {
143 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
144 self.emit_u32(def_index.as_u32())
148 impl<'tcx> SpecializedEncoder<Span> for EncodeContext<'tcx> {
149 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
151 return TAG_INVALID_SPAN.encode(self);
154 let span = span.data();
156 // The Span infrastructure should make sure that this invariant holds:
157 debug_assert!(span.lo <= span.hi);
159 if !self.source_file_cache.contains(span.lo) {
160 let source_map = self.tcx.sess.source_map();
161 let source_file_index = source_map.lookup_source_file_idx(span.lo);
162 self.source_file_cache = source_map.files()[source_file_index].clone();
165 if !self.source_file_cache.contains(span.hi) {
166 // Unfortunately, macro expansion still sometimes generates Spans
167 // that malformed in this way.
168 return TAG_INVALID_SPAN.encode(self);
171 // HACK(eddyb) there's no way to indicate which crate a Span is coming
172 // from right now, so decoding would fail to find the SourceFile if
173 // it's not local to the crate the Span is found in.
174 if self.source_file_cache.is_imported() {
175 return TAG_INVALID_SPAN.encode(self);
178 TAG_VALID_SPAN.encode(self)?;
179 span.lo.encode(self)?;
181 // Encode length which is usually less than span.hi and profits more
182 // from the variable-length integer encoding that we use.
183 let len = span.hi - span.lo;
186 // Don't encode the expansion context.
190 impl SpecializedEncoder<Ident> for EncodeContext<'tcx> {
191 fn specialized_encode(&mut self, ident: &Ident) -> Result<(), Self::Error> {
192 // FIXME(jseyfried): intercrate hygiene
193 ident.name.encode(self)
197 impl<'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'tcx> {
199 fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
200 self.specialized_encode(&def_id.to_def_id())
204 impl<'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'tcx> {
205 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
206 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
210 impl<'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'tcx> {
211 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
212 use std::collections::hash_map::Entry;
213 let index = match self.interpret_allocs.entry(*alloc_id) {
214 Entry::Occupied(e) => *e.get(),
215 Entry::Vacant(e) => {
216 let idx = self.interpret_allocs_inverse.len();
217 self.interpret_allocs_inverse.push(*alloc_id);
227 impl<'tcx> SpecializedEncoder<&'tcx [(ty::Predicate<'tcx>, Span)]> for EncodeContext<'tcx> {
228 fn specialized_encode(
230 predicates: &&'tcx [(ty::Predicate<'tcx>, Span)],
231 ) -> Result<(), Self::Error> {
232 ty_codec::encode_spanned_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
236 impl<'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'tcx> {
237 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
238 f.encode_opaque(&mut self.opaque)
242 impl<'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>> for EncodeContext<'tcx> {
243 fn specialized_encode(&mut self, _: &mir::ClearCrossCrate<T>) -> Result<(), Self::Error> {
248 impl<'tcx> TyEncoder for EncodeContext<'tcx> {
249 fn position(&self) -> usize {
250 self.opaque.position()
254 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
255 trait EncodeContentsForLazy<T: ?Sized + LazyMeta> {
256 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) -> T::Meta;
259 impl<T: Encodable> EncodeContentsForLazy<T> for &T {
260 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) {
261 self.encode(ecx).unwrap()
265 impl<T: Encodable> EncodeContentsForLazy<T> for T {
266 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) {
267 self.encode(ecx).unwrap()
271 impl<I, T: Encodable> EncodeContentsForLazy<[T]> for I
274 I::Item: EncodeContentsForLazy<T>,
276 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) -> usize {
277 self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
281 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would
282 // normally need extra variables to avoid errors about multiple mutable borrows.
283 macro_rules! record {
284 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
287 let lazy = $self.lazy(value);
288 $self.$tables.$table.set($def_id.index, lazy);
293 impl<'tcx> EncodeContext<'tcx> {
294 fn emit_lazy_distance<T: ?Sized + LazyMeta>(
297 ) -> Result<(), <Self as Encoder>::Error> {
298 let min_end = lazy.position.get() + T::min_size(lazy.meta);
299 let distance = match self.lazy_state {
300 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
301 LazyState::NodeStart(start) => {
302 let start = start.get();
303 assert!(min_end <= start);
306 LazyState::Previous(last_min_end) => {
308 last_min_end <= lazy.position,
309 "make sure that the calls to `lazy*` \
310 are in the same order as the metadata fields",
312 lazy.position.get() - last_min_end.get()
315 self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap());
316 self.emit_usize(distance)
319 fn lazy<T: ?Sized + LazyMeta>(&mut self, value: impl EncodeContentsForLazy<T>) -> Lazy<T> {
320 let pos = NonZeroUsize::new(self.position()).unwrap();
322 assert_eq!(self.lazy_state, LazyState::NoNode);
323 self.lazy_state = LazyState::NodeStart(pos);
324 let meta = value.encode_contents_for_lazy(self);
325 self.lazy_state = LazyState::NoNode;
327 assert!(pos.get() + <T>::min_size(meta) <= self.position());
329 Lazy::from_position_and_meta(pos, meta)
332 fn encode_info_for_items(&mut self) {
333 let krate = self.tcx.hir().krate();
334 let vis = Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public };
335 self.encode_info_for_mod(hir::CRATE_HIR_ID, &krate.module, &krate.attrs, &vis);
336 krate.visit_all_item_likes(&mut self.as_deep_visitor());
337 for macro_def in krate.exported_macros {
338 self.visit_macro_def(macro_def);
342 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
343 let definitions = self.tcx.hir().definitions();
344 self.lazy(definitions.def_path_table())
347 fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> {
348 let source_map = self.tcx.sess.source_map();
349 let all_source_files = source_map.files();
351 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
353 let adapted = all_source_files
355 .filter(|source_file| {
356 // No need to re-export imported source_files, as any downstream
357 // crate will import them from their original source.
358 // FIXME(eddyb) the `Span` encoding should take that into account.
359 !source_file.is_imported()
362 match source_file.name {
363 // This path of this SourceFile has been modified by
364 // path-remapping, so we use it verbatim (and avoid
365 // cloning the whole map in the process).
366 _ if source_file.name_was_remapped => source_file.clone(),
368 // Otherwise expand all paths to absolute paths because
369 // any relative paths are potentially relative to a
371 FileName::Real(ref name) => {
372 let mut adapted = (**source_file).clone();
373 adapted.name = Path::new(&working_dir).join(name).into();
374 adapted.name_hash = {
375 let mut hasher: StableHasher = StableHasher::new();
376 adapted.name.hash(&mut hasher);
377 hasher.finish::<u128>()
382 // expanded code, not from a file
383 _ => source_file.clone(),
386 .collect::<Vec<_>>();
388 self.lazy(adapted.iter().map(|rc| &**rc))
391 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
392 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
394 let mut i = self.position();
396 let crate_deps = self.encode_crate_deps();
397 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
398 let dep_bytes = self.position() - i;
400 // Encode the lib features.
402 let lib_features = self.encode_lib_features();
403 let lib_feature_bytes = self.position() - i;
405 // Encode the language items.
407 let lang_items = self.encode_lang_items();
408 let lang_items_missing = self.encode_lang_items_missing();
409 let lang_item_bytes = self.position() - i;
411 // Encode the diagnostic items.
413 let diagnostic_items = self.encode_diagnostic_items();
414 let diagnostic_item_bytes = self.position() - i;
416 // Encode the native libraries used
418 let native_libraries = self.encode_native_libraries();
419 let native_lib_bytes = self.position() - i;
421 let foreign_modules = self.encode_foreign_modules();
425 let source_map = self.encode_source_map();
426 let source_map_bytes = self.position() - i;
428 // Encode DefPathTable
430 let def_path_table = self.encode_def_path_table();
431 let def_path_table_bytes = self.position() - i;
433 // Encode the def IDs of impls, for coherence checking.
435 let impls = self.encode_impls();
436 let impl_bytes = self.position() - i;
438 // Encode exported symbols info.
440 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
441 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
442 let exported_symbols_bytes = self.position() - i;
448 self.encode_info_for_items();
449 let item_bytes = self.position() - i;
451 // Encode the allocation index
452 let interpret_alloc_index = {
453 let mut interpret_alloc_index = Vec::new();
455 trace!("beginning to encode alloc ids");
457 let new_n = self.interpret_allocs_inverse.len();
458 // if we have found new ids, serialize those, too
463 trace!("encoding {} further alloc ids", new_n - n);
464 for idx in n..new_n {
465 let id = self.interpret_allocs_inverse[idx];
466 let pos = self.position() as u32;
467 interpret_alloc_index.push(pos);
468 interpret::specialized_encode_alloc_id(self, tcx, id).unwrap();
472 self.lazy(interpret_alloc_index)
476 let per_def = self.per_def.encode(&mut self.opaque);
477 let per_def_bytes = self.position() - i;
479 // Encode the proc macro data
481 let proc_macro_data = self.encode_proc_macros();
482 let proc_macro_data_bytes = self.position() - i;
484 let attrs = tcx.hir().krate_attrs();
485 let has_default_lib_allocator = attr::contains_name(&attrs, sym::default_lib_allocator);
487 let root = self.lazy(CrateRoot {
488 name: tcx.crate_name(LOCAL_CRATE),
489 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
490 triple: tcx.sess.opts.target_triple.clone(),
491 hash: tcx.crate_hash(LOCAL_CRATE),
492 disambiguator: tcx.sess.local_crate_disambiguator(),
493 panic_strategy: tcx.sess.panic_strategy(),
494 edition: tcx.sess.edition(),
495 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
496 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
497 has_default_lib_allocator: has_default_lib_allocator,
498 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
499 proc_macro_decls_static: if is_proc_macro {
500 let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap();
506 proc_macro_stability: if is_proc_macro {
507 tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).map(|stab| *stab)
511 compiler_builtins: attr::contains_name(&attrs, sym::compiler_builtins),
512 needs_allocator: attr::contains_name(&attrs, sym::needs_allocator),
513 needs_panic_runtime: attr::contains_name(&attrs, sym::needs_panic_runtime),
514 no_builtins: attr::contains_name(&attrs, sym::no_builtins),
515 panic_runtime: attr::contains_name(&attrs, sym::panic_runtime),
516 profiler_runtime: attr::contains_name(&attrs, sym::profiler_runtime),
517 symbol_mangling_version: tcx.sess.opts.debugging_opts.symbol_mangling_version,
520 dylib_dependency_formats,
531 interpret_alloc_index,
535 let total_bytes = self.position();
537 if self.tcx.sess.meta_stats() {
538 let mut zero_bytes = 0;
539 for e in self.opaque.data.iter() {
545 println!("metadata stats:");
546 println!(" dep bytes: {}", dep_bytes);
547 println!(" lib feature bytes: {}", lib_feature_bytes);
548 println!(" lang item bytes: {}", lang_item_bytes);
549 println!(" diagnostic item bytes: {}", diagnostic_item_bytes);
550 println!(" native bytes: {}", native_lib_bytes);
551 println!(" source_map bytes: {}", source_map_bytes);
552 println!(" impl bytes: {}", impl_bytes);
553 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
554 println!(" def-path table bytes: {}", def_path_table_bytes);
555 println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
556 println!(" item bytes: {}", item_bytes);
557 println!(" per-def table bytes: {}", per_def_bytes);
558 println!(" zero bytes: {}", zero_bytes);
559 println!(" total bytes: {}", total_bytes);
566 impl EncodeContext<'tcx> {
567 fn encode_variances_of(&mut self, def_id: DefId) {
568 debug!("EncodeContext::encode_variances_of({:?})", def_id);
569 record!(self.per_def.variances[def_id] <- &self.tcx.variances_of(def_id)[..]);
572 fn encode_item_type(&mut self, def_id: DefId) {
573 debug!("EncodeContext::encode_item_type({:?})", def_id);
574 record!(self.per_def.ty[def_id] <- self.tcx.type_of(def_id));
577 fn encode_enum_variant_info(&mut self, enum_did: DefId, index: VariantIdx) {
579 let def = tcx.adt_def(enum_did);
580 let variant = &def.variants[index];
581 let def_id = variant.def_id;
582 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
584 let data = VariantData {
585 ctor_kind: variant.ctor_kind,
586 discr: variant.discr,
587 ctor: variant.ctor_def_id.map(|did| did.index),
590 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
591 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
593 record!(self.per_def.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
594 record!(self.per_def.visibility[def_id] <-
595 ty::Visibility::from_hir(enum_vis, enum_id, self.tcx));
596 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
597 record!(self.per_def.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
598 record!(self.per_def.children[def_id] <- variant.fields.iter().map(|f| {
599 assert!(f.did.is_local());
602 self.encode_stability(def_id);
603 self.encode_deprecation(def_id);
604 self.encode_item_type(def_id);
605 if variant.ctor_kind == CtorKind::Fn {
606 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
607 if let Some(ctor_def_id) = variant.ctor_def_id {
608 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
610 // FIXME(eddyb) is this ever used?
611 self.encode_variances_of(def_id);
613 self.encode_generics(def_id);
614 self.encode_explicit_predicates(def_id);
615 self.encode_inferred_outlives(def_id);
616 self.encode_optimized_mir(def_id);
617 self.encode_promoted_mir(def_id);
620 fn encode_enum_variant_ctor(&mut self, enum_did: DefId, index: VariantIdx) {
622 let def = tcx.adt_def(enum_did);
623 let variant = &def.variants[index];
624 let def_id = variant.ctor_def_id.unwrap();
625 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
627 // FIXME(eddyb) encode only the `CtorKind` for constructors.
628 let data = VariantData {
629 ctor_kind: variant.ctor_kind,
630 discr: variant.discr,
631 ctor: Some(def_id.index),
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(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));
643 record!(self.per_def.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
644 record!(self.per_def.visibility[def_id] <- ctor_vis);
645 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
646 self.encode_stability(def_id);
647 self.encode_deprecation(def_id);
648 self.encode_item_type(def_id);
649 if variant.ctor_kind == CtorKind::Fn {
650 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
651 self.encode_variances_of(def_id);
653 self.encode_generics(def_id);
654 self.encode_explicit_predicates(def_id);
655 self.encode_inferred_outlives(def_id);
656 self.encode_optimized_mir(def_id);
657 self.encode_promoted_mir(def_id);
660 fn encode_info_for_mod(
664 attrs: &[ast::Attribute],
665 vis: &hir::Visibility<'_>,
668 let def_id = tcx.hir().local_def_id(id);
669 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
672 reexports: match tcx.module_exports(def_id) {
673 Some(exports) => self.lazy(exports),
678 record!(self.per_def.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
679 record!(self.per_def.visibility[def_id] <- ty::Visibility::from_hir(vis, id, self.tcx));
680 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
681 record!(self.per_def.attributes[def_id] <- attrs);
682 record!(self.per_def.children[def_id] <- md.item_ids.iter().map(|item_id| {
683 tcx.hir().local_def_id(item_id.id).index
685 self.encode_stability(def_id);
686 self.encode_deprecation(def_id);
689 fn encode_field(&mut self, adt_def_id: DefId, variant_index: VariantIdx, field_index: usize) {
691 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
692 let field = &variant.fields[field_index];
694 let def_id = field.did;
695 debug!("EncodeContext::encode_field({:?})", def_id);
697 let variant_id = tcx.hir().as_local_hir_id(variant.def_id).unwrap();
698 let variant_data = tcx.hir().expect_variant_data(variant_id);
700 record!(self.per_def.kind[def_id] <- EntryKind::Field);
701 record!(self.per_def.visibility[def_id] <- field.vis);
702 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
703 record!(self.per_def.attributes[def_id] <- variant_data.fields()[field_index].attrs);
704 self.encode_stability(def_id);
705 self.encode_deprecation(def_id);
706 self.encode_item_type(def_id);
707 self.encode_generics(def_id);
708 self.encode_explicit_predicates(def_id);
709 self.encode_inferred_outlives(def_id);
712 fn encode_struct_ctor(&mut self, adt_def_id: DefId, def_id: DefId) {
713 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
715 let adt_def = tcx.adt_def(adt_def_id);
716 let variant = adt_def.non_enum_variant();
718 let data = VariantData {
719 ctor_kind: variant.ctor_kind,
720 discr: variant.discr,
721 ctor: Some(def_id.index),
724 let struct_id = tcx.hir().as_local_hir_id(adt_def_id).unwrap();
725 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
726 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
727 for field in &variant.fields {
728 if ctor_vis.is_at_least(field.vis, tcx) {
729 ctor_vis = field.vis;
733 // If the structure is marked as non_exhaustive then lower the visibility
734 // to within the crate.
735 if adt_def.non_enum_variant().is_field_list_non_exhaustive()
736 && ctor_vis == ty::Visibility::Public
738 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
741 record!(self.per_def.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
742 record!(self.per_def.visibility[def_id] <- ctor_vis);
743 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
744 self.encode_stability(def_id);
745 self.encode_deprecation(def_id);
746 self.encode_item_type(def_id);
747 if variant.ctor_kind == CtorKind::Fn {
748 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
749 self.encode_variances_of(def_id);
751 self.encode_generics(def_id);
752 self.encode_explicit_predicates(def_id);
753 self.encode_inferred_outlives(def_id);
754 self.encode_optimized_mir(def_id);
755 self.encode_promoted_mir(def_id);
758 fn encode_generics(&mut self, def_id: DefId) {
759 debug!("EncodeContext::encode_generics({:?})", def_id);
760 record!(self.per_def.generics[def_id] <- self.tcx.generics_of(def_id));
763 fn encode_explicit_predicates(&mut self, def_id: DefId) {
764 debug!("EncodeContext::encode_explicit_predicates({:?})", def_id);
765 record!(self.per_def.explicit_predicates[def_id] <-
766 self.tcx.explicit_predicates_of(def_id));
769 fn encode_inferred_outlives(&mut self, def_id: DefId) {
770 debug!("EncodeContext::encode_inferred_outlives({:?})", def_id);
771 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
772 if !inferred_outlives.is_empty() {
773 record!(self.per_def.inferred_outlives[def_id] <- inferred_outlives);
777 fn encode_super_predicates(&mut self, def_id: DefId) {
778 debug!("EncodeContext::encode_super_predicates({:?})", def_id);
779 record!(self.per_def.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
782 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
783 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
786 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
787 let ast_item = tcx.hir().expect_trait_item(hir_id);
788 let trait_item = tcx.associated_item(def_id);
790 let container = match trait_item.defaultness {
791 hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
792 hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
793 hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
796 record!(self.per_def.kind[def_id] <- match trait_item.kind {
797 ty::AssocKind::Const => {
799 hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item));
800 let rendered_const = self.lazy(RenderedConst(rendered));
802 EntryKind::AssocConst(
808 ty::AssocKind::Method => {
809 let fn_data = if let hir::TraitItemKind::Method(m_sig, m) = &ast_item.kind {
810 let param_names = match *m {
811 hir::TraitMethod::Required(ref names) => {
812 self.encode_fn_param_names(names)
814 hir::TraitMethod::Provided(body) => {
815 self.encode_fn_param_names_for_body(body)
819 asyncness: m_sig.header.asyncness,
820 constness: hir::Constness::NotConst,
826 EntryKind::Method(self.lazy(MethodData {
829 has_self: trait_item.method_has_self_argument,
832 ty::AssocKind::Type => EntryKind::AssocType(container),
833 ty::AssocKind::OpaqueTy => span_bug!(ast_item.span, "opaque type in trait"),
835 record!(self.per_def.visibility[def_id] <- trait_item.vis);
836 record!(self.per_def.span[def_id] <- ast_item.span);
837 record!(self.per_def.attributes[def_id] <- ast_item.attrs);
838 self.encode_stability(def_id);
839 self.encode_const_stability(def_id);
840 self.encode_deprecation(def_id);
841 match trait_item.kind {
842 ty::AssocKind::Const | ty::AssocKind::Method => {
843 self.encode_item_type(def_id);
845 ty::AssocKind::Type => {
846 if trait_item.defaultness.has_value() {
847 self.encode_item_type(def_id);
850 ty::AssocKind::OpaqueTy => unreachable!(),
852 if trait_item.kind == ty::AssocKind::Method {
853 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
854 self.encode_variances_of(def_id);
856 self.encode_generics(def_id);
857 self.encode_explicit_predicates(def_id);
858 self.encode_inferred_outlives(def_id);
859 self.encode_optimized_mir(def_id);
860 self.encode_promoted_mir(def_id);
863 fn metadata_output_only(&self) -> bool {
864 // MIR optimisation can be skipped when we're just interested in the metadata.
865 !self.tcx.sess.opts.output_types.should_codegen()
868 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
869 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
872 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
873 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
874 let impl_item = self.tcx.associated_item(def_id);
876 let container = match impl_item.defaultness {
877 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
878 hir::Defaultness::Final => AssocContainer::ImplFinal,
879 hir::Defaultness::Default { has_value: false } => {
880 span_bug!(ast_item.span, "impl items always have values (currently)")
884 record!(self.per_def.kind[def_id] <- match impl_item.kind {
885 ty::AssocKind::Const => {
886 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
887 let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
889 EntryKind::AssocConst(
892 self.encode_rendered_const_for_body(body_id))
897 ty::AssocKind::Method => {
898 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.kind {
900 asyncness: sig.header.asyncness,
901 constness: sig.header.constness,
902 param_names: self.encode_fn_param_names_for_body(body),
907 EntryKind::Method(self.lazy(MethodData {
910 has_self: impl_item.method_has_self_argument,
913 ty::AssocKind::OpaqueTy => EntryKind::AssocOpaqueTy(container),
914 ty::AssocKind::Type => EntryKind::AssocType(container)
916 record!(self.per_def.visibility[def_id] <- impl_item.vis);
917 record!(self.per_def.span[def_id] <- ast_item.span);
918 record!(self.per_def.attributes[def_id] <- ast_item.attrs);
919 self.encode_stability(def_id);
920 self.encode_const_stability(def_id);
921 self.encode_deprecation(def_id);
922 self.encode_item_type(def_id);
923 if impl_item.kind == ty::AssocKind::Method {
924 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
925 self.encode_variances_of(def_id);
927 self.encode_generics(def_id);
928 self.encode_explicit_predicates(def_id);
929 self.encode_inferred_outlives(def_id);
930 let mir = match ast_item.kind {
931 hir::ImplItemKind::Const(..) => true,
932 hir::ImplItemKind::Method(ref sig, _) => {
933 let generics = self.tcx.generics_of(def_id);
934 let needs_inline = (generics.requires_monomorphization(self.tcx)
935 || tcx.codegen_fn_attrs(def_id).requests_inline())
936 && !self.metadata_output_only();
937 let is_const_fn = sig.header.constness == hir::Constness::Const;
938 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
939 needs_inline || is_const_fn || always_encode_mir
941 hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(..) => false,
944 self.encode_optimized_mir(def_id);
945 self.encode_promoted_mir(def_id);
949 fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[ast::Name]> {
950 self.tcx.dep_graph.with_ignore(|| {
951 let body = self.tcx.hir().body(body_id);
952 self.lazy(body.params.iter().map(|arg| match arg.pat.kind {
953 hir::PatKind::Binding(_, _, ident, _) => ident.name,
959 fn encode_fn_param_names(&mut self, param_names: &[ast::Ident]) -> Lazy<[ast::Name]> {
960 self.lazy(param_names.iter().map(|ident| ident.name))
963 fn encode_optimized_mir(&mut self, def_id: DefId) {
964 debug!("EntryBuilder::encode_mir({:?})", def_id);
965 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
966 record!(self.per_def.mir[def_id] <- self.tcx.optimized_mir(def_id));
970 fn encode_promoted_mir(&mut self, def_id: DefId) {
971 debug!("EncodeContext::encode_promoted_mir({:?})", def_id);
972 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
973 record!(self.per_def.promoted_mir[def_id] <- self.tcx.promoted_mir(def_id));
977 // Encodes the inherent implementations of a structure, enumeration, or trait.
978 fn encode_inherent_implementations(&mut self, def_id: DefId) {
979 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
980 let implementations = self.tcx.inherent_impls(def_id);
981 if !implementations.is_empty() {
982 record!(self.per_def.inherent_impls[def_id] <- implementations.iter().map(|&def_id| {
983 assert!(def_id.is_local());
989 fn encode_stability(&mut self, def_id: DefId) {
990 debug!("EncodeContext::encode_stability({:?})", def_id);
991 if let Some(stab) = self.tcx.lookup_stability(def_id) {
992 record!(self.per_def.stability[def_id] <- stab)
996 fn encode_const_stability(&mut self, def_id: DefId) {
997 debug!("EncodeContext::encode_const_stability({:?})", def_id);
998 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
999 record!(self.per_def.const_stability[def_id] <- stab)
1003 fn encode_deprecation(&mut self, def_id: DefId) {
1004 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1005 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1006 record!(self.per_def.deprecation[def_id] <- depr);
1010 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1011 let body = self.tcx.hir().body(body_id);
1012 let rendered = hir::print::to_string(self.tcx.hir(), |s| s.print_expr(&body.value));
1013 let rendered_const = &RenderedConst(rendered);
1014 self.lazy(rendered_const)
1017 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1020 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1022 record!(self.per_def.kind[def_id] <- match item.kind {
1023 hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic,
1024 hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic,
1025 hir::ItemKind::Const(_, body_id) => {
1026 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1029 self.encode_rendered_const_for_body(body_id)
1032 hir::ItemKind::Fn(ref sig, .., body) => {
1034 asyncness: sig.header.asyncness,
1035 constness: sig.header.constness,
1036 param_names: self.encode_fn_param_names_for_body(body),
1039 EntryKind::Fn(self.lazy(data))
1041 hir::ItemKind::Mod(ref m) => {
1042 return self.encode_info_for_mod(item.hir_id, m, &item.attrs, &item.vis);
1044 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1045 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1046 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1047 hir::ItemKind::OpaqueTy(..) => EntryKind::OpaqueTy,
1048 hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1049 hir::ItemKind::Struct(ref struct_def, _) => {
1050 let adt_def = self.tcx.adt_def(def_id);
1051 let variant = adt_def.non_enum_variant();
1053 // Encode def_ids for each field and method
1054 // for methods, write all the stuff get_trait_method
1056 let ctor = struct_def.ctor_hir_id().map(|ctor_hir_id| {
1057 self.tcx.hir().local_def_id(ctor_hir_id).index
1060 EntryKind::Struct(self.lazy(VariantData {
1061 ctor_kind: variant.ctor_kind,
1062 discr: variant.discr,
1066 hir::ItemKind::Union(..) => {
1067 let adt_def = self.tcx.adt_def(def_id);
1068 let variant = adt_def.non_enum_variant();
1070 EntryKind::Union(self.lazy(VariantData {
1071 ctor_kind: variant.ctor_kind,
1072 discr: variant.discr,
1076 hir::ItemKind::Impl { defaultness, .. } => {
1077 let trait_ref = self.tcx.impl_trait_ref(def_id);
1078 let polarity = self.tcx.impl_polarity(def_id);
1079 let parent = if let Some(trait_ref) = trait_ref {
1080 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1081 trait_def.ancestors(self.tcx, def_id).nth(1).and_then(|node| {
1083 specialization_graph::Node::Impl(parent) => Some(parent),
1091 // if this is an impl of `CoerceUnsized`, create its
1092 // "unsized info", else just store None
1093 let coerce_unsized_info =
1094 trait_ref.and_then(|t| {
1095 if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1096 Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1102 let data = ImplData {
1105 parent_impl: parent,
1106 coerce_unsized_info,
1109 EntryKind::Impl(self.lazy(data))
1111 hir::ItemKind::Trait(..) => {
1112 let trait_def = self.tcx.trait_def(def_id);
1113 let data = TraitData {
1114 unsafety: trait_def.unsafety,
1115 paren_sugar: trait_def.paren_sugar,
1116 has_auto_impl: self.tcx.trait_is_auto(def_id),
1117 is_marker: trait_def.is_marker,
1120 EntryKind::Trait(self.lazy(data))
1122 hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1123 hir::ItemKind::ExternCrate(_) |
1124 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1126 record!(self.per_def.visibility[def_id] <-
1127 ty::Visibility::from_hir(&item.vis, item.hir_id, tcx));
1128 record!(self.per_def.span[def_id] <- item.span);
1129 record!(self.per_def.attributes[def_id] <- item.attrs);
1130 // FIXME(eddyb) there should be a nicer way to do this.
1132 hir::ItemKind::ForeignMod(ref fm) => record!(self.per_def.children[def_id] <-
1135 .map(|foreign_item| tcx.hir().local_def_id(
1136 foreign_item.hir_id).index)
1138 hir::ItemKind::Enum(..) => record!(self.per_def.children[def_id] <-
1139 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1140 assert!(v.def_id.is_local());
1144 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1145 record!(self.per_def.children[def_id] <-
1146 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1147 assert!(f.did.is_local());
1152 hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1153 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1154 record!(self.per_def.children[def_id] <-
1155 associated_item_def_ids.iter().map(|&def_id| {
1156 assert!(def_id.is_local());
1163 self.encode_stability(def_id);
1164 self.encode_const_stability(def_id);
1165 self.encode_deprecation(def_id);
1167 hir::ItemKind::Static(..)
1168 | hir::ItemKind::Const(..)
1169 | hir::ItemKind::Fn(..)
1170 | hir::ItemKind::TyAlias(..)
1171 | hir::ItemKind::OpaqueTy(..)
1172 | hir::ItemKind::Enum(..)
1173 | hir::ItemKind::Struct(..)
1174 | hir::ItemKind::Union(..)
1175 | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1178 if let hir::ItemKind::Fn(..) = item.kind {
1179 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
1181 if let hir::ItemKind::Impl { .. } = item.kind {
1182 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1183 record!(self.per_def.impl_trait_ref[def_id] <- trait_ref);
1186 self.encode_inherent_implementations(def_id);
1188 hir::ItemKind::Enum(..)
1189 | hir::ItemKind::Struct(..)
1190 | hir::ItemKind::Union(..)
1191 | hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1195 hir::ItemKind::Static(..)
1196 | hir::ItemKind::Const(..)
1197 | hir::ItemKind::Fn(..)
1198 | hir::ItemKind::TyAlias(..)
1199 | hir::ItemKind::Enum(..)
1200 | hir::ItemKind::Struct(..)
1201 | hir::ItemKind::Union(..)
1202 | hir::ItemKind::Impl { .. }
1203 | hir::ItemKind::OpaqueTy(..)
1204 | hir::ItemKind::Trait(..)
1205 | hir::ItemKind::TraitAlias(..) => {
1206 self.encode_generics(def_id);
1207 self.encode_explicit_predicates(def_id);
1208 self.encode_inferred_outlives(def_id);
1213 hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => {
1214 self.encode_super_predicates(def_id);
1219 let mir = match item.kind {
1220 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => true,
1221 hir::ItemKind::Fn(ref sig, ..) => {
1222 let generics = tcx.generics_of(def_id);
1223 let needs_inline = (generics.requires_monomorphization(tcx)
1224 || tcx.codegen_fn_attrs(def_id).requests_inline())
1225 && !self.metadata_output_only();
1226 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1227 needs_inline || sig.header.constness == hir::Constness::Const || always_encode_mir
1232 self.encode_optimized_mir(def_id);
1233 self.encode_promoted_mir(def_id);
1237 /// Serialize the text of exported macros
1238 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) {
1239 use syntax::print::pprust;
1240 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id);
1241 record!(self.per_def.kind[def_id] <- EntryKind::MacroDef(self.lazy(MacroDef {
1242 body: pprust::tts_to_string(macro_def.body.clone()),
1243 legacy: macro_def.legacy,
1245 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1246 record!(self.per_def.span[def_id] <- macro_def.span);
1247 record!(self.per_def.attributes[def_id] <- macro_def.attrs);
1248 self.encode_stability(def_id);
1249 self.encode_deprecation(def_id);
1252 fn encode_info_for_generic_param(
1255 kind: EntryKind<'tcx>,
1258 record!(self.per_def.kind[def_id] <- kind);
1259 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1260 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
1262 self.encode_item_type(def_id);
1266 fn encode_info_for_closure(&mut self, def_id: DefId) {
1267 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1269 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1270 // including on the signature, which is inferred in `typeck_tables_of.
1271 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1272 let ty = self.tcx.typeck_tables_of(def_id).node_type(hir_id);
1274 record!(self.per_def.kind[def_id] <- match ty.kind {
1275 ty::Generator(def_id, ..) => {
1276 let layout = self.tcx.generator_layout(def_id);
1277 let data = GeneratorData {
1278 layout: layout.clone(),
1280 EntryKind::Generator(self.lazy(data))
1283 ty::Closure(..) => EntryKind::Closure,
1285 _ => bug!("closure that is neither generator nor closure"),
1287 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1288 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
1289 record!(self.per_def.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
1290 self.encode_item_type(def_id);
1291 if let ty::Closure(def_id, substs) = ty.kind {
1292 record!(self.per_def.fn_sig[def_id] <- substs.as_closure().sig(def_id, self.tcx));
1294 self.encode_generics(def_id);
1295 self.encode_optimized_mir(def_id);
1296 self.encode_promoted_mir(def_id);
1299 fn encode_info_for_anon_const(&mut self, def_id: DefId) {
1300 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1301 let id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1302 let body_id = self.tcx.hir().body_owned_by(id);
1303 let const_data = self.encode_rendered_const_for_body(body_id);
1304 let qualifs = self.tcx.mir_const_qualif(def_id);
1306 record!(self.per_def.kind[def_id] <- EntryKind::Const(qualifs, const_data));
1307 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1308 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
1309 self.encode_item_type(def_id);
1310 self.encode_generics(def_id);
1311 self.encode_explicit_predicates(def_id);
1312 self.encode_inferred_outlives(def_id);
1313 self.encode_optimized_mir(def_id);
1314 self.encode_promoted_mir(def_id);
1317 fn encode_native_libraries(&mut self) -> Lazy<[NativeLibrary]> {
1318 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1319 self.lazy(used_libraries.iter().cloned())
1322 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1323 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1324 self.lazy(foreign_modules.iter().cloned())
1327 fn encode_proc_macros(&mut self) -> Option<Lazy<[DefIndex]>> {
1328 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
1331 Some(self.lazy(tcx.hir().krate().items.values().filter_map(|item| {
1332 if item.attrs.iter().any(|attr| is_proc_macro_attr(attr)) {
1333 Some(item.hir_id.owner)
1343 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1344 let crates = self.tcx.crates();
1346 let mut deps = crates
1349 let dep = CrateDep {
1350 name: self.tcx.original_crate_name(cnum),
1351 hash: self.tcx.crate_hash(cnum),
1352 host_hash: self.tcx.crate_host_hash(cnum),
1353 kind: self.tcx.dep_kind(cnum),
1354 extra_filename: self.tcx.extra_filename(cnum),
1358 .collect::<Vec<_>>();
1360 deps.sort_by_key(|&(cnum, _)| cnum);
1363 // Sanity-check the crate numbers
1364 let mut expected_cnum = 1;
1365 for &(n, _) in &deps {
1366 assert_eq!(n, CrateNum::new(expected_cnum));
1371 // We're just going to write a list of crate 'name-hash-version's, with
1372 // the assumption that they are numbered 1 to n.
1373 // FIXME (#2166): This is not nearly enough to support correct versioning
1374 // but is enough to get transitive crate dependencies working.
1375 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1378 fn encode_lib_features(&mut self) -> Lazy<[(ast::Name, Option<ast::Name>)]> {
1380 let lib_features = tcx.lib_features();
1381 self.lazy(lib_features.to_vec())
1384 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1386 let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1387 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1390 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1392 let lang_items = tcx.lang_items();
1393 let lang_items = lang_items.items().iter();
1394 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1395 if let Some(def_id) = opt_def_id {
1396 if def_id.is_local() {
1397 return Some((def_id.index, i));
1404 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1406 self.lazy(&tcx.lang_items().missing)
1409 /// Encodes an index, mapping each trait to its (local) implementations.
1410 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1411 debug!("EncodeContext::encode_impls()");
1413 let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() };
1414 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1416 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1418 // Bring everything into deterministic order for hashing
1419 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1421 let all_impls: Vec<_> = all_impls
1423 .map(|(trait_def_id, mut impls)| {
1424 // Bring everything into deterministic order for hashing
1425 impls.sort_by_cached_key(|&def_index| {
1426 tcx.hir().definitions().def_path_hash(def_index)
1430 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1431 impls: self.lazy(&impls),
1436 self.lazy(&all_impls)
1439 // Encodes all symbols exported from this crate into the metadata.
1441 // This pass is seeded off the reachability list calculated in the
1442 // middle::reachable module but filters out items that either don't have a
1443 // symbol associated with them (they weren't translated) or if they're an FFI
1444 // definition (as that's not defined in this crate).
1445 fn encode_exported_symbols(
1447 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1448 ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1449 // The metadata symbol name is special. It should not show up in
1450 // downstream crates.
1451 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1456 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1457 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1464 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1465 let formats = self.tcx.dependency_formats(LOCAL_CRATE);
1466 for (ty, arr) in formats.iter() {
1467 if *ty != config::CrateType::Dylib {
1470 return self.lazy(arr.iter().map(|slot| match *slot {
1471 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1473 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1474 Linkage::Static => Some(LinkagePreference::RequireStatic),
1480 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1483 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1485 record!(self.per_def.kind[def_id] <- match nitem.kind {
1486 hir::ForeignItemKind::Fn(_, ref names, _) => {
1488 asyncness: hir::IsAsync::NotAsync,
1489 constness: if self.tcx.is_const_fn_raw(def_id) {
1490 hir::Constness::Const
1492 hir::Constness::NotConst
1494 param_names: self.encode_fn_param_names(names),
1496 EntryKind::ForeignFn(self.lazy(data))
1498 hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => EntryKind::ForeignMutStatic,
1499 hir::ForeignItemKind::Static(_, hir::Mutability::Not) => EntryKind::ForeignImmStatic,
1500 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1502 record!(self.per_def.visibility[def_id] <-
1503 ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, self.tcx));
1504 record!(self.per_def.span[def_id] <- nitem.span);
1505 record!(self.per_def.attributes[def_id] <- nitem.attrs);
1506 self.encode_stability(def_id);
1507 self.encode_const_stability(def_id);
1508 self.encode_deprecation(def_id);
1509 self.encode_item_type(def_id);
1510 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1511 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
1512 self.encode_variances_of(def_id);
1514 self.encode_generics(def_id);
1515 self.encode_explicit_predicates(def_id);
1516 self.encode_inferred_outlives(def_id);
1520 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1521 impl Visitor<'tcx> for EncodeContext<'tcx> {
1522 type Map = Map<'tcx>;
1524 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
1525 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
1527 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1528 intravisit::walk_expr(self, ex);
1529 self.encode_info_for_expr(ex);
1531 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1532 intravisit::walk_anon_const(self, c);
1533 let def_id = self.tcx.hir().local_def_id(c.hir_id);
1534 self.encode_info_for_anon_const(def_id);
1536 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1537 intravisit::walk_item(self, item);
1538 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1540 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1541 _ => self.encode_info_for_item(def_id, item),
1543 self.encode_addl_info_for_item(item);
1545 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1546 intravisit::walk_foreign_item(self, ni);
1547 let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1548 self.encode_info_for_foreign_item(def_id, ni);
1550 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1551 intravisit::walk_generics(self, generics);
1552 self.encode_info_for_generics(generics);
1554 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) {
1555 self.encode_info_for_macro_def(macro_def);
1559 impl EncodeContext<'tcx> {
1560 fn encode_fields(&mut self, adt_def_id: DefId) {
1561 let def = self.tcx.adt_def(adt_def_id);
1562 for (variant_index, variant) in def.variants.iter_enumerated() {
1563 for (field_index, _field) in variant.fields.iter().enumerate() {
1564 // FIXME(eddyb) `adt_def_id` is leftover from incremental isolation,
1565 // pass `def`, `variant` or `field` instead.
1566 self.encode_field(adt_def_id, variant_index, field_index);
1571 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1572 for param in generics.params {
1573 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1575 GenericParamKind::Lifetime { .. } => continue,
1576 GenericParamKind::Type { ref default, .. } => {
1577 self.encode_info_for_generic_param(
1579 EntryKind::TypeParam,
1583 GenericParamKind::Const { .. } => {
1584 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true);
1590 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1592 hir::ExprKind::Closure(..) => {
1593 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1594 self.encode_info_for_closure(def_id);
1600 /// In some cases, along with the item itself, we also
1601 /// encode some sub-items. Usually we want some info from the item
1602 /// so it's easier to do that here then to wait until we would encounter
1603 /// normally in the visitor walk.
1604 fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1605 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1607 hir::ItemKind::Static(..)
1608 | hir::ItemKind::Const(..)
1609 | hir::ItemKind::Fn(..)
1610 | hir::ItemKind::Mod(..)
1611 | hir::ItemKind::ForeignMod(..)
1612 | hir::ItemKind::GlobalAsm(..)
1613 | hir::ItemKind::ExternCrate(..)
1614 | hir::ItemKind::Use(..)
1615 | hir::ItemKind::TyAlias(..)
1616 | hir::ItemKind::OpaqueTy(..)
1617 | hir::ItemKind::TraitAlias(..) => {
1618 // no sub-item recording needed in these cases
1620 hir::ItemKind::Enum(..) => {
1621 self.encode_fields(def_id);
1623 let def = self.tcx.adt_def(def_id);
1624 for (i, variant) in def.variants.iter_enumerated() {
1625 // FIXME(eddyb) `def_id` is leftover from incremental isolation,
1626 // pass `def` or `variant` instead.
1627 self.encode_enum_variant_info(def_id, i);
1629 // FIXME(eddyb) `def_id` is leftover from incremental isolation,
1630 // pass `def`, `variant` or `ctor_def_id` instead.
1631 if let Some(_ctor_def_id) = variant.ctor_def_id {
1632 self.encode_enum_variant_ctor(def_id, i);
1636 hir::ItemKind::Struct(ref struct_def, _) => {
1637 self.encode_fields(def_id);
1639 // If the struct has a constructor, encode it.
1640 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1641 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1642 self.encode_struct_ctor(def_id, ctor_def_id);
1645 hir::ItemKind::Union(..) => {
1646 self.encode_fields(def_id);
1648 hir::ItemKind::Impl { .. } => {
1649 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1650 self.encode_info_for_impl_item(trait_item_def_id);
1653 hir::ItemKind::Trait(..) => {
1654 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1655 self.encode_info_for_trait_item(item_def_id);
1662 struct ImplVisitor<'tcx> {
1664 impls: FxHashMap<DefId, Vec<DefIndex>>,
1667 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1668 fn visit_item(&mut self, item: &hir::Item<'_>) {
1669 if let hir::ItemKind::Impl { .. } = item.kind {
1670 let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1671 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1672 self.impls.entry(trait_ref.def_id).or_default().push(impl_id.index);
1677 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
1679 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
1680 // handled in `visit_item` above
1684 // NOTE(eddyb) The following comment was preserved for posterity, even
1685 // though it's no longer relevant as EBML (which uses nested & tagged
1686 // "documents") was replaced with a scheme that can't go out of bounds.
1688 // And here we run into yet another obscure archive bug: in which metadata
1689 // loaded from archives may have trailing garbage bytes. Awhile back one of
1690 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1691 // and opt) by having ebml generate an out-of-bounds panic when looking at
1694 // Upon investigation it turned out that the metadata file inside of an rlib
1695 // (and ar archive) was being corrupted. Some compilations would generate a
1696 // metadata file which would end in a few extra bytes, while other
1697 // compilations would not have these extra bytes appended to the end. These
1698 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1699 // being interpreted causing the out-of-bounds.
1701 // The root cause of why these extra bytes were appearing was never
1702 // discovered, and in the meantime the solution we're employing is to insert
1703 // the length of the metadata to the start of the metadata. Later on this
1704 // will allow us to slice the metadata to the precise length that we just
1705 // generated regardless of trailing bytes that end up in it.
1707 pub(super) fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
1708 let mut encoder = opaque::Encoder::new(vec![]);
1709 encoder.emit_raw_bytes(METADATA_HEADER);
1711 // Will be filled with the root position after encoding everything.
1712 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1714 // Since encoding metadata is not in a query, and nothing is cached,
1715 // there's no need to do dep-graph tracking for any of it.
1716 let (root, mut result) = tcx.dep_graph.with_ignore(move || {
1717 let mut ecx = EncodeContext {
1720 per_def: Default::default(),
1721 lazy_state: LazyState::NoNode,
1722 type_shorthands: Default::default(),
1723 predicate_shorthands: Default::default(),
1724 source_file_cache: tcx.sess.source_map().files()[0].clone(),
1725 interpret_allocs: Default::default(),
1726 interpret_allocs_inverse: Default::default(),
1729 // Encode the rustc version string in a predictable location.
1730 rustc_version().encode(&mut ecx).unwrap();
1732 // Encode all the entries and extra information in the crate,
1733 // culminating in the `CrateRoot` which points to all of it.
1734 let root = ecx.encode_crate_root();
1735 (root, ecx.opaque.into_inner())
1738 // Encode the root position.
1739 let header = METADATA_HEADER.len();
1740 let pos = root.position.get();
1741 result[header + 0] = (pos >> 24) as u8;
1742 result[header + 1] = (pos >> 16) as u8;
1743 result[header + 2] = (pos >> 8) as u8;
1744 result[header + 3] = (pos >> 0) as u8;
1746 EncodedMetadata { raw_data: result }