1 use crate::rmeta::table::{FixedSizeEncoding, TableBuilder};
5 use rustc_data_structures::fingerprint::{Fingerprint, FingerprintEncoder};
6 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
7 use rustc_data_structures::stable_hasher::StableHasher;
8 use rustc_data_structures::sync::{join, Lrc};
10 use rustc_hir::def::CtorKind;
11 use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
12 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
13 use rustc_hir::itemlikevisit::{ItemLikeVisitor, ParItemLikeVisitor};
14 use rustc_hir::lang_items;
15 use rustc_hir::{AnonConst, GenericParamKind};
16 use rustc_index::bit_set::GrowableBitSet;
17 use rustc_index::vec::Idx;
18 use rustc_middle::hir::map::Map;
19 use rustc_middle::middle::cstore::{EncodedMetadata, ForeignModule, LinkagePreference, NativeLib};
20 use rustc_middle::middle::dependency_format::Linkage;
21 use rustc_middle::middle::exported_symbols::{
22 metadata_symbol_name, ExportedSymbol, SymbolExportLevel,
24 use rustc_middle::mir::interpret;
25 use rustc_middle::traits::specialization_graph;
26 use rustc_middle::ty::codec::TyEncoder;
27 use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
28 use rustc_serialize::{opaque, Encodable, Encoder};
29 use rustc_session::config::CrateType;
30 use rustc_span::hygiene::{ExpnDataEncodeMode, HygieneEncodeContext};
31 use rustc_span::source_map::Spanned;
32 use rustc_span::symbol::{sym, Ident, Symbol};
33 use rustc_span::{self, ExternalSource, FileName, SourceFile, Span, SyntaxContext};
34 use rustc_target::abi::VariantIdx;
36 use std::num::NonZeroUsize;
38 use tracing::{debug, trace};
40 pub(super) struct EncodeContext<'a, 'tcx> {
41 opaque: opaque::Encoder,
44 tables: TableBuilders<'tcx>,
46 lazy_state: LazyState,
47 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
48 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
50 interpret_allocs: FxIndexSet<interpret::AllocId>,
52 // This is used to speed up Span encoding.
53 // The `usize` is an index into the `MonotonicVec`
54 // that stores the `SourceFile`
55 source_file_cache: (Lrc<SourceFile>, usize),
56 // The indices (into the `SourceMap`'s `MonotonicVec`)
57 // of all of the `SourceFiles` that we need to serialize.
58 // When we serialize a `Span`, we insert the index of its
59 // `SourceFile` into the `GrowableBitSet`.
61 // This needs to be a `GrowableBitSet` and not a
62 // regular `BitSet` because we may actually import new `SourceFiles`
63 // during metadata encoding, due to executing a query
64 // with a result containing a foreign `Span`.
65 required_source_files: Option<GrowableBitSet<usize>>,
67 hygiene_ctxt: &'a HygieneEncodeContext,
70 macro_rules! encoder_methods {
71 ($($name:ident($ty:ty);)*) => {
72 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
73 self.opaque.$name(value)
78 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
79 type Error = <opaque::Encoder as Encoder>::Error;
82 fn emit_unit(&mut self) -> Result<(), Self::Error> {
109 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
112 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
113 e.emit_lazy_distance(*self)
117 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
120 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
121 e.emit_usize(self.meta)?;
125 e.emit_lazy_distance(*self)
129 impl<'a, 'tcx, I: Idx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
130 for Lazy<Table<I, T>>
132 Option<T>: FixedSizeEncoding,
134 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
135 e.emit_usize(self.meta)?;
136 e.emit_lazy_distance(*self)
140 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex {
141 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
142 s.emit_u32(self.as_u32())
146 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
147 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
148 rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s)
152 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
153 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
154 rustc_span::hygiene::raw_encode_expn_id(
157 ExpnDataEncodeMode::Metadata,
163 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
164 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
166 return TAG_INVALID_SPAN.encode(s);
169 let span = self.data();
171 // The Span infrastructure should make sure that this invariant holds:
172 debug_assert!(span.lo <= span.hi);
174 if !s.source_file_cache.0.contains(span.lo) {
175 let source_map = s.tcx.sess.source_map();
176 let source_file_index = source_map.lookup_source_file_idx(span.lo);
177 s.source_file_cache =
178 (source_map.files()[source_file_index].clone(), source_file_index);
181 if !s.source_file_cache.0.contains(span.hi) {
182 // Unfortunately, macro expansion still sometimes generates Spans
183 // that malformed in this way.
184 return TAG_INVALID_SPAN.encode(s);
187 let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!");
188 // Record the fact that we need to encode the data for this `SourceFile`
189 source_files.insert(s.source_file_cache.1);
191 // There are two possible cases here:
192 // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
193 // crate we are writing metadata for. When the metadata for *this* crate gets
194 // deserialized, the deserializer will need to know which crate it originally came
195 // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
196 // be deserialized after the rest of the span data, which tells the deserializer
197 // which crate contains the source map information.
198 // 2. This span comes from our own crate. No special hamdling is needed - we just
199 // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
200 // our own source map information.
202 // If we're a proc-macro crate, we always treat this as a local `Span`.
203 // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
204 // if we're a proc-macro crate.
205 // This allows us to avoid loading the dependencies of proc-macro crates: all of
206 // the information we need to decode `Span`s is stored in the proc-macro crate.
207 let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro {
208 // To simplify deserialization, we 'rebase' this span onto the crate it originally came from
209 // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values
210 // are relative to the source map information for the 'foreign' crate whose CrateNum
211 // we write into the metadata. This allows `imported_source_files` to binary
212 // search through the 'foreign' crate's source map information, using the
213 // deserialized 'lo' and 'hi' values directly.
215 // All of this logic ensures that the final result of deserialization is a 'normal'
216 // Span that can be used without any additional trouble.
217 let external_start_pos = {
218 // Introduce a new scope so that we drop the 'lock()' temporary
219 match &*s.source_file_cache.0.external_src.lock() {
220 ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos,
221 src => panic!("Unexpected external source {:?}", src),
224 let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos;
225 let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos;
227 (TAG_VALID_SPAN_FOREIGN, lo, hi)
229 (TAG_VALID_SPAN_LOCAL, span.lo, span.hi)
235 // Encode length which is usually less than span.hi and profits more
236 // from the variable-length integer encoding that we use.
240 // Don't serialize any `SyntaxContext`s from a proc-macro crate,
241 // since we don't load proc-macro dependencies during serialization.
242 // This means that any hygiene information from macros used *within*
243 // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
244 // definition) will be lost.
246 // This can show up in two ways:
248 // 1. Any hygiene information associated with identifier of
249 // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
250 // Since proc-macros can only be invoked from a different crate,
251 // real code should never need to care about this.
253 // 2. Using `Span::def_site` or `Span::mixed_site` will not
254 // include any hygiene information associated with the definition
255 // site. This means that a proc-macro cannot emit a `$crate`
256 // identifier which resolves to one of its dependencies,
257 // which also should never come up in practice.
259 // Additionally, this affects `Span::parent`, and any other
260 // span inspection APIs that would otherwise allow traversing
261 // the `SyntaxContexts` associated with a span.
263 // None of these user-visible effects should result in any
264 // cross-crate inconsistencies (getting one behavior in the same
265 // crate, and a different behavior in another crate) due to the
266 // limited surface that proc-macros can expose.
268 // IMPORTANT: If this is ever changed, be sure to update
269 // `rustc_span::hygiene::raw_encode_expn_id` to handle
270 // encoding `ExpnData` for proc-macro crates.
272 SyntaxContext::root().encode(s)?;
274 span.ctxt.encode(s)?;
277 if tag == TAG_VALID_SPAN_FOREIGN {
278 // This needs to be two lines to avoid holding the `s.source_file_cache`
279 // while calling `cnum.encode(s)`
280 let cnum = s.source_file_cache.0.cnum;
288 impl<'a, 'tcx> FingerprintEncoder for EncodeContext<'a, 'tcx> {
289 fn encode_fingerprint(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
290 f.encode_opaque(&mut self.opaque)
294 impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
295 const CLEAR_CROSS_CRATE: bool = true;
297 fn position(&self) -> usize {
298 self.opaque.position()
301 fn tcx(&self) -> TyCtxt<'tcx> {
305 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
306 &mut self.type_shorthands
309 fn predicate_shorthands(&mut self) -> &mut FxHashMap<rustc_middle::ty::Predicate<'tcx>, usize> {
310 &mut self.predicate_shorthands
315 alloc_id: &rustc_middle::mir::interpret::AllocId,
316 ) -> Result<(), Self::Error> {
317 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
323 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
324 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
329 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
330 trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> {
331 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta;
334 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for &T {
335 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
336 self.encode(ecx).unwrap()
340 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for T {
341 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
342 self.encode(ecx).unwrap()
346 impl<'a, 'tcx, I, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, [T]> for I
349 I::Item: EncodeContentsForLazy<'a, 'tcx, T>,
351 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize {
352 self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
356 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would
357 // normally need extra variables to avoid errors about multiple mutable borrows.
358 macro_rules! record {
359 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
362 let lazy = $self.lazy(value);
363 $self.$tables.$table.set($def_id.index, lazy);
368 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
369 fn emit_lazy_distance<T: ?Sized + LazyMeta>(
372 ) -> Result<(), <Self as Encoder>::Error> {
373 let min_end = lazy.position.get() + T::min_size(lazy.meta);
374 let distance = match self.lazy_state {
375 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
376 LazyState::NodeStart(start) => {
377 let start = start.get();
378 assert!(min_end <= start);
381 LazyState::Previous(last_min_end) => {
383 last_min_end <= lazy.position,
384 "make sure that the calls to `lazy*` \
385 are in the same order as the metadata fields",
387 lazy.position.get() - last_min_end.get()
390 self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap());
391 self.emit_usize(distance)
394 fn lazy<T: ?Sized + LazyMeta>(
396 value: impl EncodeContentsForLazy<'a, 'tcx, T>,
398 let pos = NonZeroUsize::new(self.position()).unwrap();
400 assert_eq!(self.lazy_state, LazyState::NoNode);
401 self.lazy_state = LazyState::NodeStart(pos);
402 let meta = value.encode_contents_for_lazy(self);
403 self.lazy_state = LazyState::NoNode;
405 assert!(pos.get() + <T>::min_size(meta) <= self.position());
407 Lazy::from_position_and_meta(pos, meta)
410 fn encode_info_for_items(&mut self) {
411 let krate = self.tcx.hir().krate();
412 let vis = Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public };
413 self.encode_info_for_mod(hir::CRATE_HIR_ID, &krate.item.module, &krate.item.attrs, &vis);
414 krate.visit_all_item_likes(&mut self.as_deep_visitor());
415 for macro_def in krate.exported_macros {
416 self.visit_macro_def(macro_def);
420 fn encode_def_path_table(&mut self) {
421 let table = self.tcx.hir().definitions().def_path_table();
422 for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
423 let def_key = self.lazy(def_key);
424 let def_path_hash = self.lazy(def_path_hash);
425 self.tables.def_keys.set(def_index, def_key);
426 self.tables.def_path_hashes.set(def_index, def_path_hash);
430 fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> {
431 let source_map = self.tcx.sess.source_map();
432 let all_source_files = source_map.files();
434 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
435 // By replacing the `Option` with `None`, we ensure that we can't
436 // accidentally serialize any more `Span`s after the source map encoding
438 let required_source_files = self.required_source_files.take().unwrap();
440 let adapted = all_source_files
443 .filter(|(idx, source_file)| {
444 // Only serialize `SourceFile`s that were used
445 // during the encoding of a `Span`
446 required_source_files.contains(*idx) &&
447 // Don't serialize imported `SourceFile`s, unless
448 // we're in a proc-macro crate.
449 (!source_file.is_imported() || self.is_proc_macro)
451 .map(|(_, source_file)| {
452 let mut adapted = match source_file.name {
453 // This path of this SourceFile has been modified by
454 // path-remapping, so we use it verbatim (and avoid
455 // cloning the whole map in the process).
456 _ if source_file.name_was_remapped => source_file.clone(),
458 // Otherwise expand all paths to absolute paths because
459 // any relative paths are potentially relative to a
461 FileName::Real(ref name) => {
462 let name = name.stable_name();
463 let mut adapted = (**source_file).clone();
464 adapted.name = Path::new(&working_dir).join(name).into();
465 adapted.name_hash = {
466 let mut hasher: StableHasher = StableHasher::new();
467 adapted.name.hash(&mut hasher);
468 hasher.finish::<u128>()
473 // expanded code, not from a file
474 _ => source_file.clone(),
477 // We're serializing this `SourceFile` into our crate metadata,
478 // so mark it as coming from this crate.
479 // This also ensures that we don't try to deserialize the
480 // `CrateNum` for a proc-macro dependency - since proc macro
481 // dependencies aren't loaded when we deserialize a proc-macro,
482 // trying to remap the `CrateNum` would fail.
483 if self.is_proc_macro {
484 Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE;
488 .collect::<Vec<_>>();
490 self.lazy(adapted.iter().map(|rc| &**rc))
493 fn is_proc_macro(&self) -> bool {
494 self.tcx.sess.crate_types().contains(&CrateType::ProcMacro)
497 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
498 let is_proc_macro = self.is_proc_macro();
500 let mut i = self.position();
502 // Encode the crate deps
503 let crate_deps = self.encode_crate_deps();
504 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
505 let dep_bytes = self.position() - i;
507 // Encode the lib features.
509 let lib_features = self.encode_lib_features();
510 let lib_feature_bytes = self.position() - i;
512 // Encode the language items.
514 let lang_items = self.encode_lang_items();
515 let lang_items_missing = self.encode_lang_items_missing();
516 let lang_item_bytes = self.position() - i;
518 // Encode the diagnostic items.
520 let diagnostic_items = self.encode_diagnostic_items();
521 let diagnostic_item_bytes = self.position() - i;
523 // Encode the native libraries used
525 let native_libraries = self.encode_native_libraries();
526 let native_lib_bytes = self.position() - i;
528 let foreign_modules = self.encode_foreign_modules();
530 // Encode DefPathTable
532 self.encode_def_path_table();
533 let def_path_table_bytes = self.position() - i;
535 // Encode the def IDs of impls, for coherence checking.
537 let impls = self.encode_impls();
538 let impl_bytes = self.position() - i;
544 self.encode_info_for_items();
545 let item_bytes = self.position() - i;
547 // Encode the allocation index
548 let interpret_alloc_index = {
549 let mut interpret_alloc_index = Vec::new();
551 trace!("beginning to encode alloc ids");
553 let new_n = self.interpret_allocs.len();
554 // if we have found new ids, serialize those, too
559 trace!("encoding {} further alloc ids", new_n - n);
560 for idx in n..new_n {
561 let id = self.interpret_allocs[idx];
562 let pos = self.position() as u32;
563 interpret_alloc_index.push(pos);
564 interpret::specialized_encode_alloc_id(self, tcx, id).unwrap();
568 self.lazy(interpret_alloc_index)
572 let tables = self.tables.encode(&mut self.opaque);
573 let tables_bytes = self.position() - i;
575 // Encode the proc macro data
577 let proc_macro_data = self.encode_proc_macros();
578 let proc_macro_data_bytes = self.position() - i;
580 // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
581 // this as late as possible to give the prefetching as much time as possible to complete.
583 let exported_symbols = tcx.exported_symbols(LOCAL_CRATE);
584 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
585 let exported_symbols_bytes = self.position() - i;
587 // Encode the hygiene data,
588 // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process
589 // of encoding other items (e.g. `optimized_mir`) may cause us to load
590 // data from the incremental cache. If this causes us to deserialize a `Span`,
591 // then we may load additional `SyntaxContext`s into the global `HygieneData`.
592 // Therefore, we need to encode the hygiene data last to ensure that we encode
593 // any `SyntaxContext`s that might be used.
595 let (syntax_contexts, expn_data) = self.encode_hygiene();
596 let hygiene_bytes = self.position() - i;
598 // Encode source_map. This needs to be done last,
599 // since encoding `Span`s tells us which `SourceFiles` we actually
602 let source_map = self.encode_source_map();
603 let source_map_bytes = self.position() - i;
605 let attrs = tcx.hir().krate_attrs();
606 let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator);
608 let root = self.lazy(CrateRoot {
609 name: tcx.crate_name(LOCAL_CRATE),
610 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
611 triple: tcx.sess.opts.target_triple.clone(),
612 hash: tcx.crate_hash(LOCAL_CRATE),
613 disambiguator: tcx.sess.local_crate_disambiguator(),
614 panic_strategy: tcx.sess.panic_strategy(),
615 edition: tcx.sess.edition(),
616 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
617 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
618 has_default_lib_allocator,
619 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
620 proc_macro_decls_static: if is_proc_macro {
621 let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap();
627 proc_macro_stability: if is_proc_macro {
628 tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied()
632 compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
633 needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
634 needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
635 no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
636 panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
637 profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
638 symbol_mangling_version: tcx.sess.opts.debugging_opts.symbol_mangling_version,
641 dylib_dependency_formats,
651 interpret_alloc_index,
657 let total_bytes = self.position();
659 if tcx.sess.meta_stats() {
660 let mut zero_bytes = 0;
661 for e in self.opaque.data.iter() {
667 println!("metadata stats:");
668 println!(" dep bytes: {}", dep_bytes);
669 println!(" lib feature bytes: {}", lib_feature_bytes);
670 println!(" lang item bytes: {}", lang_item_bytes);
671 println!(" diagnostic item bytes: {}", diagnostic_item_bytes);
672 println!(" native bytes: {}", native_lib_bytes);
673 println!(" source_map bytes: {}", source_map_bytes);
674 println!(" impl bytes: {}", impl_bytes);
675 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
676 println!(" def-path table bytes: {}", def_path_table_bytes);
677 println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
678 println!(" item bytes: {}", item_bytes);
679 println!(" table bytes: {}", tables_bytes);
680 println!(" hygiene bytes: {}", hygiene_bytes);
681 println!(" zero bytes: {}", zero_bytes);
682 println!(" total bytes: {}", total_bytes);
689 impl EncodeContext<'a, 'tcx> {
690 fn encode_variances_of(&mut self, def_id: DefId) {
691 debug!("EncodeContext::encode_variances_of({:?})", def_id);
692 record!(self.tables.variances[def_id] <- &self.tcx.variances_of(def_id)[..]);
695 fn encode_item_type(&mut self, def_id: DefId) {
696 debug!("EncodeContext::encode_item_type({:?})", def_id);
697 record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id));
700 fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) {
702 let variant = &def.variants[index];
703 let def_id = variant.def_id;
704 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
706 let data = VariantData {
707 ctor_kind: variant.ctor_kind,
708 discr: variant.discr,
709 ctor: variant.ctor_def_id.map(|did| did.index),
710 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
713 let enum_id = tcx.hir().local_def_id_to_hir_id(def.did.expect_local());
714 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
716 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
717 record!(self.tables.visibility[def_id] <-
718 ty::Visibility::from_hir(enum_vis, enum_id, self.tcx));
719 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
720 record!(self.tables.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
721 record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
722 assert!(f.did.is_local());
725 self.encode_ident_span(def_id, variant.ident);
726 self.encode_stability(def_id);
727 self.encode_deprecation(def_id);
728 self.encode_item_type(def_id);
729 if variant.ctor_kind == CtorKind::Fn {
730 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
731 if let Some(ctor_def_id) = variant.ctor_def_id {
732 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
734 // FIXME(eddyb) is this ever used?
735 self.encode_variances_of(def_id);
737 self.encode_generics(def_id);
738 self.encode_explicit_predicates(def_id);
739 self.encode_inferred_outlives(def_id);
740 self.encode_optimized_mir(def_id.expect_local());
741 self.encode_promoted_mir(def_id.expect_local());
744 fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) {
746 let variant = &def.variants[index];
747 let def_id = variant.ctor_def_id.unwrap();
748 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
750 // FIXME(eddyb) encode only the `CtorKind` for constructors.
751 let data = VariantData {
752 ctor_kind: variant.ctor_kind,
753 discr: variant.discr,
754 ctor: Some(def_id.index),
755 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
758 // Variant constructors have the same visibility as the parent enums, unless marked as
759 // non-exhaustive, in which case they are lowered to `pub(crate)`.
760 let enum_id = tcx.hir().local_def_id_to_hir_id(def.did.expect_local());
761 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
762 let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx);
763 if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public {
764 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
767 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
768 record!(self.tables.visibility[def_id] <- ctor_vis);
769 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
770 self.encode_stability(def_id);
771 self.encode_deprecation(def_id);
772 self.encode_item_type(def_id);
773 if variant.ctor_kind == CtorKind::Fn {
774 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
775 self.encode_variances_of(def_id);
777 self.encode_generics(def_id);
778 self.encode_explicit_predicates(def_id);
779 self.encode_inferred_outlives(def_id);
780 self.encode_optimized_mir(def_id.expect_local());
781 self.encode_promoted_mir(def_id.expect_local());
784 fn encode_info_for_mod(
788 attrs: &[ast::Attribute],
789 vis: &hir::Visibility<'_>,
792 let local_def_id = tcx.hir().local_def_id(id);
793 let def_id = local_def_id.to_def_id();
794 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
797 reexports: match tcx.module_exports(local_def_id) {
799 let hir = self.tcx.hir();
803 .map(|export| export.map_id(|id| hir.local_def_id_to_hir_id(id))),
808 expansion: tcx.hir().definitions().expansion_that_defined(local_def_id),
811 record!(self.tables.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
812 record!(self.tables.visibility[def_id] <- ty::Visibility::from_hir(vis, id, self.tcx));
813 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
814 record!(self.tables.attributes[def_id] <- attrs);
815 record!(self.tables.children[def_id] <- md.item_ids.iter().map(|item_id| {
816 tcx.hir().local_def_id(item_id.id).local_def_index
818 self.encode_stability(def_id);
819 self.encode_deprecation(def_id);
824 adt_def: &ty::AdtDef,
825 variant_index: VariantIdx,
829 let variant = &adt_def.variants[variant_index];
830 let field = &variant.fields[field_index];
832 let def_id = field.did;
833 debug!("EncodeContext::encode_field({:?})", def_id);
835 let variant_id = tcx.hir().local_def_id_to_hir_id(variant.def_id.expect_local());
836 let variant_data = tcx.hir().expect_variant_data(variant_id);
838 record!(self.tables.kind[def_id] <- EntryKind::Field);
839 record!(self.tables.visibility[def_id] <- field.vis);
840 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
841 record!(self.tables.attributes[def_id] <- variant_data.fields()[field_index].attrs);
842 self.encode_ident_span(def_id, field.ident);
843 self.encode_stability(def_id);
844 self.encode_deprecation(def_id);
845 self.encode_item_type(def_id);
846 self.encode_generics(def_id);
847 self.encode_explicit_predicates(def_id);
848 self.encode_inferred_outlives(def_id);
851 fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) {
852 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
854 let variant = adt_def.non_enum_variant();
856 let data = VariantData {
857 ctor_kind: variant.ctor_kind,
858 discr: variant.discr,
859 ctor: Some(def_id.index),
860 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
863 let struct_id = tcx.hir().local_def_id_to_hir_id(adt_def.did.expect_local());
864 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
865 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
866 for field in &variant.fields {
867 if ctor_vis.is_at_least(field.vis, tcx) {
868 ctor_vis = field.vis;
872 // If the structure is marked as non_exhaustive then lower the visibility
873 // to within the crate.
874 if adt_def.non_enum_variant().is_field_list_non_exhaustive()
875 && ctor_vis == ty::Visibility::Public
877 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
880 record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
881 record!(self.tables.visibility[def_id] <- ctor_vis);
882 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
883 self.encode_stability(def_id);
884 self.encode_deprecation(def_id);
885 self.encode_item_type(def_id);
886 if variant.ctor_kind == CtorKind::Fn {
887 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
888 self.encode_variances_of(def_id);
890 self.encode_generics(def_id);
891 self.encode_explicit_predicates(def_id);
892 self.encode_inferred_outlives(def_id);
893 self.encode_optimized_mir(def_id.expect_local());
894 self.encode_promoted_mir(def_id.expect_local());
897 fn encode_generics(&mut self, def_id: DefId) {
898 debug!("EncodeContext::encode_generics({:?})", def_id);
899 record!(self.tables.generics[def_id] <- self.tcx.generics_of(def_id));
902 fn encode_explicit_predicates(&mut self, def_id: DefId) {
903 debug!("EncodeContext::encode_explicit_predicates({:?})", def_id);
904 record!(self.tables.explicit_predicates[def_id] <-
905 self.tcx.explicit_predicates_of(def_id));
908 fn encode_inferred_outlives(&mut self, def_id: DefId) {
909 debug!("EncodeContext::encode_inferred_outlives({:?})", def_id);
910 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
911 if !inferred_outlives.is_empty() {
912 record!(self.tables.inferred_outlives[def_id] <- inferred_outlives);
916 fn encode_super_predicates(&mut self, def_id: DefId) {
917 debug!("EncodeContext::encode_super_predicates({:?})", def_id);
918 record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
921 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
922 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
925 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
926 let ast_item = tcx.hir().expect_trait_item(hir_id);
927 let trait_item = tcx.associated_item(def_id);
929 let container = match trait_item.defaultness {
930 hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
931 hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
932 hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
935 record!(self.tables.kind[def_id] <- match trait_item.kind {
936 ty::AssocKind::Const => {
937 let rendered = rustc_hir_pretty::to_string(
938 &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
939 |s| s.print_trait_item(ast_item)
941 let rendered_const = self.lazy(RenderedConst(rendered));
943 EntryKind::AssocConst(
949 ty::AssocKind::Fn => {
950 let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind {
951 let param_names = match *m {
952 hir::TraitFn::Required(ref names) => {
953 self.encode_fn_param_names(names)
955 hir::TraitFn::Provided(body) => {
956 self.encode_fn_param_names_for_body(body)
960 asyncness: m_sig.header.asyncness,
961 constness: hir::Constness::NotConst,
967 EntryKind::AssocFn(self.lazy(AssocFnData {
970 has_self: trait_item.fn_has_self_parameter,
973 ty::AssocKind::Type => EntryKind::AssocType(container),
975 record!(self.tables.visibility[def_id] <- trait_item.vis);
976 record!(self.tables.span[def_id] <- ast_item.span);
977 record!(self.tables.attributes[def_id] <- ast_item.attrs);
978 self.encode_ident_span(def_id, ast_item.ident);
979 self.encode_stability(def_id);
980 self.encode_const_stability(def_id);
981 self.encode_deprecation(def_id);
982 match trait_item.kind {
983 ty::AssocKind::Const | ty::AssocKind::Fn => {
984 self.encode_item_type(def_id);
986 ty::AssocKind::Type => {
987 if trait_item.defaultness.has_value() {
988 self.encode_item_type(def_id);
992 if trait_item.kind == ty::AssocKind::Fn {
993 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
994 self.encode_variances_of(def_id);
996 self.encode_generics(def_id);
997 self.encode_explicit_predicates(def_id);
998 self.encode_inferred_outlives(def_id);
1000 // This should be kept in sync with `PrefetchVisitor.visit_trait_item`.
1001 self.encode_optimized_mir(def_id.expect_local());
1002 self.encode_promoted_mir(def_id.expect_local());
1005 fn metadata_output_only(&self) -> bool {
1006 // MIR optimisation can be skipped when we're just interested in the metadata.
1007 !self.tcx.sess.opts.output_types.should_codegen()
1010 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1011 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1014 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1015 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
1016 let impl_item = self.tcx.associated_item(def_id);
1018 let container = match impl_item.defaultness {
1019 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
1020 hir::Defaultness::Final => AssocContainer::ImplFinal,
1021 hir::Defaultness::Default { has_value: false } => {
1022 span_bug!(ast_item.span, "impl items always have values (currently)")
1026 record!(self.tables.kind[def_id] <- match impl_item.kind {
1027 ty::AssocKind::Const => {
1028 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1029 let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1031 EntryKind::AssocConst(
1034 self.encode_rendered_const_for_body(body_id))
1039 ty::AssocKind::Fn => {
1040 let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind {
1042 asyncness: sig.header.asyncness,
1043 constness: sig.header.constness,
1044 param_names: self.encode_fn_param_names_for_body(body),
1049 EntryKind::AssocFn(self.lazy(AssocFnData {
1052 has_self: impl_item.fn_has_self_parameter,
1055 ty::AssocKind::Type => EntryKind::AssocType(container)
1057 record!(self.tables.visibility[def_id] <- impl_item.vis);
1058 record!(self.tables.span[def_id] <- ast_item.span);
1059 record!(self.tables.attributes[def_id] <- ast_item.attrs);
1060 self.encode_ident_span(def_id, impl_item.ident);
1061 self.encode_stability(def_id);
1062 self.encode_const_stability(def_id);
1063 self.encode_deprecation(def_id);
1064 self.encode_item_type(def_id);
1065 if impl_item.kind == ty::AssocKind::Fn {
1066 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1067 self.encode_variances_of(def_id);
1069 self.encode_generics(def_id);
1070 self.encode_explicit_predicates(def_id);
1071 self.encode_inferred_outlives(def_id);
1073 // The following part should be kept in sync with `PrefetchVisitor.visit_impl_item`.
1075 let mir = match ast_item.kind {
1076 hir::ImplItemKind::Const(..) => true,
1077 hir::ImplItemKind::Fn(ref sig, _) => {
1078 let generics = self.tcx.generics_of(def_id);
1079 let needs_inline = (generics.requires_monomorphization(self.tcx)
1080 || tcx.codegen_fn_attrs(def_id).requests_inline())
1081 && !self.metadata_output_only();
1082 let is_const_fn = sig.header.constness == hir::Constness::Const;
1083 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1084 needs_inline || is_const_fn || always_encode_mir
1086 hir::ImplItemKind::TyAlias(..) => false,
1089 self.encode_optimized_mir(def_id.expect_local());
1090 self.encode_promoted_mir(def_id.expect_local());
1094 fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> {
1095 self.lazy(self.tcx.hir().body_param_names(body_id))
1098 fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> {
1099 self.lazy(param_names.iter())
1102 fn encode_optimized_mir(&mut self, def_id: LocalDefId) {
1103 debug!("EntryBuilder::encode_mir({:?})", def_id);
1104 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1105 record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1107 let unused = self.tcx.unused_generic_params(def_id);
1108 if !unused.is_empty() {
1109 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1114 fn encode_promoted_mir(&mut self, def_id: LocalDefId) {
1115 debug!("EncodeContext::encode_promoted_mir({:?})", def_id);
1116 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1117 record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1121 // Encodes the inherent implementations of a structure, enumeration, or trait.
1122 fn encode_inherent_implementations(&mut self, def_id: DefId) {
1123 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1124 let implementations = self.tcx.inherent_impls(def_id);
1125 if !implementations.is_empty() {
1126 record!(self.tables.inherent_impls[def_id] <- implementations.iter().map(|&def_id| {
1127 assert!(def_id.is_local());
1133 fn encode_stability(&mut self, def_id: DefId) {
1134 debug!("EncodeContext::encode_stability({:?})", def_id);
1135 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1136 record!(self.tables.stability[def_id] <- stab)
1140 fn encode_const_stability(&mut self, def_id: DefId) {
1141 debug!("EncodeContext::encode_const_stability({:?})", def_id);
1142 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1143 record!(self.tables.const_stability[def_id] <- stab)
1147 fn encode_deprecation(&mut self, def_id: DefId) {
1148 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1149 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1150 record!(self.tables.deprecation[def_id] <- depr);
1154 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1155 let hir = self.tcx.hir();
1156 let body = hir.body(body_id);
1157 let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1158 s.print_expr(&body.value)
1160 let rendered_const = &RenderedConst(rendered);
1161 self.lazy(rendered_const)
1164 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1167 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1169 self.encode_ident_span(def_id, item.ident);
1171 record!(self.tables.kind[def_id] <- match item.kind {
1172 hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic,
1173 hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic,
1174 hir::ItemKind::Const(_, body_id) => {
1175 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1178 self.encode_rendered_const_for_body(body_id)
1181 hir::ItemKind::Fn(ref sig, .., body) => {
1183 asyncness: sig.header.asyncness,
1184 constness: sig.header.constness,
1185 param_names: self.encode_fn_param_names_for_body(body),
1188 EntryKind::Fn(self.lazy(data))
1190 hir::ItemKind::Mod(ref m) => {
1191 return self.encode_info_for_mod(item.hir_id, m, &item.attrs, &item.vis);
1193 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1194 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1195 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1196 hir::ItemKind::OpaqueTy(..) => EntryKind::OpaqueTy,
1197 hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1198 hir::ItemKind::Struct(ref struct_def, _) => {
1199 let adt_def = self.tcx.adt_def(def_id);
1200 let variant = adt_def.non_enum_variant();
1202 // Encode def_ids for each field and method
1203 // for methods, write all the stuff get_trait_method
1205 let ctor = struct_def.ctor_hir_id().map(|ctor_hir_id| {
1206 self.tcx.hir().local_def_id(ctor_hir_id).local_def_index
1209 EntryKind::Struct(self.lazy(VariantData {
1210 ctor_kind: variant.ctor_kind,
1211 discr: variant.discr,
1213 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1216 hir::ItemKind::Union(..) => {
1217 let adt_def = self.tcx.adt_def(def_id);
1218 let variant = adt_def.non_enum_variant();
1220 EntryKind::Union(self.lazy(VariantData {
1221 ctor_kind: variant.ctor_kind,
1222 discr: variant.discr,
1224 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1227 hir::ItemKind::Impl { defaultness, .. } => {
1228 let trait_ref = self.tcx.impl_trait_ref(def_id);
1229 let polarity = self.tcx.impl_polarity(def_id);
1230 let parent = if let Some(trait_ref) = trait_ref {
1231 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1232 trait_def.ancestors(self.tcx, def_id).ok()
1233 .and_then(|mut an| an.nth(1).and_then(|node| {
1235 specialization_graph::Node::Impl(parent) => Some(parent),
1243 // if this is an impl of `CoerceUnsized`, create its
1244 // "unsized info", else just store None
1245 let coerce_unsized_info =
1246 trait_ref.and_then(|t| {
1247 if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1248 Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1254 let data = ImplData {
1257 parent_impl: parent,
1258 coerce_unsized_info,
1261 EntryKind::Impl(self.lazy(data))
1263 hir::ItemKind::Trait(..) => {
1264 let trait_def = self.tcx.trait_def(def_id);
1265 let data = TraitData {
1266 unsafety: trait_def.unsafety,
1267 paren_sugar: trait_def.paren_sugar,
1268 has_auto_impl: self.tcx.trait_is_auto(def_id),
1269 is_marker: trait_def.is_marker,
1270 specialization_kind: trait_def.specialization_kind,
1273 EntryKind::Trait(self.lazy(data))
1275 hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1276 hir::ItemKind::ExternCrate(_) |
1277 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1279 record!(self.tables.visibility[def_id] <-
1280 ty::Visibility::from_hir(&item.vis, item.hir_id, tcx));
1281 record!(self.tables.span[def_id] <- item.span);
1282 record!(self.tables.attributes[def_id] <- item.attrs);
1283 // FIXME(eddyb) there should be a nicer way to do this.
1285 hir::ItemKind::ForeignMod(ref fm) => record!(self.tables.children[def_id] <-
1288 .map(|foreign_item| tcx.hir().local_def_id(
1289 foreign_item.hir_id).local_def_index)
1291 hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <-
1292 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1293 assert!(v.def_id.is_local());
1297 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1298 record!(self.tables.children[def_id] <-
1299 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1300 assert!(f.did.is_local());
1305 hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1306 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1307 record!(self.tables.children[def_id] <-
1308 associated_item_def_ids.iter().map(|&def_id| {
1309 assert!(def_id.is_local());
1316 self.encode_stability(def_id);
1317 self.encode_const_stability(def_id);
1318 self.encode_deprecation(def_id);
1320 hir::ItemKind::Static(..)
1321 | hir::ItemKind::Const(..)
1322 | hir::ItemKind::Fn(..)
1323 | hir::ItemKind::TyAlias(..)
1324 | hir::ItemKind::OpaqueTy(..)
1325 | hir::ItemKind::Enum(..)
1326 | hir::ItemKind::Struct(..)
1327 | hir::ItemKind::Union(..)
1328 | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1331 if let hir::ItemKind::Fn(..) = item.kind {
1332 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1334 if let hir::ItemKind::Impl { .. } = item.kind {
1335 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1336 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1339 self.encode_inherent_implementations(def_id);
1341 hir::ItemKind::Enum(..)
1342 | hir::ItemKind::Struct(..)
1343 | hir::ItemKind::Union(..)
1344 | hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1348 hir::ItemKind::Static(..)
1349 | hir::ItemKind::Const(..)
1350 | hir::ItemKind::Fn(..)
1351 | hir::ItemKind::TyAlias(..)
1352 | hir::ItemKind::Enum(..)
1353 | hir::ItemKind::Struct(..)
1354 | hir::ItemKind::Union(..)
1355 | hir::ItemKind::Impl { .. }
1356 | hir::ItemKind::OpaqueTy(..)
1357 | hir::ItemKind::Trait(..)
1358 | hir::ItemKind::TraitAlias(..) => {
1359 self.encode_generics(def_id);
1360 self.encode_explicit_predicates(def_id);
1361 self.encode_inferred_outlives(def_id);
1366 hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => {
1367 self.encode_super_predicates(def_id);
1372 // The following part should be kept in sync with `PrefetchVisitor.visit_item`.
1374 let mir = match item.kind {
1375 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => true,
1376 hir::ItemKind::Fn(ref sig, ..) => {
1377 let generics = tcx.generics_of(def_id);
1378 let needs_inline = (generics.requires_monomorphization(tcx)
1379 || tcx.codegen_fn_attrs(def_id).requests_inline())
1380 && !self.metadata_output_only();
1381 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1382 needs_inline || sig.header.constness == hir::Constness::Const || always_encode_mir
1387 self.encode_optimized_mir(def_id.expect_local());
1388 self.encode_promoted_mir(def_id.expect_local());
1392 /// Serialize the text of exported macros
1393 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) {
1394 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id).to_def_id();
1395 record!(self.tables.kind[def_id] <- EntryKind::MacroDef(self.lazy(macro_def.ast.clone())));
1396 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1397 record!(self.tables.span[def_id] <- macro_def.span);
1398 record!(self.tables.attributes[def_id] <- macro_def.attrs);
1399 self.encode_ident_span(def_id, macro_def.ident);
1400 self.encode_stability(def_id);
1401 self.encode_deprecation(def_id);
1404 fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1405 record!(self.tables.kind[def_id] <- kind);
1406 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1407 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
1409 self.encode_item_type(def_id);
1413 fn encode_info_for_closure(&mut self, def_id: LocalDefId) {
1414 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1416 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1417 // including on the signature, which is inferred in `typeck.
1418 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1419 let ty = self.tcx.typeck(def_id).node_type(hir_id);
1421 record!(self.tables.kind[def_id.to_def_id()] <- match ty.kind {
1422 ty::Generator(..) => {
1423 let data = self.tcx.generator_kind(def_id).unwrap();
1424 EntryKind::Generator(data)
1427 ty::Closure(..) => EntryKind::Closure,
1429 _ => bug!("closure that is neither generator nor closure"),
1431 record!(self.tables.visibility[def_id.to_def_id()] <- ty::Visibility::Public);
1432 record!(self.tables.span[def_id.to_def_id()] <- self.tcx.def_span(def_id));
1433 record!(self.tables.attributes[def_id.to_def_id()] <- &self.tcx.get_attrs(def_id.to_def_id())[..]);
1434 self.encode_item_type(def_id.to_def_id());
1435 if let ty::Closure(def_id, substs) = ty.kind {
1436 record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1438 self.encode_generics(def_id.to_def_id());
1439 self.encode_optimized_mir(def_id);
1440 self.encode_promoted_mir(def_id);
1443 fn encode_info_for_anon_const(&mut self, def_id: LocalDefId) {
1444 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1445 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1446 let body_id = self.tcx.hir().body_owned_by(id);
1447 let const_data = self.encode_rendered_const_for_body(body_id);
1448 let qualifs = self.tcx.mir_const_qualif(def_id);
1450 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data));
1451 record!(self.tables.visibility[def_id.to_def_id()] <- ty::Visibility::Public);
1452 record!(self.tables.span[def_id.to_def_id()] <- self.tcx.def_span(def_id));
1453 self.encode_item_type(def_id.to_def_id());
1454 self.encode_generics(def_id.to_def_id());
1455 self.encode_explicit_predicates(def_id.to_def_id());
1456 self.encode_inferred_outlives(def_id.to_def_id());
1457 self.encode_optimized_mir(def_id);
1458 self.encode_promoted_mir(def_id);
1461 fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
1462 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1463 self.lazy(used_libraries.iter().cloned())
1466 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1467 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1468 self.lazy(foreign_modules.iter().cloned())
1471 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable) {
1472 let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1473 let mut expn_data_table: TableBuilder<_, _> = Default::default();
1475 let _: Result<(), !> = self.hygiene_ctxt.encode(
1476 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table),
1477 |(this, syntax_contexts, _), index, ctxt_data| {
1478 syntax_contexts.set(index, this.lazy(ctxt_data));
1481 |(this, _, expn_data_table), index, expn_data| {
1482 expn_data_table.set(index, this.lazy(expn_data));
1487 (syntax_contexts.encode(&mut self.opaque), expn_data_table.encode(&mut self.opaque))
1490 fn encode_proc_macros(&mut self) -> Option<Lazy<[DefIndex]>> {
1491 let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1494 Some(self.lazy(tcx.hir().krate().proc_macros.iter().map(|p| p.owner.local_def_index)))
1500 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1501 let crates = self.tcx.crates();
1503 let mut deps = crates
1506 let dep = CrateDep {
1507 name: self.tcx.original_crate_name(cnum),
1508 hash: self.tcx.crate_hash(cnum),
1509 host_hash: self.tcx.crate_host_hash(cnum),
1510 kind: self.tcx.dep_kind(cnum),
1511 extra_filename: self.tcx.extra_filename(cnum),
1515 .collect::<Vec<_>>();
1517 deps.sort_by_key(|&(cnum, _)| cnum);
1520 // Sanity-check the crate numbers
1521 let mut expected_cnum = 1;
1522 for &(n, _) in &deps {
1523 assert_eq!(n, CrateNum::new(expected_cnum));
1528 // We're just going to write a list of crate 'name-hash-version's, with
1529 // the assumption that they are numbered 1 to n.
1530 // FIXME (#2166): This is not nearly enough to support correct versioning
1531 // but is enough to get transitive crate dependencies working.
1532 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1535 fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> {
1537 let lib_features = tcx.lib_features();
1538 self.lazy(lib_features.to_vec())
1541 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1543 let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1544 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1547 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1549 let lang_items = tcx.lang_items();
1550 let lang_items = lang_items.items().iter();
1551 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1552 if let Some(def_id) = opt_def_id {
1553 if def_id.is_local() {
1554 return Some((def_id.index, i));
1561 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1563 self.lazy(&tcx.lang_items().missing)
1566 /// Encodes an index, mapping each trait to its (local) implementations.
1567 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1568 debug!("EncodeContext::encode_impls()");
1570 let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() };
1571 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1573 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1575 // Bring everything into deterministic order for hashing
1576 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1578 let all_impls: Vec<_> = all_impls
1580 .map(|(trait_def_id, mut impls)| {
1581 // Bring everything into deterministic order for hashing
1582 impls.sort_by_cached_key(|&(index, _)| {
1583 tcx.hir().definitions().def_path_hash(LocalDefId { local_def_index: index })
1587 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1588 impls: self.lazy(&impls),
1593 self.lazy(&all_impls)
1596 // Encodes all symbols exported from this crate into the metadata.
1598 // This pass is seeded off the reachability list calculated in the
1599 // middle::reachable module but filters out items that either don't have a
1600 // symbol associated with them (they weren't translated) or if they're an FFI
1601 // definition (as that's not defined in this crate).
1602 fn encode_exported_symbols(
1604 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1605 ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1606 // The metadata symbol name is special. It should not show up in
1607 // downstream crates.
1608 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1613 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1614 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1621 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1622 let formats = self.tcx.dependency_formats(LOCAL_CRATE);
1623 for (ty, arr) in formats.iter() {
1624 if *ty != CrateType::Dylib {
1627 return self.lazy(arr.iter().map(|slot| match *slot {
1628 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1630 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1631 Linkage::Static => Some(LinkagePreference::RequireStatic),
1637 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1640 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1642 record!(self.tables.kind[def_id] <- match nitem.kind {
1643 hir::ForeignItemKind::Fn(_, ref names, _) => {
1645 asyncness: hir::IsAsync::NotAsync,
1646 constness: if self.tcx.is_const_fn_raw(def_id) {
1647 hir::Constness::Const
1649 hir::Constness::NotConst
1651 param_names: self.encode_fn_param_names(names),
1653 EntryKind::ForeignFn(self.lazy(data))
1655 hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => EntryKind::ForeignMutStatic,
1656 hir::ForeignItemKind::Static(_, hir::Mutability::Not) => EntryKind::ForeignImmStatic,
1657 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1659 record!(self.tables.visibility[def_id] <-
1660 ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, self.tcx));
1661 record!(self.tables.span[def_id] <- nitem.span);
1662 record!(self.tables.attributes[def_id] <- nitem.attrs);
1663 self.encode_ident_span(def_id, nitem.ident);
1664 self.encode_stability(def_id);
1665 self.encode_const_stability(def_id);
1666 self.encode_deprecation(def_id);
1667 self.encode_item_type(def_id);
1668 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1669 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1670 self.encode_variances_of(def_id);
1672 self.encode_generics(def_id);
1673 self.encode_explicit_predicates(def_id);
1674 self.encode_inferred_outlives(def_id);
1678 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1679 impl Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1680 type Map = Map<'tcx>;
1682 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1683 NestedVisitorMap::OnlyBodies(self.tcx.hir())
1685 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1686 intravisit::walk_expr(self, ex);
1687 self.encode_info_for_expr(ex);
1689 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1690 intravisit::walk_anon_const(self, c);
1691 let def_id = self.tcx.hir().local_def_id(c.hir_id);
1692 self.encode_info_for_anon_const(def_id);
1694 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1695 intravisit::walk_item(self, item);
1696 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1698 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1699 _ => self.encode_info_for_item(def_id.to_def_id(), item),
1701 self.encode_addl_info_for_item(item);
1703 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1704 intravisit::walk_foreign_item(self, ni);
1705 let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1706 self.encode_info_for_foreign_item(def_id.to_def_id(), ni);
1708 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1709 intravisit::walk_generics(self, generics);
1710 self.encode_info_for_generics(generics);
1712 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) {
1713 self.encode_info_for_macro_def(macro_def);
1717 impl EncodeContext<'a, 'tcx> {
1718 fn encode_fields(&mut self, adt_def: &ty::AdtDef) {
1719 for (variant_index, variant) in adt_def.variants.iter_enumerated() {
1720 for (field_index, _field) in variant.fields.iter().enumerate() {
1721 self.encode_field(adt_def, variant_index, field_index);
1726 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1727 for param in generics.params {
1728 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1730 GenericParamKind::Lifetime { .. } => continue,
1731 GenericParamKind::Type { ref default, .. } => {
1732 self.encode_info_for_generic_param(
1734 EntryKind::TypeParam,
1738 GenericParamKind::Const { .. } => {
1739 self.encode_info_for_generic_param(
1741 EntryKind::ConstParam,
1749 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1750 if let hir::ExprKind::Closure(..) = expr.kind {
1751 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1752 self.encode_info_for_closure(def_id);
1756 fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) {
1757 record!(self.tables.ident_span[def_id] <- ident.span);
1760 /// In some cases, along with the item itself, we also
1761 /// encode some sub-items. Usually we want some info from the item
1762 /// so it's easier to do that here then to wait until we would encounter
1763 /// normally in the visitor walk.
1764 fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1765 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1767 hir::ItemKind::Static(..)
1768 | hir::ItemKind::Const(..)
1769 | hir::ItemKind::Fn(..)
1770 | hir::ItemKind::Mod(..)
1771 | hir::ItemKind::ForeignMod(..)
1772 | hir::ItemKind::GlobalAsm(..)
1773 | hir::ItemKind::ExternCrate(..)
1774 | hir::ItemKind::Use(..)
1775 | hir::ItemKind::TyAlias(..)
1776 | hir::ItemKind::OpaqueTy(..)
1777 | hir::ItemKind::TraitAlias(..) => {
1778 // no sub-item recording needed in these cases
1780 hir::ItemKind::Enum(..) => {
1781 let def = self.tcx.adt_def(def_id.to_def_id());
1782 self.encode_fields(def);
1784 for (i, variant) in def.variants.iter_enumerated() {
1785 self.encode_enum_variant_info(def, i);
1787 if let Some(_ctor_def_id) = variant.ctor_def_id {
1788 self.encode_enum_variant_ctor(def, i);
1792 hir::ItemKind::Struct(ref struct_def, _) => {
1793 let def = self.tcx.adt_def(def_id.to_def_id());
1794 self.encode_fields(def);
1796 // If the struct has a constructor, encode it.
1797 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1798 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1799 self.encode_struct_ctor(def, ctor_def_id.to_def_id());
1802 hir::ItemKind::Union(..) => {
1803 let def = self.tcx.adt_def(def_id.to_def_id());
1804 self.encode_fields(def);
1806 hir::ItemKind::Impl { .. } => {
1807 for &trait_item_def_id in
1808 self.tcx.associated_item_def_ids(def_id.to_def_id()).iter()
1810 self.encode_info_for_impl_item(trait_item_def_id);
1813 hir::ItemKind::Trait(..) => {
1814 for &item_def_id in self.tcx.associated_item_def_ids(def_id.to_def_id()).iter() {
1815 self.encode_info_for_trait_item(item_def_id);
1822 struct ImplVisitor<'tcx> {
1824 impls: FxHashMap<DefId, Vec<(DefIndex, Option<ty::fast_reject::SimplifiedType>)>>,
1827 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1828 fn visit_item(&mut self, item: &hir::Item<'_>) {
1829 if let hir::ItemKind::Impl { .. } = item.kind {
1830 let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1831 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id.to_def_id()) {
1832 let simplified_self_ty =
1833 ty::fast_reject::simplify_type(self.tcx, trait_ref.self_ty(), false);
1836 .entry(trait_ref.def_id)
1838 .push((impl_id.local_def_index, simplified_self_ty));
1843 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
1845 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
1846 // handled in `visit_item` above
1850 /// Used to prefetch queries which will be needed later by metadata encoding.
1851 /// Only a subset of the queries are actually prefetched to keep this code smaller.
1852 struct PrefetchVisitor<'tcx> {
1854 mir_keys: &'tcx FxHashSet<LocalDefId>,
1857 impl<'tcx> PrefetchVisitor<'tcx> {
1858 fn prefetch_mir(&self, def_id: LocalDefId) {
1859 if self.mir_keys.contains(&def_id) {
1860 self.tcx.ensure().optimized_mir(def_id);
1861 self.tcx.ensure().promoted_mir(def_id);
1866 impl<'tcx, 'v> ParItemLikeVisitor<'v> for PrefetchVisitor<'tcx> {
1867 fn visit_item(&self, item: &hir::Item<'_>) {
1868 // This should be kept in sync with `encode_info_for_item`.
1871 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
1872 self.prefetch_mir(tcx.hir().local_def_id(item.hir_id))
1874 hir::ItemKind::Fn(ref sig, ..) => {
1875 let def_id = tcx.hir().local_def_id(item.hir_id);
1876 let generics = tcx.generics_of(def_id.to_def_id());
1877 let needs_inline = generics.requires_monomorphization(tcx)
1878 || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline();
1879 if needs_inline || sig.header.constness == hir::Constness::Const {
1880 self.prefetch_mir(def_id)
1887 fn visit_trait_item(&self, trait_item: &'v hir::TraitItem<'v>) {
1888 // This should be kept in sync with `encode_info_for_trait_item`.
1889 self.prefetch_mir(self.tcx.hir().local_def_id(trait_item.hir_id));
1892 fn visit_impl_item(&self, impl_item: &'v hir::ImplItem<'v>) {
1893 // This should be kept in sync with `encode_info_for_impl_item`.
1895 match impl_item.kind {
1896 hir::ImplItemKind::Const(..) => {
1897 self.prefetch_mir(tcx.hir().local_def_id(impl_item.hir_id))
1899 hir::ImplItemKind::Fn(ref sig, _) => {
1900 let def_id = tcx.hir().local_def_id(impl_item.hir_id);
1901 let generics = tcx.generics_of(def_id.to_def_id());
1902 let needs_inline = generics.requires_monomorphization(tcx)
1903 || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline();
1904 let is_const_fn = sig.header.constness == hir::Constness::Const;
1905 if needs_inline || is_const_fn {
1906 self.prefetch_mir(def_id)
1909 hir::ImplItemKind::TyAlias(..) => (),
1914 // NOTE(eddyb) The following comment was preserved for posterity, even
1915 // though it's no longer relevant as EBML (which uses nested & tagged
1916 // "documents") was replaced with a scheme that can't go out of bounds.
1918 // And here we run into yet another obscure archive bug: in which metadata
1919 // loaded from archives may have trailing garbage bytes. Awhile back one of
1920 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1921 // and opt) by having ebml generate an out-of-bounds panic when looking at
1924 // Upon investigation it turned out that the metadata file inside of an rlib
1925 // (and ar archive) was being corrupted. Some compilations would generate a
1926 // metadata file which would end in a few extra bytes, while other
1927 // compilations would not have these extra bytes appended to the end. These
1928 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1929 // being interpreted causing the out-of-bounds.
1931 // The root cause of why these extra bytes were appearing was never
1932 // discovered, and in the meantime the solution we're employing is to insert
1933 // the length of the metadata to the start of the metadata. Later on this
1934 // will allow us to slice the metadata to the precise length that we just
1935 // generated regardless of trailing bytes that end up in it.
1937 pub(super) fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
1938 // Since encoding metadata is not in a query, and nothing is cached,
1939 // there's no need to do dep-graph tracking for any of it.
1940 tcx.dep_graph.assert_ignored();
1943 || encode_metadata_impl(tcx),
1945 if tcx.sess.threads() == 1 {
1948 // Prefetch some queries used by metadata encoding.
1949 // This is not necessary for correctness, but is only done for performance reasons.
1950 // It can be removed if it turns out to cause trouble or be detrimental to performance.
1953 if !tcx.sess.opts.output_types.should_codegen() {
1954 // We won't emit MIR, so don't prefetch it.
1957 tcx.hir().krate().par_visit_all_item_likes(&PrefetchVisitor {
1959 mir_keys: tcx.mir_keys(LOCAL_CRATE),
1962 || tcx.exported_symbols(LOCAL_CRATE),
1969 fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata {
1970 let mut encoder = opaque::Encoder::new(vec![]);
1971 encoder.emit_raw_bytes(METADATA_HEADER);
1973 // Will be filled with the root position after encoding everything.
1974 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1976 let source_map_files = tcx.sess.source_map().files();
1977 let hygiene_ctxt = HygieneEncodeContext::default();
1979 let mut ecx = EncodeContext {
1982 tables: Default::default(),
1983 lazy_state: LazyState::NoNode,
1984 type_shorthands: Default::default(),
1985 predicate_shorthands: Default::default(),
1986 source_file_cache: (source_map_files[0].clone(), 0),
1987 interpret_allocs: Default::default(),
1988 required_source_files: Some(GrowableBitSet::with_capacity(source_map_files.len())),
1989 is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
1990 hygiene_ctxt: &hygiene_ctxt,
1992 drop(source_map_files);
1994 // Encode the rustc version string in a predictable location.
1995 rustc_version().encode(&mut ecx).unwrap();
1997 // Encode all the entries and extra information in the crate,
1998 // culminating in the `CrateRoot` which points to all of it.
1999 let root = ecx.encode_crate_root();
2001 let mut result = ecx.opaque.into_inner();
2003 // Encode the root position.
2004 let header = METADATA_HEADER.len();
2005 let pos = root.position.get();
2006 result[header + 0] = (pos >> 24) as u8;
2007 result[header + 1] = (pos >> 16) as u8;
2008 result[header + 2] = (pos >> 8) as u8;
2009 result[header + 3] = (pos >> 0) as u8;
2011 EncodedMetadata { raw_data: result }