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};
30 use rustc_span::source_map::Spanned;
31 use rustc_span::symbol::{kw, sym, Ident, Symbol};
32 use rustc_span::{self, FileName, SourceFile, Span};
34 use std::num::NonZeroUsize;
39 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
40 use rustc_hir::itemlikevisit::ItemLikeVisitor;
42 struct EncodeContext<'tcx> {
43 opaque: opaque::Encoder,
46 per_def: PerDefTableBuilders<'tcx>,
48 lazy_state: LazyState,
49 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
50 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
52 interpret_allocs: FxHashMap<interpret::AllocId, usize>,
53 interpret_allocs_inverse: Vec<interpret::AllocId>,
55 // This is used to speed up Span encoding.
56 source_file_cache: Lrc<SourceFile>,
59 macro_rules! encoder_methods {
60 ($($name:ident($ty:ty);)*) => {
61 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
62 self.opaque.$name(value)
67 impl<'tcx> Encoder for EncodeContext<'tcx> {
68 type Error = <opaque::Encoder as Encoder>::Error;
70 fn emit_unit(&mut self) -> Result<(), Self::Error> {
97 impl<'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'tcx> {
98 fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
99 self.emit_lazy_distance(*lazy)
103 impl<'tcx, T> SpecializedEncoder<Lazy<[T]>> for EncodeContext<'tcx> {
104 fn specialized_encode(&mut self, lazy: &Lazy<[T]>) -> Result<(), Self::Error> {
105 self.emit_usize(lazy.meta)?;
109 self.emit_lazy_distance(*lazy)
113 impl<'tcx, I: Idx, T> SpecializedEncoder<Lazy<Table<I, T>>> for EncodeContext<'tcx>
115 Option<T>: FixedSizeEncoding,
117 fn specialized_encode(&mut self, lazy: &Lazy<Table<I, T>>) -> Result<(), Self::Error> {
118 self.emit_usize(lazy.meta)?;
119 self.emit_lazy_distance(*lazy)
123 impl<'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'tcx> {
125 fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
126 self.emit_u32(cnum.as_u32())
130 impl<'tcx> SpecializedEncoder<DefId> for EncodeContext<'tcx> {
132 fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
133 let DefId { krate, index } = *def_id;
140 impl<'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'tcx> {
142 fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
143 self.emit_u32(def_index.as_u32())
147 impl<'tcx> SpecializedEncoder<Span> for EncodeContext<'tcx> {
148 fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
150 return TAG_INVALID_SPAN.encode(self);
153 let span = span.data();
155 // The Span infrastructure should make sure that this invariant holds:
156 debug_assert!(span.lo <= span.hi);
158 if !self.source_file_cache.contains(span.lo) {
159 let source_map = self.tcx.sess.source_map();
160 let source_file_index = source_map.lookup_source_file_idx(span.lo);
161 self.source_file_cache = source_map.files()[source_file_index].clone();
164 if !self.source_file_cache.contains(span.hi) {
165 // Unfortunately, macro expansion still sometimes generates Spans
166 // that malformed in this way.
167 return TAG_INVALID_SPAN.encode(self);
170 // HACK(eddyb) there's no way to indicate which crate a Span is coming
171 // from right now, so decoding would fail to find the SourceFile if
172 // it's not local to the crate the Span is found in.
173 if self.source_file_cache.is_imported() {
174 return TAG_INVALID_SPAN.encode(self);
177 TAG_VALID_SPAN.encode(self)?;
178 span.lo.encode(self)?;
180 // Encode length which is usually less than span.hi and profits more
181 // from the variable-length integer encoding that we use.
182 let len = span.hi - span.lo;
185 // Don't encode the expansion context.
189 impl SpecializedEncoder<Ident> for EncodeContext<'tcx> {
190 fn specialized_encode(&mut self, ident: &Ident) -> Result<(), Self::Error> {
191 // FIXME(jseyfried): intercrate hygiene
192 ident.name.encode(self)
196 impl<'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'tcx> {
198 fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
199 self.specialized_encode(&def_id.to_def_id())
203 impl<'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'tcx> {
204 fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
205 ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
209 impl<'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'tcx> {
210 fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
211 use std::collections::hash_map::Entry;
212 let index = match self.interpret_allocs.entry(*alloc_id) {
213 Entry::Occupied(e) => *e.get(),
214 Entry::Vacant(e) => {
215 let idx = self.interpret_allocs_inverse.len();
216 self.interpret_allocs_inverse.push(*alloc_id);
226 impl<'tcx> SpecializedEncoder<&'tcx [(ty::Predicate<'tcx>, Span)]> for EncodeContext<'tcx> {
227 fn specialized_encode(
229 predicates: &&'tcx [(ty::Predicate<'tcx>, Span)],
230 ) -> Result<(), Self::Error> {
231 ty_codec::encode_spanned_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
235 impl<'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'tcx> {
236 fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
237 f.encode_opaque(&mut self.opaque)
241 impl<'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>> for EncodeContext<'tcx> {
242 fn specialized_encode(&mut self, _: &mir::ClearCrossCrate<T>) -> Result<(), Self::Error> {
247 impl<'tcx> TyEncoder for EncodeContext<'tcx> {
248 fn position(&self) -> usize {
249 self.opaque.position()
253 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
254 trait EncodeContentsForLazy<T: ?Sized + LazyMeta> {
255 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) -> T::Meta;
258 impl<T: Encodable> EncodeContentsForLazy<T> for &T {
259 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) {
260 self.encode(ecx).unwrap()
264 impl<T: Encodable> EncodeContentsForLazy<T> for T {
265 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) {
266 self.encode(ecx).unwrap()
270 impl<I, T: Encodable> EncodeContentsForLazy<[T]> for I
273 I::Item: EncodeContentsForLazy<T>,
275 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) -> usize {
276 self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
280 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would
281 // normally need extra variables to avoid errors about multiple mutable borrows.
282 macro_rules! record {
283 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
286 let lazy = $self.lazy(value);
287 $self.$tables.$table.set($def_id.index, lazy);
292 impl<'tcx> EncodeContext<'tcx> {
293 fn emit_lazy_distance<T: ?Sized + LazyMeta>(
296 ) -> Result<(), <Self as Encoder>::Error> {
297 let min_end = lazy.position.get() + T::min_size(lazy.meta);
298 let distance = match self.lazy_state {
299 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
300 LazyState::NodeStart(start) => {
301 let start = start.get();
302 assert!(min_end <= start);
305 LazyState::Previous(last_min_end) => {
307 last_min_end <= lazy.position,
308 "make sure that the calls to `lazy*` \
309 are in the same order as the metadata fields",
311 lazy.position.get() - last_min_end.get()
314 self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap());
315 self.emit_usize(distance)
318 fn lazy<T: ?Sized + LazyMeta>(&mut self, value: impl EncodeContentsForLazy<T>) -> Lazy<T> {
319 let pos = NonZeroUsize::new(self.position()).unwrap();
321 assert_eq!(self.lazy_state, LazyState::NoNode);
322 self.lazy_state = LazyState::NodeStart(pos);
323 let meta = value.encode_contents_for_lazy(self);
324 self.lazy_state = LazyState::NoNode;
326 assert!(pos.get() + <T>::min_size(meta) <= self.position());
328 Lazy::from_position_and_meta(pos, meta)
331 fn encode_info_for_items(&mut self) {
332 let krate = self.tcx.hir().krate();
333 let vis = Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public };
334 self.encode_info_for_mod(hir::CRATE_HIR_ID, &krate.module, &krate.attrs, &vis);
335 krate.visit_all_item_likes(&mut self.as_deep_visitor());
336 for macro_def in krate.exported_macros {
337 self.visit_macro_def(macro_def);
341 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
342 let definitions = self.tcx.hir().definitions();
343 self.lazy(definitions.def_path_table())
346 fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> {
347 let source_map = self.tcx.sess.source_map();
348 let all_source_files = source_map.files();
350 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
352 let adapted = all_source_files
354 .filter(|source_file| {
355 // No need to re-export imported source_files, as any downstream
356 // crate will import them from their original source.
357 // FIXME(eddyb) the `Span` encoding should take that into account.
358 !source_file.is_imported()
361 match source_file.name {
362 // This path of this SourceFile has been modified by
363 // path-remapping, so we use it verbatim (and avoid
364 // cloning the whole map in the process).
365 _ if source_file.name_was_remapped => source_file.clone(),
367 // Otherwise expand all paths to absolute paths because
368 // any relative paths are potentially relative to a
370 FileName::Real(ref name) => {
371 let mut adapted = (**source_file).clone();
372 adapted.name = Path::new(&working_dir).join(name).into();
373 adapted.name_hash = {
374 let mut hasher: StableHasher = StableHasher::new();
375 adapted.name.hash(&mut hasher);
376 hasher.finish::<u128>()
381 // expanded code, not from a file
382 _ => source_file.clone(),
385 .collect::<Vec<_>>();
387 self.lazy(adapted.iter().map(|rc| &**rc))
390 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
391 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
393 let mut i = self.position();
395 let crate_deps = self.encode_crate_deps();
396 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
397 let dep_bytes = self.position() - i;
399 // Encode the lib features.
401 let lib_features = self.encode_lib_features();
402 let lib_feature_bytes = self.position() - i;
404 // Encode the language items.
406 let lang_items = self.encode_lang_items();
407 let lang_items_missing = self.encode_lang_items_missing();
408 let lang_item_bytes = self.position() - i;
410 // Encode the diagnostic items.
412 let diagnostic_items = self.encode_diagnostic_items();
413 let diagnostic_item_bytes = self.position() - i;
415 // Encode the native libraries used
417 let native_libraries = self.encode_native_libraries();
418 let native_lib_bytes = self.position() - i;
420 let foreign_modules = self.encode_foreign_modules();
424 let source_map = self.encode_source_map();
425 let source_map_bytes = self.position() - i;
427 // Encode DefPathTable
429 let def_path_table = self.encode_def_path_table();
430 let def_path_table_bytes = self.position() - i;
432 // Encode the def IDs of impls, for coherence checking.
434 let impls = self.encode_impls();
435 let impl_bytes = self.position() - i;
437 // Encode exported symbols info.
439 let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
440 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
441 let exported_symbols_bytes = self.position() - i;
447 self.encode_info_for_items();
448 let item_bytes = self.position() - i;
450 // Encode the allocation index
451 let interpret_alloc_index = {
452 let mut interpret_alloc_index = Vec::new();
454 trace!("beginning to encode alloc ids");
456 let new_n = self.interpret_allocs_inverse.len();
457 // if we have found new ids, serialize those, too
462 trace!("encoding {} further alloc ids", new_n - n);
463 for idx in n..new_n {
464 let id = self.interpret_allocs_inverse[idx];
465 let pos = self.position() as u32;
466 interpret_alloc_index.push(pos);
467 interpret::specialized_encode_alloc_id(self, tcx, id).unwrap();
471 self.lazy(interpret_alloc_index)
475 let per_def = self.per_def.encode(&mut self.opaque);
476 let per_def_bytes = self.position() - i;
478 // Encode the proc macro data
480 let proc_macro_data = self.encode_proc_macros();
481 let proc_macro_data_bytes = self.position() - i;
483 let attrs = tcx.hir().krate_attrs();
484 let has_default_lib_allocator = attr::contains_name(&attrs, sym::default_lib_allocator);
486 let root = self.lazy(CrateRoot {
487 name: tcx.crate_name(LOCAL_CRATE),
488 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
489 triple: tcx.sess.opts.target_triple.clone(),
490 hash: tcx.crate_hash(LOCAL_CRATE),
491 disambiguator: tcx.sess.local_crate_disambiguator(),
492 panic_strategy: tcx.sess.panic_strategy(),
493 edition: tcx.sess.edition(),
494 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
495 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
496 has_default_lib_allocator: has_default_lib_allocator,
497 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
498 proc_macro_decls_static: if is_proc_macro {
499 let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap();
505 proc_macro_stability: if is_proc_macro {
506 tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied()
510 compiler_builtins: attr::contains_name(&attrs, sym::compiler_builtins),
511 needs_allocator: attr::contains_name(&attrs, sym::needs_allocator),
512 needs_panic_runtime: attr::contains_name(&attrs, sym::needs_panic_runtime),
513 no_builtins: attr::contains_name(&attrs, sym::no_builtins),
514 panic_runtime: attr::contains_name(&attrs, sym::panic_runtime),
515 profiler_runtime: attr::contains_name(&attrs, sym::profiler_runtime),
516 symbol_mangling_version: tcx.sess.opts.debugging_opts.symbol_mangling_version,
519 dylib_dependency_formats,
530 interpret_alloc_index,
534 let total_bytes = self.position();
536 if self.tcx.sess.meta_stats() {
537 let mut zero_bytes = 0;
538 for e in self.opaque.data.iter() {
544 println!("metadata stats:");
545 println!(" dep bytes: {}", dep_bytes);
546 println!(" lib feature bytes: {}", lib_feature_bytes);
547 println!(" lang item bytes: {}", lang_item_bytes);
548 println!(" diagnostic item bytes: {}", diagnostic_item_bytes);
549 println!(" native bytes: {}", native_lib_bytes);
550 println!(" source_map bytes: {}", source_map_bytes);
551 println!(" impl bytes: {}", impl_bytes);
552 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
553 println!(" def-path table bytes: {}", def_path_table_bytes);
554 println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
555 println!(" item bytes: {}", item_bytes);
556 println!(" per-def table bytes: {}", per_def_bytes);
557 println!(" zero bytes: {}", zero_bytes);
558 println!(" total bytes: {}", total_bytes);
565 impl EncodeContext<'tcx> {
566 fn encode_variances_of(&mut self, def_id: DefId) {
567 debug!("EncodeContext::encode_variances_of({:?})", def_id);
568 record!(self.per_def.variances[def_id] <- &self.tcx.variances_of(def_id)[..]);
571 fn encode_item_type(&mut self, def_id: DefId) {
572 debug!("EncodeContext::encode_item_type({:?})", def_id);
573 record!(self.per_def.ty[def_id] <- self.tcx.type_of(def_id));
576 fn encode_enum_variant_info(&mut self, enum_did: DefId, index: VariantIdx) {
578 let def = tcx.adt_def(enum_did);
579 let variant = &def.variants[index];
580 let def_id = variant.def_id;
581 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
583 let data = VariantData {
584 ctor_kind: variant.ctor_kind,
585 discr: variant.discr,
586 ctor: variant.ctor_def_id.map(|did| did.index),
589 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
590 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
592 record!(self.per_def.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
593 record!(self.per_def.visibility[def_id] <-
594 ty::Visibility::from_hir(enum_vis, enum_id, self.tcx));
595 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
596 record!(self.per_def.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
597 record!(self.per_def.children[def_id] <- variant.fields.iter().map(|f| {
598 assert!(f.did.is_local());
601 self.encode_stability(def_id);
602 self.encode_deprecation(def_id);
603 self.encode_item_type(def_id);
604 if variant.ctor_kind == CtorKind::Fn {
605 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
606 if let Some(ctor_def_id) = variant.ctor_def_id {
607 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
609 // FIXME(eddyb) is this ever used?
610 self.encode_variances_of(def_id);
612 self.encode_generics(def_id);
613 self.encode_explicit_predicates(def_id);
614 self.encode_inferred_outlives(def_id);
615 self.encode_optimized_mir(def_id);
616 self.encode_promoted_mir(def_id);
619 fn encode_enum_variant_ctor(&mut self, enum_did: DefId, index: VariantIdx) {
621 let def = tcx.adt_def(enum_did);
622 let variant = &def.variants[index];
623 let def_id = variant.ctor_def_id.unwrap();
624 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
626 // FIXME(eddyb) encode only the `CtorKind` for constructors.
627 let data = VariantData {
628 ctor_kind: variant.ctor_kind,
629 discr: variant.discr,
630 ctor: Some(def_id.index),
633 // Variant constructors have the same visibility as the parent enums, unless marked as
634 // non-exhaustive, in which case they are lowered to `pub(crate)`.
635 let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
636 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
637 let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx);
638 if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public {
639 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
642 record!(self.per_def.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
643 record!(self.per_def.visibility[def_id] <- ctor_vis);
644 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
645 self.encode_stability(def_id);
646 self.encode_deprecation(def_id);
647 self.encode_item_type(def_id);
648 if variant.ctor_kind == CtorKind::Fn {
649 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
650 self.encode_variances_of(def_id);
652 self.encode_generics(def_id);
653 self.encode_explicit_predicates(def_id);
654 self.encode_inferred_outlives(def_id);
655 self.encode_optimized_mir(def_id);
656 self.encode_promoted_mir(def_id);
659 fn encode_info_for_mod(
663 attrs: &[ast::Attribute],
664 vis: &hir::Visibility<'_>,
667 let def_id = tcx.hir().local_def_id(id);
668 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
671 reexports: match tcx.module_exports(def_id) {
672 Some(exports) => self.lazy(exports),
677 record!(self.per_def.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
678 record!(self.per_def.visibility[def_id] <- ty::Visibility::from_hir(vis, id, self.tcx));
679 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
680 record!(self.per_def.attributes[def_id] <- attrs);
681 record!(self.per_def.children[def_id] <- md.item_ids.iter().map(|item_id| {
682 tcx.hir().local_def_id(item_id.id).index
684 self.encode_stability(def_id);
685 self.encode_deprecation(def_id);
688 fn encode_field(&mut self, adt_def_id: DefId, variant_index: VariantIdx, field_index: usize) {
690 let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
691 let field = &variant.fields[field_index];
693 let def_id = field.did;
694 debug!("EncodeContext::encode_field({:?})", def_id);
696 let variant_id = tcx.hir().as_local_hir_id(variant.def_id).unwrap();
697 let variant_data = tcx.hir().expect_variant_data(variant_id);
699 record!(self.per_def.kind[def_id] <- EntryKind::Field);
700 record!(self.per_def.visibility[def_id] <- field.vis);
701 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
702 record!(self.per_def.attributes[def_id] <- variant_data.fields()[field_index].attrs);
703 self.encode_stability(def_id);
704 self.encode_deprecation(def_id);
705 self.encode_item_type(def_id);
706 self.encode_generics(def_id);
707 self.encode_explicit_predicates(def_id);
708 self.encode_inferred_outlives(def_id);
711 fn encode_struct_ctor(&mut self, adt_def_id: DefId, def_id: DefId) {
712 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
714 let adt_def = tcx.adt_def(adt_def_id);
715 let variant = adt_def.non_enum_variant();
717 let data = VariantData {
718 ctor_kind: variant.ctor_kind,
719 discr: variant.discr,
720 ctor: Some(def_id.index),
723 let struct_id = tcx.hir().as_local_hir_id(adt_def_id).unwrap();
724 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
725 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
726 for field in &variant.fields {
727 if ctor_vis.is_at_least(field.vis, tcx) {
728 ctor_vis = field.vis;
732 // If the structure is marked as non_exhaustive then lower the visibility
733 // to within the crate.
734 if adt_def.non_enum_variant().is_field_list_non_exhaustive()
735 && ctor_vis == ty::Visibility::Public
737 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
740 record!(self.per_def.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
741 record!(self.per_def.visibility[def_id] <- ctor_vis);
742 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
743 self.encode_stability(def_id);
744 self.encode_deprecation(def_id);
745 self.encode_item_type(def_id);
746 if variant.ctor_kind == CtorKind::Fn {
747 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
748 self.encode_variances_of(def_id);
750 self.encode_generics(def_id);
751 self.encode_explicit_predicates(def_id);
752 self.encode_inferred_outlives(def_id);
753 self.encode_optimized_mir(def_id);
754 self.encode_promoted_mir(def_id);
757 fn encode_generics(&mut self, def_id: DefId) {
758 debug!("EncodeContext::encode_generics({:?})", def_id);
759 record!(self.per_def.generics[def_id] <- self.tcx.generics_of(def_id));
762 fn encode_explicit_predicates(&mut self, def_id: DefId) {
763 debug!("EncodeContext::encode_explicit_predicates({:?})", def_id);
764 record!(self.per_def.explicit_predicates[def_id] <-
765 self.tcx.explicit_predicates_of(def_id));
768 fn encode_inferred_outlives(&mut self, def_id: DefId) {
769 debug!("EncodeContext::encode_inferred_outlives({:?})", def_id);
770 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
771 if !inferred_outlives.is_empty() {
772 record!(self.per_def.inferred_outlives[def_id] <- inferred_outlives);
776 fn encode_super_predicates(&mut self, def_id: DefId) {
777 debug!("EncodeContext::encode_super_predicates({:?})", def_id);
778 record!(self.per_def.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
781 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
782 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
785 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
786 let ast_item = tcx.hir().expect_trait_item(hir_id);
787 let trait_item = tcx.associated_item(def_id);
789 let container = match trait_item.defaultness {
790 hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
791 hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
792 hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
795 record!(self.per_def.kind[def_id] <- match trait_item.kind {
796 ty::AssocKind::Const => {
798 hir::print::to_string(&self.tcx.hir(), |s| s.print_trait_item(ast_item));
799 let rendered_const = self.lazy(RenderedConst(rendered));
801 EntryKind::AssocConst(
807 ty::AssocKind::Method => {
808 let fn_data = if let hir::TraitItemKind::Method(m_sig, m) = &ast_item.kind {
809 let param_names = match *m {
810 hir::TraitMethod::Required(ref names) => {
811 self.encode_fn_param_names(names)
813 hir::TraitMethod::Provided(body) => {
814 self.encode_fn_param_names_for_body(body)
818 asyncness: m_sig.header.asyncness,
819 constness: hir::Constness::NotConst,
825 EntryKind::Method(self.lazy(MethodData {
828 has_self: trait_item.method_has_self_argument,
831 ty::AssocKind::Type => EntryKind::AssocType(container),
832 ty::AssocKind::OpaqueTy => span_bug!(ast_item.span, "opaque type in trait"),
834 record!(self.per_def.visibility[def_id] <- trait_item.vis);
835 record!(self.per_def.span[def_id] <- ast_item.span);
836 record!(self.per_def.attributes[def_id] <- ast_item.attrs);
837 self.encode_stability(def_id);
838 self.encode_const_stability(def_id);
839 self.encode_deprecation(def_id);
840 match trait_item.kind {
841 ty::AssocKind::Const | ty::AssocKind::Method => {
842 self.encode_item_type(def_id);
844 ty::AssocKind::Type => {
845 if trait_item.defaultness.has_value() {
846 self.encode_item_type(def_id);
849 ty::AssocKind::OpaqueTy => unreachable!(),
851 if trait_item.kind == ty::AssocKind::Method {
852 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
853 self.encode_variances_of(def_id);
855 self.encode_generics(def_id);
856 self.encode_explicit_predicates(def_id);
857 self.encode_inferred_outlives(def_id);
858 self.encode_optimized_mir(def_id);
859 self.encode_promoted_mir(def_id);
862 fn metadata_output_only(&self) -> bool {
863 // MIR optimisation can be skipped when we're just interested in the metadata.
864 !self.tcx.sess.opts.output_types.should_codegen()
867 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
868 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
871 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
872 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
873 let impl_item = self.tcx.associated_item(def_id);
875 let container = match impl_item.defaultness {
876 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
877 hir::Defaultness::Final => AssocContainer::ImplFinal,
878 hir::Defaultness::Default { has_value: false } => {
879 span_bug!(ast_item.span, "impl items always have values (currently)")
883 record!(self.per_def.kind[def_id] <- match impl_item.kind {
884 ty::AssocKind::Const => {
885 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
886 let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
888 EntryKind::AssocConst(
891 self.encode_rendered_const_for_body(body_id))
896 ty::AssocKind::Method => {
897 let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.kind {
899 asyncness: sig.header.asyncness,
900 constness: sig.header.constness,
901 param_names: self.encode_fn_param_names_for_body(body),
906 EntryKind::Method(self.lazy(MethodData {
909 has_self: impl_item.method_has_self_argument,
912 ty::AssocKind::OpaqueTy => EntryKind::AssocOpaqueTy(container),
913 ty::AssocKind::Type => EntryKind::AssocType(container)
915 record!(self.per_def.visibility[def_id] <- impl_item.vis);
916 record!(self.per_def.span[def_id] <- ast_item.span);
917 record!(self.per_def.attributes[def_id] <- ast_item.attrs);
918 self.encode_stability(def_id);
919 self.encode_const_stability(def_id);
920 self.encode_deprecation(def_id);
921 self.encode_item_type(def_id);
922 if impl_item.kind == ty::AssocKind::Method {
923 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
924 self.encode_variances_of(def_id);
926 self.encode_generics(def_id);
927 self.encode_explicit_predicates(def_id);
928 self.encode_inferred_outlives(def_id);
929 let mir = match ast_item.kind {
930 hir::ImplItemKind::Const(..) => true,
931 hir::ImplItemKind::Method(ref sig, _) => {
932 let generics = self.tcx.generics_of(def_id);
933 let needs_inline = (generics.requires_monomorphization(self.tcx)
934 || tcx.codegen_fn_attrs(def_id).requests_inline())
935 && !self.metadata_output_only();
936 let is_const_fn = sig.header.constness == hir::Constness::Const;
937 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
938 needs_inline || is_const_fn || always_encode_mir
940 hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(..) => false,
943 self.encode_optimized_mir(def_id);
944 self.encode_promoted_mir(def_id);
948 fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[ast::Name]> {
949 self.tcx.dep_graph.with_ignore(|| {
950 let body = self.tcx.hir().body(body_id);
951 self.lazy(body.params.iter().map(|arg| match arg.pat.kind {
952 hir::PatKind::Binding(_, _, ident, _) => ident.name,
958 fn encode_fn_param_names(&mut self, param_names: &[ast::Ident]) -> Lazy<[ast::Name]> {
959 self.lazy(param_names.iter().map(|ident| ident.name))
962 fn encode_optimized_mir(&mut self, def_id: DefId) {
963 debug!("EntryBuilder::encode_mir({:?})", def_id);
964 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
965 record!(self.per_def.mir[def_id] <- self.tcx.optimized_mir(def_id));
969 fn encode_promoted_mir(&mut self, def_id: DefId) {
970 debug!("EncodeContext::encode_promoted_mir({:?})", def_id);
971 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
972 record!(self.per_def.promoted_mir[def_id] <- self.tcx.promoted_mir(def_id));
976 // Encodes the inherent implementations of a structure, enumeration, or trait.
977 fn encode_inherent_implementations(&mut self, def_id: DefId) {
978 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
979 let implementations = self.tcx.inherent_impls(def_id);
980 if !implementations.is_empty() {
981 record!(self.per_def.inherent_impls[def_id] <- implementations.iter().map(|&def_id| {
982 assert!(def_id.is_local());
988 fn encode_stability(&mut self, def_id: DefId) {
989 debug!("EncodeContext::encode_stability({:?})", def_id);
990 if let Some(stab) = self.tcx.lookup_stability(def_id) {
991 record!(self.per_def.stability[def_id] <- stab)
995 fn encode_const_stability(&mut self, def_id: DefId) {
996 debug!("EncodeContext::encode_const_stability({:?})", def_id);
997 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
998 record!(self.per_def.const_stability[def_id] <- stab)
1002 fn encode_deprecation(&mut self, def_id: DefId) {
1003 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1004 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1005 record!(self.per_def.deprecation[def_id] <- depr);
1009 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1010 let body = self.tcx.hir().body(body_id);
1011 let rendered = hir::print::to_string(&self.tcx.hir(), |s| s.print_expr(&body.value));
1012 let rendered_const = &RenderedConst(rendered);
1013 self.lazy(rendered_const)
1016 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1019 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1021 record!(self.per_def.kind[def_id] <- match item.kind {
1022 hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic,
1023 hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic,
1024 hir::ItemKind::Const(_, body_id) => {
1025 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1028 self.encode_rendered_const_for_body(body_id)
1031 hir::ItemKind::Fn(ref sig, .., body) => {
1033 asyncness: sig.header.asyncness,
1034 constness: sig.header.constness,
1035 param_names: self.encode_fn_param_names_for_body(body),
1038 EntryKind::Fn(self.lazy(data))
1040 hir::ItemKind::Mod(ref m) => {
1041 return self.encode_info_for_mod(item.hir_id, m, &item.attrs, &item.vis);
1043 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1044 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1045 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1046 hir::ItemKind::OpaqueTy(..) => EntryKind::OpaqueTy,
1047 hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1048 hir::ItemKind::Struct(ref struct_def, _) => {
1049 let adt_def = self.tcx.adt_def(def_id);
1050 let variant = adt_def.non_enum_variant();
1052 // Encode def_ids for each field and method
1053 // for methods, write all the stuff get_trait_method
1055 let ctor = struct_def.ctor_hir_id().map(|ctor_hir_id| {
1056 self.tcx.hir().local_def_id(ctor_hir_id).index
1059 EntryKind::Struct(self.lazy(VariantData {
1060 ctor_kind: variant.ctor_kind,
1061 discr: variant.discr,
1065 hir::ItemKind::Union(..) => {
1066 let adt_def = self.tcx.adt_def(def_id);
1067 let variant = adt_def.non_enum_variant();
1069 EntryKind::Union(self.lazy(VariantData {
1070 ctor_kind: variant.ctor_kind,
1071 discr: variant.discr,
1075 hir::ItemKind::Impl { defaultness, .. } => {
1076 let trait_ref = self.tcx.impl_trait_ref(def_id);
1077 let polarity = self.tcx.impl_polarity(def_id);
1078 let parent = if let Some(trait_ref) = trait_ref {
1079 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1080 trait_def.ancestors(self.tcx, def_id).nth(1).and_then(|node| {
1082 specialization_graph::Node::Impl(parent) => Some(parent),
1090 // if this is an impl of `CoerceUnsized`, create its
1091 // "unsized info", else just store None
1092 let coerce_unsized_info =
1093 trait_ref.and_then(|t| {
1094 if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1095 Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1101 let data = ImplData {
1104 parent_impl: parent,
1105 coerce_unsized_info,
1108 EntryKind::Impl(self.lazy(data))
1110 hir::ItemKind::Trait(..) => {
1111 let trait_def = self.tcx.trait_def(def_id);
1112 let data = TraitData {
1113 unsafety: trait_def.unsafety,
1114 paren_sugar: trait_def.paren_sugar,
1115 has_auto_impl: self.tcx.trait_is_auto(def_id),
1116 is_marker: trait_def.is_marker,
1119 EntryKind::Trait(self.lazy(data))
1121 hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1122 hir::ItemKind::ExternCrate(_) |
1123 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1125 record!(self.per_def.visibility[def_id] <-
1126 ty::Visibility::from_hir(&item.vis, item.hir_id, tcx));
1127 record!(self.per_def.span[def_id] <- item.span);
1128 record!(self.per_def.attributes[def_id] <- item.attrs);
1129 // FIXME(eddyb) there should be a nicer way to do this.
1131 hir::ItemKind::ForeignMod(ref fm) => record!(self.per_def.children[def_id] <-
1134 .map(|foreign_item| tcx.hir().local_def_id(
1135 foreign_item.hir_id).index)
1137 hir::ItemKind::Enum(..) => record!(self.per_def.children[def_id] <-
1138 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1139 assert!(v.def_id.is_local());
1143 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1144 record!(self.per_def.children[def_id] <-
1145 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1146 assert!(f.did.is_local());
1151 hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1152 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1153 record!(self.per_def.children[def_id] <-
1154 associated_item_def_ids.iter().map(|&def_id| {
1155 assert!(def_id.is_local());
1162 self.encode_stability(def_id);
1163 self.encode_const_stability(def_id);
1164 self.encode_deprecation(def_id);
1166 hir::ItemKind::Static(..)
1167 | hir::ItemKind::Const(..)
1168 | hir::ItemKind::Fn(..)
1169 | hir::ItemKind::TyAlias(..)
1170 | hir::ItemKind::OpaqueTy(..)
1171 | hir::ItemKind::Enum(..)
1172 | hir::ItemKind::Struct(..)
1173 | hir::ItemKind::Union(..)
1174 | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1177 if let hir::ItemKind::Fn(..) = item.kind {
1178 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
1180 if let hir::ItemKind::Impl { .. } = item.kind {
1181 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1182 record!(self.per_def.impl_trait_ref[def_id] <- trait_ref);
1185 self.encode_inherent_implementations(def_id);
1187 hir::ItemKind::Enum(..)
1188 | hir::ItemKind::Struct(..)
1189 | hir::ItemKind::Union(..)
1190 | hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1194 hir::ItemKind::Static(..)
1195 | hir::ItemKind::Const(..)
1196 | hir::ItemKind::Fn(..)
1197 | hir::ItemKind::TyAlias(..)
1198 | hir::ItemKind::Enum(..)
1199 | hir::ItemKind::Struct(..)
1200 | hir::ItemKind::Union(..)
1201 | hir::ItemKind::Impl { .. }
1202 | hir::ItemKind::OpaqueTy(..)
1203 | hir::ItemKind::Trait(..)
1204 | hir::ItemKind::TraitAlias(..) => {
1205 self.encode_generics(def_id);
1206 self.encode_explicit_predicates(def_id);
1207 self.encode_inferred_outlives(def_id);
1212 hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => {
1213 self.encode_super_predicates(def_id);
1218 let mir = match item.kind {
1219 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => true,
1220 hir::ItemKind::Fn(ref sig, ..) => {
1221 let generics = tcx.generics_of(def_id);
1222 let needs_inline = (generics.requires_monomorphization(tcx)
1223 || tcx.codegen_fn_attrs(def_id).requests_inline())
1224 && !self.metadata_output_only();
1225 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1226 needs_inline || sig.header.constness == hir::Constness::Const || always_encode_mir
1231 self.encode_optimized_mir(def_id);
1232 self.encode_promoted_mir(def_id);
1236 /// Serialize the text of exported macros
1237 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) {
1238 use rustc_ast_pretty::pprust;
1239 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id);
1240 record!(self.per_def.kind[def_id] <- EntryKind::MacroDef(self.lazy(MacroDef {
1241 body: pprust::tts_to_string(macro_def.body.clone()),
1242 legacy: macro_def.legacy,
1244 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1245 record!(self.per_def.span[def_id] <- macro_def.span);
1246 record!(self.per_def.attributes[def_id] <- macro_def.attrs);
1247 self.encode_stability(def_id);
1248 self.encode_deprecation(def_id);
1251 fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1252 record!(self.per_def.kind[def_id] <- kind);
1253 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1254 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
1256 self.encode_item_type(def_id);
1260 fn encode_info_for_closure(&mut self, def_id: DefId) {
1261 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1263 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1264 // including on the signature, which is inferred in `typeck_tables_of.
1265 let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1266 let ty = self.tcx.typeck_tables_of(def_id).node_type(hir_id);
1268 record!(self.per_def.kind[def_id] <- match ty.kind {
1269 ty::Generator(..) => {
1270 let data = self.tcx.generator_kind(def_id).unwrap();
1271 EntryKind::Generator(data)
1274 ty::Closure(..) => EntryKind::Closure,
1276 _ => bug!("closure that is neither generator nor closure"),
1278 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1279 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
1280 record!(self.per_def.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
1281 self.encode_item_type(def_id);
1282 if let ty::Closure(def_id, substs) = ty.kind {
1283 record!(self.per_def.fn_sig[def_id] <- substs.as_closure().sig(def_id, self.tcx));
1285 self.encode_generics(def_id);
1286 self.encode_optimized_mir(def_id);
1287 self.encode_promoted_mir(def_id);
1290 fn encode_info_for_anon_const(&mut self, def_id: DefId) {
1291 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1292 let id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
1293 let body_id = self.tcx.hir().body_owned_by(id);
1294 let const_data = self.encode_rendered_const_for_body(body_id);
1295 let qualifs = self.tcx.mir_const_qualif(def_id);
1297 record!(self.per_def.kind[def_id] <- EntryKind::Const(qualifs, const_data));
1298 record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
1299 record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
1300 self.encode_item_type(def_id);
1301 self.encode_generics(def_id);
1302 self.encode_explicit_predicates(def_id);
1303 self.encode_inferred_outlives(def_id);
1304 self.encode_optimized_mir(def_id);
1305 self.encode_promoted_mir(def_id);
1308 fn encode_native_libraries(&mut self) -> Lazy<[NativeLibrary]> {
1309 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1310 self.lazy(used_libraries.iter().cloned())
1313 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1314 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1315 self.lazy(foreign_modules.iter().cloned())
1318 fn encode_proc_macros(&mut self) -> Option<Lazy<[DefIndex]>> {
1319 let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
1322 Some(self.lazy(tcx.hir().krate().proc_macros.iter().map(|p| p.owner)))
1328 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1329 let crates = self.tcx.crates();
1331 let mut deps = crates
1334 let dep = CrateDep {
1335 name: self.tcx.original_crate_name(cnum),
1336 hash: self.tcx.crate_hash(cnum),
1337 host_hash: self.tcx.crate_host_hash(cnum),
1338 kind: self.tcx.dep_kind(cnum),
1339 extra_filename: self.tcx.extra_filename(cnum),
1343 .collect::<Vec<_>>();
1345 deps.sort_by_key(|&(cnum, _)| cnum);
1348 // Sanity-check the crate numbers
1349 let mut expected_cnum = 1;
1350 for &(n, _) in &deps {
1351 assert_eq!(n, CrateNum::new(expected_cnum));
1356 // We're just going to write a list of crate 'name-hash-version's, with
1357 // the assumption that they are numbered 1 to n.
1358 // FIXME (#2166): This is not nearly enough to support correct versioning
1359 // but is enough to get transitive crate dependencies working.
1360 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1363 fn encode_lib_features(&mut self) -> Lazy<[(ast::Name, Option<ast::Name>)]> {
1365 let lib_features = tcx.lib_features();
1366 self.lazy(lib_features.to_vec())
1369 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1371 let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1372 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1375 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1377 let lang_items = tcx.lang_items();
1378 let lang_items = lang_items.items().iter();
1379 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1380 if let Some(def_id) = opt_def_id {
1381 if def_id.is_local() {
1382 return Some((def_id.index, i));
1389 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1391 self.lazy(&tcx.lang_items().missing)
1394 /// Encodes an index, mapping each trait to its (local) implementations.
1395 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1396 debug!("EncodeContext::encode_impls()");
1398 let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() };
1399 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1401 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1403 // Bring everything into deterministic order for hashing
1404 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1406 let all_impls: Vec<_> = all_impls
1408 .map(|(trait_def_id, mut impls)| {
1409 // Bring everything into deterministic order for hashing
1410 impls.sort_by_cached_key(|&def_index| {
1411 tcx.hir().definitions().def_path_hash(def_index)
1415 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1416 impls: self.lazy(&impls),
1421 self.lazy(&all_impls)
1424 // Encodes all symbols exported from this crate into the metadata.
1426 // This pass is seeded off the reachability list calculated in the
1427 // middle::reachable module but filters out items that either don't have a
1428 // symbol associated with them (they weren't translated) or if they're an FFI
1429 // definition (as that's not defined in this crate).
1430 fn encode_exported_symbols(
1432 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1433 ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1434 // The metadata symbol name is special. It should not show up in
1435 // downstream crates.
1436 let metadata_symbol_name = SymbolName::new(&metadata_symbol_name(self.tcx));
1441 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1442 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1449 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1450 let formats = self.tcx.dependency_formats(LOCAL_CRATE);
1451 for (ty, arr) in formats.iter() {
1452 if *ty != config::CrateType::Dylib {
1455 return self.lazy(arr.iter().map(|slot| match *slot {
1456 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1458 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1459 Linkage::Static => Some(LinkagePreference::RequireStatic),
1465 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1468 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1470 record!(self.per_def.kind[def_id] <- match nitem.kind {
1471 hir::ForeignItemKind::Fn(_, ref names, _) => {
1473 asyncness: hir::IsAsync::NotAsync,
1474 constness: if self.tcx.is_const_fn_raw(def_id) {
1475 hir::Constness::Const
1477 hir::Constness::NotConst
1479 param_names: self.encode_fn_param_names(names),
1481 EntryKind::ForeignFn(self.lazy(data))
1483 hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => EntryKind::ForeignMutStatic,
1484 hir::ForeignItemKind::Static(_, hir::Mutability::Not) => EntryKind::ForeignImmStatic,
1485 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1487 record!(self.per_def.visibility[def_id] <-
1488 ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, self.tcx));
1489 record!(self.per_def.span[def_id] <- nitem.span);
1490 record!(self.per_def.attributes[def_id] <- nitem.attrs);
1491 self.encode_stability(def_id);
1492 self.encode_const_stability(def_id);
1493 self.encode_deprecation(def_id);
1494 self.encode_item_type(def_id);
1495 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1496 record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
1497 self.encode_variances_of(def_id);
1499 self.encode_generics(def_id);
1500 self.encode_explicit_predicates(def_id);
1501 self.encode_inferred_outlives(def_id);
1505 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1506 impl Visitor<'tcx> for EncodeContext<'tcx> {
1507 type Map = Map<'tcx>;
1509 fn nested_visit_map(&mut self) -> NestedVisitorMap<'_, Self::Map> {
1510 NestedVisitorMap::OnlyBodies(&self.tcx.hir())
1512 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1513 intravisit::walk_expr(self, ex);
1514 self.encode_info_for_expr(ex);
1516 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1517 intravisit::walk_anon_const(self, c);
1518 let def_id = self.tcx.hir().local_def_id(c.hir_id);
1519 self.encode_info_for_anon_const(def_id);
1521 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1522 intravisit::walk_item(self, item);
1523 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1525 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1526 _ => self.encode_info_for_item(def_id, item),
1528 self.encode_addl_info_for_item(item);
1530 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1531 intravisit::walk_foreign_item(self, ni);
1532 let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1533 self.encode_info_for_foreign_item(def_id, ni);
1535 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1536 intravisit::walk_generics(self, generics);
1537 self.encode_info_for_generics(generics);
1539 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) {
1540 self.encode_info_for_macro_def(macro_def);
1544 impl EncodeContext<'tcx> {
1545 fn encode_fields(&mut self, adt_def_id: DefId) {
1546 let def = self.tcx.adt_def(adt_def_id);
1547 for (variant_index, variant) in def.variants.iter_enumerated() {
1548 for (field_index, _field) in variant.fields.iter().enumerate() {
1549 // FIXME(eddyb) `adt_def_id` is leftover from incremental isolation,
1550 // pass `def`, `variant` or `field` instead.
1551 self.encode_field(adt_def_id, variant_index, field_index);
1556 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1557 for param in generics.params {
1558 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1560 GenericParamKind::Lifetime { .. } => continue,
1561 GenericParamKind::Type { ref default, .. } => {
1562 self.encode_info_for_generic_param(
1564 EntryKind::TypeParam,
1568 GenericParamKind::Const { .. } => {
1569 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true);
1575 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1577 hir::ExprKind::Closure(..) => {
1578 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1579 self.encode_info_for_closure(def_id);
1585 /// In some cases, along with the item itself, we also
1586 /// encode some sub-items. Usually we want some info from the item
1587 /// so it's easier to do that here then to wait until we would encounter
1588 /// normally in the visitor walk.
1589 fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1590 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1592 hir::ItemKind::Static(..)
1593 | hir::ItemKind::Const(..)
1594 | hir::ItemKind::Fn(..)
1595 | hir::ItemKind::Mod(..)
1596 | hir::ItemKind::ForeignMod(..)
1597 | hir::ItemKind::GlobalAsm(..)
1598 | hir::ItemKind::ExternCrate(..)
1599 | hir::ItemKind::Use(..)
1600 | hir::ItemKind::TyAlias(..)
1601 | hir::ItemKind::OpaqueTy(..)
1602 | hir::ItemKind::TraitAlias(..) => {
1603 // no sub-item recording needed in these cases
1605 hir::ItemKind::Enum(..) => {
1606 self.encode_fields(def_id);
1608 let def = self.tcx.adt_def(def_id);
1609 for (i, variant) in def.variants.iter_enumerated() {
1610 // FIXME(eddyb) `def_id` is leftover from incremental isolation,
1611 // pass `def` or `variant` instead.
1612 self.encode_enum_variant_info(def_id, i);
1614 // FIXME(eddyb) `def_id` is leftover from incremental isolation,
1615 // pass `def`, `variant` or `ctor_def_id` instead.
1616 if let Some(_ctor_def_id) = variant.ctor_def_id {
1617 self.encode_enum_variant_ctor(def_id, i);
1621 hir::ItemKind::Struct(ref struct_def, _) => {
1622 self.encode_fields(def_id);
1624 // If the struct has a constructor, encode it.
1625 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1626 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1627 self.encode_struct_ctor(def_id, ctor_def_id);
1630 hir::ItemKind::Union(..) => {
1631 self.encode_fields(def_id);
1633 hir::ItemKind::Impl { .. } => {
1634 for &trait_item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1635 self.encode_info_for_impl_item(trait_item_def_id);
1638 hir::ItemKind::Trait(..) => {
1639 for &item_def_id in self.tcx.associated_item_def_ids(def_id).iter() {
1640 self.encode_info_for_trait_item(item_def_id);
1647 struct ImplVisitor<'tcx> {
1649 impls: FxHashMap<DefId, Vec<DefIndex>>,
1652 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1653 fn visit_item(&mut self, item: &hir::Item<'_>) {
1654 if let hir::ItemKind::Impl { .. } = item.kind {
1655 let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1656 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
1657 self.impls.entry(trait_ref.def_id).or_default().push(impl_id.index);
1662 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
1664 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
1665 // handled in `visit_item` above
1669 // NOTE(eddyb) The following comment was preserved for posterity, even
1670 // though it's no longer relevant as EBML (which uses nested & tagged
1671 // "documents") was replaced with a scheme that can't go out of bounds.
1673 // And here we run into yet another obscure archive bug: in which metadata
1674 // loaded from archives may have trailing garbage bytes. Awhile back one of
1675 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1676 // and opt) by having ebml generate an out-of-bounds panic when looking at
1679 // Upon investigation it turned out that the metadata file inside of an rlib
1680 // (and ar archive) was being corrupted. Some compilations would generate a
1681 // metadata file which would end in a few extra bytes, while other
1682 // compilations would not have these extra bytes appended to the end. These
1683 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1684 // being interpreted causing the out-of-bounds.
1686 // The root cause of why these extra bytes were appearing was never
1687 // discovered, and in the meantime the solution we're employing is to insert
1688 // the length of the metadata to the start of the metadata. Later on this
1689 // will allow us to slice the metadata to the precise length that we just
1690 // generated regardless of trailing bytes that end up in it.
1692 pub(super) fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
1693 let mut encoder = opaque::Encoder::new(vec![]);
1694 encoder.emit_raw_bytes(METADATA_HEADER);
1696 // Will be filled with the root position after encoding everything.
1697 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1699 // Since encoding metadata is not in a query, and nothing is cached,
1700 // there's no need to do dep-graph tracking for any of it.
1701 let (root, mut result) = tcx.dep_graph.with_ignore(move || {
1702 let mut ecx = EncodeContext {
1705 per_def: Default::default(),
1706 lazy_state: LazyState::NoNode,
1707 type_shorthands: Default::default(),
1708 predicate_shorthands: Default::default(),
1709 source_file_cache: tcx.sess.source_map().files()[0].clone(),
1710 interpret_allocs: Default::default(),
1711 interpret_allocs_inverse: Default::default(),
1714 // Encode the rustc version string in a predictable location.
1715 rustc_version().encode(&mut ecx).unwrap();
1717 // Encode all the entries and extra information in the crate,
1718 // culminating in the `CrateRoot` which points to all of it.
1719 let root = ecx.encode_crate_root();
1720 (root, ecx.opaque.into_inner())
1723 // Encode the root position.
1724 let header = METADATA_HEADER.len();
1725 let pos = root.position.get();
1726 result[header + 0] = (pos >> 24) as u8;
1727 result[header + 1] = (pos >> 16) as u8;
1728 result[header + 2] = (pos >> 8) as u8;
1729 result[header + 3] = (pos >> 0) as u8;
1731 EncodedMetadata { raw_data: result }