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::definitions::DefPathTable;
13 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
14 use rustc_hir::itemlikevisit::{ItemLikeVisitor, ParItemLikeVisitor};
15 use rustc_hir::lang_items;
16 use rustc_hir::{AnonConst, GenericParamKind};
17 use rustc_index::bit_set::GrowableBitSet;
18 use rustc_index::vec::Idx;
19 use rustc_middle::hir::map::Map;
20 use rustc_middle::middle::cstore::{EncodedMetadata, ForeignModule, LinkagePreference, NativeLib};
21 use rustc_middle::middle::dependency_format::Linkage;
22 use rustc_middle::middle::exported_symbols::{
23 metadata_symbol_name, ExportedSymbol, SymbolExportLevel,
25 use rustc_middle::mir::interpret;
26 use rustc_middle::traits::specialization_graph;
27 use rustc_middle::ty::codec::TyEncoder;
28 use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
29 use rustc_serialize::{opaque, Encodable, Encoder};
30 use rustc_session::config::CrateType;
31 use rustc_span::hygiene::{ExpnDataEncodeMode, HygieneEncodeContext};
32 use rustc_span::source_map::Spanned;
33 use rustc_span::symbol::{sym, Ident, Symbol};
34 use rustc_span::{self, ExternalSource, FileName, SourceFile, Span, SyntaxContext};
35 use rustc_target::abi::VariantIdx;
37 use std::num::NonZeroUsize;
39 use tracing::{debug, trace};
41 pub(super) struct EncodeContext<'a, 'tcx> {
42 opaque: opaque::Encoder,
45 tables: TableBuilders<'tcx>,
47 lazy_state: LazyState,
48 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
49 predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
51 interpret_allocs: FxIndexSet<interpret::AllocId>,
53 // This is used to speed up Span encoding.
54 // The `usize` is an index into the `MonotonicVec`
55 // that stores the `SourceFile`
56 source_file_cache: (Lrc<SourceFile>, usize),
57 // The indices (into the `SourceMap`'s `MonotonicVec`)
58 // of all of the `SourceFiles` that we need to serialize.
59 // When we serialize a `Span`, we insert the index of its
60 // `SourceFile` into the `GrowableBitSet`.
62 // This needs to be a `GrowableBitSet` and not a
63 // regular `BitSet` because we may actually import new `SourceFiles`
64 // during metadata encoding, due to executing a query
65 // with a result containing a foreign `Span`.
66 required_source_files: Option<GrowableBitSet<usize>>,
68 hygiene_ctxt: &'a HygieneEncodeContext,
71 macro_rules! encoder_methods {
72 ($($name:ident($ty:ty);)*) => {
73 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
74 self.opaque.$name(value)
79 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
80 type Error = <opaque::Encoder as Encoder>::Error;
83 fn emit_unit(&mut self) -> Result<(), Self::Error> {
110 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
113 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
114 e.emit_lazy_distance(*self)
118 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
121 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
122 e.emit_usize(self.meta)?;
126 e.emit_lazy_distance(*self)
130 impl<'a, 'tcx, I: Idx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
131 for Lazy<Table<I, T>>
133 Option<T>: FixedSizeEncoding,
135 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
136 e.emit_usize(self.meta)?;
137 e.emit_lazy_distance(*self)
141 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex {
142 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
143 s.emit_u32(self.as_u32())
147 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
148 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
149 rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s)
153 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
154 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
155 rustc_span::hygiene::raw_encode_expn_id(
158 ExpnDataEncodeMode::Metadata,
164 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
165 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
167 return TAG_INVALID_SPAN.encode(s);
170 let span = self.data();
172 // The Span infrastructure should make sure that this invariant holds:
173 debug_assert!(span.lo <= span.hi);
175 if !s.source_file_cache.0.contains(span.lo) {
176 let source_map = s.tcx.sess.source_map();
177 let source_file_index = source_map.lookup_source_file_idx(span.lo);
178 s.source_file_cache =
179 (source_map.files()[source_file_index].clone(), source_file_index);
182 if !s.source_file_cache.0.contains(span.hi) {
183 // Unfortunately, macro expansion still sometimes generates Spans
184 // that malformed in this way.
185 return TAG_INVALID_SPAN.encode(s);
188 let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!");
189 // Record the fact that we need to encode the data for this `SourceFile`
190 source_files.insert(s.source_file_cache.1);
192 // There are two possible cases here:
193 // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
194 // crate we are writing metadata for. When the metadata for *this* crate gets
195 // deserialized, the deserializer will need to know which crate it originally came
196 // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
197 // be deserialized after the rest of the span data, which tells the deserializer
198 // which crate contains the source map information.
199 // 2. This span comes from our own crate. No special hamdling is needed - we just
200 // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
201 // our own source map information.
203 // If we're a proc-macro crate, we always treat this as a local `Span`.
204 // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
205 // if we're a proc-macro crate.
206 // This allows us to avoid loading the dependencies of proc-macro crates: all of
207 // the information we need to decode `Span`s is stored in the proc-macro crate.
208 let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro {
209 // To simplify deserialization, we 'rebase' this span onto the crate it originally came from
210 // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values
211 // are relative to the source map information for the 'foreign' crate whose CrateNum
212 // we write into the metadata. This allows `imported_source_files` to binary
213 // search through the 'foreign' crate's source map information, using the
214 // deserialized 'lo' and 'hi' values directly.
216 // All of this logic ensures that the final result of deserialization is a 'normal'
217 // Span that can be used without any additional trouble.
218 let external_start_pos = {
219 // Introduce a new scope so that we drop the 'lock()' temporary
220 match &*s.source_file_cache.0.external_src.lock() {
221 ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos,
222 src => panic!("Unexpected external source {:?}", src),
225 let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos;
226 let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos;
228 (TAG_VALID_SPAN_FOREIGN, lo, hi)
230 (TAG_VALID_SPAN_LOCAL, span.lo, span.hi)
236 // Encode length which is usually less than span.hi and profits more
237 // from the variable-length integer encoding that we use.
241 // Don't serialize any `SyntaxContext`s from a proc-macro crate,
242 // since we don't load proc-macro dependencies during serialization.
243 // This means that any hygiene information from macros used *within*
244 // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
245 // definition) will be lost.
247 // This can show up in two ways:
249 // 1. Any hygiene information associated with identifier of
250 // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
251 // Since proc-macros can only be invoked from a different crate,
252 // real code should never need to care about this.
254 // 2. Using `Span::def_site` or `Span::mixed_site` will not
255 // include any hygiene information associated with the definition
256 // site. This means that a proc-macro cannot emit a `$crate`
257 // identifier which resolves to one of its dependencies,
258 // which also should never come up in practice.
260 // Additionally, this affects `Span::parent`, and any other
261 // span inspection APIs that would otherwise allow traversing
262 // the `SyntaxContexts` associated with a span.
264 // None of these user-visible effects should result in any
265 // cross-crate inconsistencies (getting one behavior in the same
266 // crate, and a different behavior in another crate) due to the
267 // limited surface that proc-macros can expose.
269 // IMPORTANT: If this is ever changed, be sure to update
270 // `rustc_span::hygiene::raw_encode_expn_id` to handle
271 // encoding `ExpnData` for proc-macro crates.
273 SyntaxContext::root().encode(s)?;
275 span.ctxt.encode(s)?;
278 if tag == TAG_VALID_SPAN_FOREIGN {
279 // This needs to be two lines to avoid holding the `s.source_file_cache`
280 // while calling `cnum.encode(s)`
281 let cnum = s.source_file_cache.0.cnum;
289 impl<'a, 'tcx> FingerprintEncoder for EncodeContext<'a, 'tcx> {
290 fn encode_fingerprint(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
291 f.encode_opaque(&mut self.opaque)
295 impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
296 const CLEAR_CROSS_CRATE: bool = true;
298 fn position(&self) -> usize {
299 self.opaque.position()
302 fn tcx(&self) -> TyCtxt<'tcx> {
306 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
307 &mut self.type_shorthands
310 fn predicate_shorthands(&mut self) -> &mut FxHashMap<rustc_middle::ty::Predicate<'tcx>, usize> {
311 &mut self.predicate_shorthands
316 alloc_id: &rustc_middle::mir::interpret::AllocId,
317 ) -> Result<(), Self::Error> {
318 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
324 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
325 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
330 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
331 trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> {
332 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta;
335 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for &T {
336 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
337 self.encode(ecx).unwrap()
341 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for T {
342 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
343 self.encode(ecx).unwrap()
347 impl<'a, 'tcx, I, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, [T]> for I
350 I::Item: EncodeContentsForLazy<'a, 'tcx, T>,
352 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize {
353 self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
357 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would
358 // normally need extra variables to avoid errors about multiple mutable borrows.
359 macro_rules! record {
360 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
363 let lazy = $self.lazy(value);
364 $self.$tables.$table.set($def_id.index, lazy);
369 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
370 fn emit_lazy_distance<T: ?Sized + LazyMeta>(
373 ) -> Result<(), <Self as Encoder>::Error> {
374 let min_end = lazy.position.get() + T::min_size(lazy.meta);
375 let distance = match self.lazy_state {
376 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
377 LazyState::NodeStart(start) => {
378 let start = start.get();
379 assert!(min_end <= start);
382 LazyState::Previous(last_min_end) => {
384 last_min_end <= lazy.position,
385 "make sure that the calls to `lazy*` \
386 are in the same order as the metadata fields",
388 lazy.position.get() - last_min_end.get()
391 self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap());
392 self.emit_usize(distance)
395 fn lazy<T: ?Sized + LazyMeta>(
397 value: impl EncodeContentsForLazy<'a, 'tcx, T>,
399 let pos = NonZeroUsize::new(self.position()).unwrap();
401 assert_eq!(self.lazy_state, LazyState::NoNode);
402 self.lazy_state = LazyState::NodeStart(pos);
403 let meta = value.encode_contents_for_lazy(self);
404 self.lazy_state = LazyState::NoNode;
406 assert!(pos.get() + <T>::min_size(meta) <= self.position());
408 Lazy::from_position_and_meta(pos, meta)
411 fn encode_info_for_items(&mut self) {
412 let krate = self.tcx.hir().krate();
413 let vis = Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public };
414 self.encode_info_for_mod(hir::CRATE_HIR_ID, &krate.item.module, &krate.item.attrs, &vis);
415 krate.visit_all_item_likes(&mut self.as_deep_visitor());
416 for macro_def in krate.exported_macros {
417 self.visit_macro_def(macro_def);
421 fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
422 let definitions = self.tcx.hir().definitions();
423 self.lazy(definitions.def_path_table())
426 fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> {
427 let source_map = self.tcx.sess.source_map();
428 let all_source_files = source_map.files();
430 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
431 // By replacing the `Option` with `None`, we ensure that we can't
432 // accidentally serialize any more `Span`s after the source map encoding
434 let required_source_files = self.required_source_files.take().unwrap();
436 let adapted = all_source_files
439 .filter(|(idx, source_file)| {
440 // Only serialize `SourceFile`s that were used
441 // during the encoding of a `Span`
442 required_source_files.contains(*idx) &&
443 // Don't serialize imported `SourceFile`s, unless
444 // we're in a proc-macro crate.
445 (!source_file.is_imported() || self.is_proc_macro)
447 .map(|(_, source_file)| {
448 let mut adapted = match source_file.name {
449 // This path of this SourceFile has been modified by
450 // path-remapping, so we use it verbatim (and avoid
451 // cloning the whole map in the process).
452 _ if source_file.name_was_remapped => source_file.clone(),
454 // Otherwise expand all paths to absolute paths because
455 // any relative paths are potentially relative to a
457 FileName::Real(ref name) => {
458 let name = name.stable_name();
459 let mut adapted = (**source_file).clone();
460 adapted.name = Path::new(&working_dir).join(name).into();
461 adapted.name_hash = {
462 let mut hasher: StableHasher = StableHasher::new();
463 adapted.name.hash(&mut hasher);
464 hasher.finish::<u128>()
469 // expanded code, not from a file
470 _ => source_file.clone(),
473 // We're serializing this `SourceFile` into our crate metadata,
474 // so mark it as coming from this crate.
475 // This also ensures that we don't try to deserialize the
476 // `CrateNum` for a proc-macro dependency - since proc macro
477 // dependencies aren't loaded when we deserialize a proc-macro,
478 // trying to remap the `CrateNum` would fail.
479 if self.is_proc_macro {
480 Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE;
484 .collect::<Vec<_>>();
486 self.lazy(adapted.iter().map(|rc| &**rc))
489 fn is_proc_macro(&self) -> bool {
490 self.tcx.sess.crate_types().contains(&CrateType::ProcMacro)
493 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
494 let is_proc_macro = self.is_proc_macro();
496 let mut i = self.position();
498 // Encode the crate deps
499 let crate_deps = self.encode_crate_deps();
500 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
501 let dep_bytes = self.position() - i;
503 // Encode the lib features.
505 let lib_features = self.encode_lib_features();
506 let lib_feature_bytes = self.position() - i;
508 // Encode the language items.
510 let lang_items = self.encode_lang_items();
511 let lang_items_missing = self.encode_lang_items_missing();
512 let lang_item_bytes = self.position() - i;
514 // Encode the diagnostic items.
516 let diagnostic_items = self.encode_diagnostic_items();
517 let diagnostic_item_bytes = self.position() - i;
519 // Encode the native libraries used
521 let native_libraries = self.encode_native_libraries();
522 let native_lib_bytes = self.position() - i;
524 let foreign_modules = self.encode_foreign_modules();
526 // Encode DefPathTable
528 let def_path_table = self.encode_def_path_table();
529 let def_path_table_bytes = self.position() - i;
531 // Encode the def IDs of impls, for coherence checking.
533 let impls = self.encode_impls();
534 let impl_bytes = self.position() - i;
540 self.encode_info_for_items();
541 let item_bytes = self.position() - i;
543 // Encode the allocation index
544 let interpret_alloc_index = {
545 let mut interpret_alloc_index = Vec::new();
547 trace!("beginning to encode alloc ids");
549 let new_n = self.interpret_allocs.len();
550 // if we have found new ids, serialize those, too
555 trace!("encoding {} further alloc ids", new_n - n);
556 for idx in n..new_n {
557 let id = self.interpret_allocs[idx];
558 let pos = self.position() as u32;
559 interpret_alloc_index.push(pos);
560 interpret::specialized_encode_alloc_id(self, tcx, id).unwrap();
564 self.lazy(interpret_alloc_index)
568 let tables = self.tables.encode(&mut self.opaque);
569 let tables_bytes = self.position() - i;
571 // Encode the proc macro data
573 let proc_macro_data = self.encode_proc_macros();
574 let proc_macro_data_bytes = self.position() - i;
576 // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
577 // this as late as possible to give the prefetching as much time as possible to complete.
579 let exported_symbols = tcx.exported_symbols(LOCAL_CRATE);
580 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
581 let exported_symbols_bytes = self.position() - i;
583 // Encode the hygiene data,
584 // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process
585 // of encoding other items (e.g. `optimized_mir`) may cause us to load
586 // data from the incremental cache. If this causes us to deserialize a `Span`,
587 // then we may load additional `SyntaxContext`s into the global `HygieneData`.
588 // Therefore, we need to encode the hygiene data last to ensure that we encode
589 // any `SyntaxContext`s that might be used.
591 let (syntax_contexts, expn_data) = self.encode_hygiene();
592 let hygiene_bytes = self.position() - i;
594 // Encode source_map. This needs to be done last,
595 // since encoding `Span`s tells us which `SourceFiles` we actually
598 let source_map = self.encode_source_map();
599 let source_map_bytes = self.position() - i;
601 let attrs = tcx.hir().krate_attrs();
602 let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator);
604 let root = self.lazy(CrateRoot {
605 name: tcx.crate_name(LOCAL_CRATE),
606 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
607 triple: tcx.sess.opts.target_triple.clone(),
608 hash: tcx.crate_hash(LOCAL_CRATE),
609 disambiguator: tcx.sess.local_crate_disambiguator(),
610 panic_strategy: tcx.sess.panic_strategy(),
611 edition: tcx.sess.edition(),
612 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
613 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
614 has_default_lib_allocator,
615 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
616 proc_macro_decls_static: if is_proc_macro {
617 let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap();
623 proc_macro_stability: if is_proc_macro {
624 tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied()
628 compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
629 needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
630 needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
631 no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
632 panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
633 profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
634 symbol_mangling_version: tcx.sess.opts.debugging_opts.symbol_mangling_version,
637 dylib_dependency_formats,
648 interpret_alloc_index,
654 let total_bytes = self.position();
656 if tcx.sess.meta_stats() {
657 let mut zero_bytes = 0;
658 for e in self.opaque.data.iter() {
664 println!("metadata stats:");
665 println!(" dep bytes: {}", dep_bytes);
666 println!(" lib feature bytes: {}", lib_feature_bytes);
667 println!(" lang item bytes: {}", lang_item_bytes);
668 println!(" diagnostic item bytes: {}", diagnostic_item_bytes);
669 println!(" native bytes: {}", native_lib_bytes);
670 println!(" source_map bytes: {}", source_map_bytes);
671 println!(" impl bytes: {}", impl_bytes);
672 println!(" exp. symbols bytes: {}", exported_symbols_bytes);
673 println!(" def-path table bytes: {}", def_path_table_bytes);
674 println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
675 println!(" item bytes: {}", item_bytes);
676 println!(" table bytes: {}", tables_bytes);
677 println!(" hygiene bytes: {}", hygiene_bytes);
678 println!(" zero bytes: {}", zero_bytes);
679 println!(" total bytes: {}", total_bytes);
686 impl EncodeContext<'a, 'tcx> {
687 fn encode_variances_of(&mut self, def_id: DefId) {
688 debug!("EncodeContext::encode_variances_of({:?})", def_id);
689 record!(self.tables.variances[def_id] <- &self.tcx.variances_of(def_id)[..]);
692 fn encode_item_type(&mut self, def_id: DefId) {
693 debug!("EncodeContext::encode_item_type({:?})", def_id);
694 record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id));
697 fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) {
699 let variant = &def.variants[index];
700 let def_id = variant.def_id;
701 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
703 let data = VariantData {
704 ctor_kind: variant.ctor_kind,
705 discr: variant.discr,
706 ctor: variant.ctor_def_id.map(|did| did.index),
707 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
710 let enum_id = tcx.hir().local_def_id_to_hir_id(def.did.expect_local());
711 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
713 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
714 record!(self.tables.visibility[def_id] <-
715 ty::Visibility::from_hir(enum_vis, enum_id, self.tcx));
716 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
717 record!(self.tables.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
718 record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
719 assert!(f.did.is_local());
722 self.encode_ident_span(def_id, variant.ident);
723 self.encode_stability(def_id);
724 self.encode_deprecation(def_id);
725 self.encode_item_type(def_id);
726 if variant.ctor_kind == CtorKind::Fn {
727 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
728 if let Some(ctor_def_id) = variant.ctor_def_id {
729 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
731 // FIXME(eddyb) is this ever used?
732 self.encode_variances_of(def_id);
734 self.encode_generics(def_id);
735 self.encode_explicit_predicates(def_id);
736 self.encode_inferred_outlives(def_id);
737 self.encode_optimized_mir(def_id.expect_local());
738 self.encode_promoted_mir(def_id.expect_local());
741 fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) {
743 let variant = &def.variants[index];
744 let def_id = variant.ctor_def_id.unwrap();
745 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
747 // FIXME(eddyb) encode only the `CtorKind` for constructors.
748 let data = VariantData {
749 ctor_kind: variant.ctor_kind,
750 discr: variant.discr,
751 ctor: Some(def_id.index),
752 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
755 // Variant constructors have the same visibility as the parent enums, unless marked as
756 // non-exhaustive, in which case they are lowered to `pub(crate)`.
757 let enum_id = tcx.hir().local_def_id_to_hir_id(def.did.expect_local());
758 let enum_vis = &tcx.hir().expect_item(enum_id).vis;
759 let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx);
760 if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public {
761 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
764 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
765 record!(self.tables.visibility[def_id] <- ctor_vis);
766 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
767 self.encode_stability(def_id);
768 self.encode_deprecation(def_id);
769 self.encode_item_type(def_id);
770 if variant.ctor_kind == CtorKind::Fn {
771 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
772 self.encode_variances_of(def_id);
774 self.encode_generics(def_id);
775 self.encode_explicit_predicates(def_id);
776 self.encode_inferred_outlives(def_id);
777 self.encode_optimized_mir(def_id.expect_local());
778 self.encode_promoted_mir(def_id.expect_local());
781 fn encode_info_for_mod(
785 attrs: &[ast::Attribute],
786 vis: &hir::Visibility<'_>,
789 let local_def_id = tcx.hir().local_def_id(id);
790 let def_id = local_def_id.to_def_id();
791 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
794 reexports: match tcx.module_exports(local_def_id) {
796 let hir = self.tcx.hir();
800 .map(|export| export.map_id(|id| hir.local_def_id_to_hir_id(id))),
805 expansion: tcx.hir().definitions().expansion_that_defined(local_def_id),
808 record!(self.tables.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
809 record!(self.tables.visibility[def_id] <- ty::Visibility::from_hir(vis, id, self.tcx));
810 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
811 record!(self.tables.attributes[def_id] <- attrs);
812 record!(self.tables.children[def_id] <- md.item_ids.iter().map(|item_id| {
813 tcx.hir().local_def_id(item_id.id).local_def_index
815 self.encode_stability(def_id);
816 self.encode_deprecation(def_id);
821 adt_def: &ty::AdtDef,
822 variant_index: VariantIdx,
826 let variant = &adt_def.variants[variant_index];
827 let field = &variant.fields[field_index];
829 let def_id = field.did;
830 debug!("EncodeContext::encode_field({:?})", def_id);
832 let variant_id = tcx.hir().local_def_id_to_hir_id(variant.def_id.expect_local());
833 let variant_data = tcx.hir().expect_variant_data(variant_id);
835 record!(self.tables.kind[def_id] <- EntryKind::Field);
836 record!(self.tables.visibility[def_id] <- field.vis);
837 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
838 record!(self.tables.attributes[def_id] <- variant_data.fields()[field_index].attrs);
839 self.encode_ident_span(def_id, field.ident);
840 self.encode_stability(def_id);
841 self.encode_deprecation(def_id);
842 self.encode_item_type(def_id);
843 self.encode_generics(def_id);
844 self.encode_explicit_predicates(def_id);
845 self.encode_inferred_outlives(def_id);
848 fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) {
849 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
851 let variant = adt_def.non_enum_variant();
853 let data = VariantData {
854 ctor_kind: variant.ctor_kind,
855 discr: variant.discr,
856 ctor: Some(def_id.index),
857 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
860 let struct_id = tcx.hir().local_def_id_to_hir_id(adt_def.did.expect_local());
861 let struct_vis = &tcx.hir().expect_item(struct_id).vis;
862 let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
863 for field in &variant.fields {
864 if ctor_vis.is_at_least(field.vis, tcx) {
865 ctor_vis = field.vis;
869 // If the structure is marked as non_exhaustive then lower the visibility
870 // to within the crate.
871 if adt_def.non_enum_variant().is_field_list_non_exhaustive()
872 && ctor_vis == ty::Visibility::Public
874 ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
877 record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
878 record!(self.tables.visibility[def_id] <- ctor_vis);
879 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
880 self.encode_stability(def_id);
881 self.encode_deprecation(def_id);
882 self.encode_item_type(def_id);
883 if variant.ctor_kind == CtorKind::Fn {
884 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
885 self.encode_variances_of(def_id);
887 self.encode_generics(def_id);
888 self.encode_explicit_predicates(def_id);
889 self.encode_inferred_outlives(def_id);
890 self.encode_optimized_mir(def_id.expect_local());
891 self.encode_promoted_mir(def_id.expect_local());
894 fn encode_generics(&mut self, def_id: DefId) {
895 debug!("EncodeContext::encode_generics({:?})", def_id);
896 record!(self.tables.generics[def_id] <- self.tcx.generics_of(def_id));
899 fn encode_explicit_predicates(&mut self, def_id: DefId) {
900 debug!("EncodeContext::encode_explicit_predicates({:?})", def_id);
901 record!(self.tables.explicit_predicates[def_id] <-
902 self.tcx.explicit_predicates_of(def_id));
905 fn encode_inferred_outlives(&mut self, def_id: DefId) {
906 debug!("EncodeContext::encode_inferred_outlives({:?})", def_id);
907 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
908 if !inferred_outlives.is_empty() {
909 record!(self.tables.inferred_outlives[def_id] <- inferred_outlives);
913 fn encode_super_predicates(&mut self, def_id: DefId) {
914 debug!("EncodeContext::encode_super_predicates({:?})", def_id);
915 record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
918 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
919 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
922 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
923 let ast_item = tcx.hir().expect_trait_item(hir_id);
924 let trait_item = tcx.associated_item(def_id);
926 let container = match trait_item.defaultness {
927 hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
928 hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
929 hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
932 record!(self.tables.kind[def_id] <- match trait_item.kind {
933 ty::AssocKind::Const => {
934 let rendered = rustc_hir_pretty::to_string(
935 &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
936 |s| s.print_trait_item(ast_item)
938 let rendered_const = self.lazy(RenderedConst(rendered));
940 EntryKind::AssocConst(
946 ty::AssocKind::Fn => {
947 let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind {
948 let param_names = match *m {
949 hir::TraitFn::Required(ref names) => {
950 self.encode_fn_param_names(names)
952 hir::TraitFn::Provided(body) => {
953 self.encode_fn_param_names_for_body(body)
957 asyncness: m_sig.header.asyncness,
958 constness: hir::Constness::NotConst,
964 EntryKind::AssocFn(self.lazy(AssocFnData {
967 has_self: trait_item.fn_has_self_parameter,
970 ty::AssocKind::Type => EntryKind::AssocType(container),
972 record!(self.tables.visibility[def_id] <- trait_item.vis);
973 record!(self.tables.span[def_id] <- ast_item.span);
974 record!(self.tables.attributes[def_id] <- ast_item.attrs);
975 self.encode_ident_span(def_id, ast_item.ident);
976 self.encode_stability(def_id);
977 self.encode_const_stability(def_id);
978 self.encode_deprecation(def_id);
979 match trait_item.kind {
980 ty::AssocKind::Const | ty::AssocKind::Fn => {
981 self.encode_item_type(def_id);
983 ty::AssocKind::Type => {
984 if trait_item.defaultness.has_value() {
985 self.encode_item_type(def_id);
989 if trait_item.kind == ty::AssocKind::Fn {
990 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
991 self.encode_variances_of(def_id);
993 self.encode_generics(def_id);
994 self.encode_explicit_predicates(def_id);
995 self.encode_inferred_outlives(def_id);
997 // This should be kept in sync with `PrefetchVisitor.visit_trait_item`.
998 self.encode_optimized_mir(def_id.expect_local());
999 self.encode_promoted_mir(def_id.expect_local());
1002 fn metadata_output_only(&self) -> bool {
1003 // MIR optimisation can be skipped when we're just interested in the metadata.
1004 !self.tcx.sess.opts.output_types.should_codegen()
1007 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1008 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1011 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1012 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
1013 let impl_item = self.tcx.associated_item(def_id);
1015 let container = match impl_item.defaultness {
1016 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
1017 hir::Defaultness::Final => AssocContainer::ImplFinal,
1018 hir::Defaultness::Default { has_value: false } => {
1019 span_bug!(ast_item.span, "impl items always have values (currently)")
1023 record!(self.tables.kind[def_id] <- match impl_item.kind {
1024 ty::AssocKind::Const => {
1025 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1026 let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1028 EntryKind::AssocConst(
1031 self.encode_rendered_const_for_body(body_id))
1036 ty::AssocKind::Fn => {
1037 let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind {
1039 asyncness: sig.header.asyncness,
1040 constness: sig.header.constness,
1041 param_names: self.encode_fn_param_names_for_body(body),
1046 EntryKind::AssocFn(self.lazy(AssocFnData {
1049 has_self: impl_item.fn_has_self_parameter,
1052 ty::AssocKind::Type => EntryKind::AssocType(container)
1054 record!(self.tables.visibility[def_id] <- impl_item.vis);
1055 record!(self.tables.span[def_id] <- ast_item.span);
1056 record!(self.tables.attributes[def_id] <- ast_item.attrs);
1057 self.encode_ident_span(def_id, impl_item.ident);
1058 self.encode_stability(def_id);
1059 self.encode_const_stability(def_id);
1060 self.encode_deprecation(def_id);
1061 self.encode_item_type(def_id);
1062 if impl_item.kind == ty::AssocKind::Fn {
1063 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1064 self.encode_variances_of(def_id);
1066 self.encode_generics(def_id);
1067 self.encode_explicit_predicates(def_id);
1068 self.encode_inferred_outlives(def_id);
1070 // The following part should be kept in sync with `PrefetchVisitor.visit_impl_item`.
1072 let mir = match ast_item.kind {
1073 hir::ImplItemKind::Const(..) => true,
1074 hir::ImplItemKind::Fn(ref sig, _) => {
1075 let generics = self.tcx.generics_of(def_id);
1076 let needs_inline = (generics.requires_monomorphization(self.tcx)
1077 || tcx.codegen_fn_attrs(def_id).requests_inline())
1078 && !self.metadata_output_only();
1079 let is_const_fn = sig.header.constness == hir::Constness::Const;
1080 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1081 needs_inline || is_const_fn || always_encode_mir
1083 hir::ImplItemKind::TyAlias(..) => false,
1086 self.encode_optimized_mir(def_id.expect_local());
1087 self.encode_promoted_mir(def_id.expect_local());
1091 fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> {
1092 self.tcx.dep_graph.with_ignore(|| self.lazy(self.tcx.hir().body_param_names(body_id)))
1095 fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> {
1096 self.lazy(param_names.iter())
1099 fn encode_optimized_mir(&mut self, def_id: LocalDefId) {
1100 debug!("EntryBuilder::encode_mir({:?})", def_id);
1101 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1102 record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1104 let unused = self.tcx.unused_generic_params(def_id);
1105 if !unused.is_empty() {
1106 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1111 fn encode_promoted_mir(&mut self, def_id: LocalDefId) {
1112 debug!("EncodeContext::encode_promoted_mir({:?})", def_id);
1113 if self.tcx.mir_keys(LOCAL_CRATE).contains(&def_id) {
1114 record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1118 // Encodes the inherent implementations of a structure, enumeration, or trait.
1119 fn encode_inherent_implementations(&mut self, def_id: DefId) {
1120 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1121 let implementations = self.tcx.inherent_impls(def_id);
1122 if !implementations.is_empty() {
1123 record!(self.tables.inherent_impls[def_id] <- implementations.iter().map(|&def_id| {
1124 assert!(def_id.is_local());
1130 fn encode_stability(&mut self, def_id: DefId) {
1131 debug!("EncodeContext::encode_stability({:?})", def_id);
1132 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1133 record!(self.tables.stability[def_id] <- stab)
1137 fn encode_const_stability(&mut self, def_id: DefId) {
1138 debug!("EncodeContext::encode_const_stability({:?})", def_id);
1139 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1140 record!(self.tables.const_stability[def_id] <- stab)
1144 fn encode_deprecation(&mut self, def_id: DefId) {
1145 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1146 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1147 record!(self.tables.deprecation[def_id] <- depr);
1151 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1152 let hir = self.tcx.hir();
1153 let body = hir.body(body_id);
1154 let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1155 s.print_expr(&body.value)
1157 let rendered_const = &RenderedConst(rendered);
1158 self.lazy(rendered_const)
1161 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1164 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1166 self.encode_ident_span(def_id, item.ident);
1168 record!(self.tables.kind[def_id] <- match item.kind {
1169 hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic,
1170 hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic,
1171 hir::ItemKind::Const(_, body_id) => {
1172 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1175 self.encode_rendered_const_for_body(body_id)
1178 hir::ItemKind::Fn(ref sig, .., body) => {
1180 asyncness: sig.header.asyncness,
1181 constness: sig.header.constness,
1182 param_names: self.encode_fn_param_names_for_body(body),
1185 EntryKind::Fn(self.lazy(data))
1187 hir::ItemKind::Mod(ref m) => {
1188 return self.encode_info_for_mod(item.hir_id, m, &item.attrs, &item.vis);
1190 hir::ItemKind::ForeignMod(_) => EntryKind::ForeignMod,
1191 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1192 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1193 hir::ItemKind::OpaqueTy(..) => EntryKind::OpaqueTy,
1194 hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1195 hir::ItemKind::Struct(ref struct_def, _) => {
1196 let adt_def = self.tcx.adt_def(def_id);
1197 let variant = adt_def.non_enum_variant();
1199 // Encode def_ids for each field and method
1200 // for methods, write all the stuff get_trait_method
1202 let ctor = struct_def.ctor_hir_id().map(|ctor_hir_id| {
1203 self.tcx.hir().local_def_id(ctor_hir_id).local_def_index
1206 EntryKind::Struct(self.lazy(VariantData {
1207 ctor_kind: variant.ctor_kind,
1208 discr: variant.discr,
1210 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1213 hir::ItemKind::Union(..) => {
1214 let adt_def = self.tcx.adt_def(def_id);
1215 let variant = adt_def.non_enum_variant();
1217 EntryKind::Union(self.lazy(VariantData {
1218 ctor_kind: variant.ctor_kind,
1219 discr: variant.discr,
1221 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1224 hir::ItemKind::Impl { defaultness, .. } => {
1225 let trait_ref = self.tcx.impl_trait_ref(def_id);
1226 let polarity = self.tcx.impl_polarity(def_id);
1227 let parent = if let Some(trait_ref) = trait_ref {
1228 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1229 trait_def.ancestors(self.tcx, def_id).ok()
1230 .and_then(|mut an| an.nth(1).and_then(|node| {
1232 specialization_graph::Node::Impl(parent) => Some(parent),
1240 // if this is an impl of `CoerceUnsized`, create its
1241 // "unsized info", else just store None
1242 let coerce_unsized_info =
1243 trait_ref.and_then(|t| {
1244 if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1245 Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1251 let data = ImplData {
1254 parent_impl: parent,
1255 coerce_unsized_info,
1258 EntryKind::Impl(self.lazy(data))
1260 hir::ItemKind::Trait(..) => {
1261 let trait_def = self.tcx.trait_def(def_id);
1262 let data = TraitData {
1263 unsafety: trait_def.unsafety,
1264 paren_sugar: trait_def.paren_sugar,
1265 has_auto_impl: self.tcx.trait_is_auto(def_id),
1266 is_marker: trait_def.is_marker,
1267 specialization_kind: trait_def.specialization_kind,
1270 EntryKind::Trait(self.lazy(data))
1272 hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1273 hir::ItemKind::ExternCrate(_) |
1274 hir::ItemKind::Use(..) => bug!("cannot encode info for item {:?}", item),
1276 record!(self.tables.visibility[def_id] <-
1277 ty::Visibility::from_hir(&item.vis, item.hir_id, tcx));
1278 record!(self.tables.span[def_id] <- item.span);
1279 record!(self.tables.attributes[def_id] <- item.attrs);
1280 // FIXME(eddyb) there should be a nicer way to do this.
1282 hir::ItemKind::ForeignMod(ref fm) => record!(self.tables.children[def_id] <-
1285 .map(|foreign_item| tcx.hir().local_def_id(
1286 foreign_item.hir_id).local_def_index)
1288 hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <-
1289 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1290 assert!(v.def_id.is_local());
1294 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1295 record!(self.tables.children[def_id] <-
1296 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1297 assert!(f.did.is_local());
1302 hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1303 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1304 record!(self.tables.children[def_id] <-
1305 associated_item_def_ids.iter().map(|&def_id| {
1306 assert!(def_id.is_local());
1313 self.encode_stability(def_id);
1314 self.encode_const_stability(def_id);
1315 self.encode_deprecation(def_id);
1317 hir::ItemKind::Static(..)
1318 | hir::ItemKind::Const(..)
1319 | hir::ItemKind::Fn(..)
1320 | hir::ItemKind::TyAlias(..)
1321 | hir::ItemKind::OpaqueTy(..)
1322 | hir::ItemKind::Enum(..)
1323 | hir::ItemKind::Struct(..)
1324 | hir::ItemKind::Union(..)
1325 | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1328 if let hir::ItemKind::Fn(..) = item.kind {
1329 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1331 if let hir::ItemKind::Impl { .. } = item.kind {
1332 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1333 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1336 self.encode_inherent_implementations(def_id);
1338 hir::ItemKind::Enum(..)
1339 | hir::ItemKind::Struct(..)
1340 | hir::ItemKind::Union(..)
1341 | hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1345 hir::ItemKind::Static(..)
1346 | hir::ItemKind::Const(..)
1347 | hir::ItemKind::Fn(..)
1348 | hir::ItemKind::TyAlias(..)
1349 | hir::ItemKind::Enum(..)
1350 | hir::ItemKind::Struct(..)
1351 | hir::ItemKind::Union(..)
1352 | hir::ItemKind::Impl { .. }
1353 | hir::ItemKind::OpaqueTy(..)
1354 | hir::ItemKind::Trait(..)
1355 | hir::ItemKind::TraitAlias(..) => {
1356 self.encode_generics(def_id);
1357 self.encode_explicit_predicates(def_id);
1358 self.encode_inferred_outlives(def_id);
1363 hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => {
1364 self.encode_super_predicates(def_id);
1369 // The following part should be kept in sync with `PrefetchVisitor.visit_item`.
1371 let mir = match item.kind {
1372 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => true,
1373 hir::ItemKind::Fn(ref sig, ..) => {
1374 let generics = tcx.generics_of(def_id);
1375 let needs_inline = (generics.requires_monomorphization(tcx)
1376 || tcx.codegen_fn_attrs(def_id).requests_inline())
1377 && !self.metadata_output_only();
1378 let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
1379 needs_inline || sig.header.constness == hir::Constness::Const || always_encode_mir
1384 self.encode_optimized_mir(def_id.expect_local());
1385 self.encode_promoted_mir(def_id.expect_local());
1389 /// Serialize the text of exported macros
1390 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) {
1391 let def_id = self.tcx.hir().local_def_id(macro_def.hir_id).to_def_id();
1392 record!(self.tables.kind[def_id] <- EntryKind::MacroDef(self.lazy(macro_def.ast.clone())));
1393 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1394 record!(self.tables.span[def_id] <- macro_def.span);
1395 record!(self.tables.attributes[def_id] <- macro_def.attrs);
1396 self.encode_ident_span(def_id, macro_def.ident);
1397 self.encode_stability(def_id);
1398 self.encode_deprecation(def_id);
1401 fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1402 record!(self.tables.kind[def_id] <- kind);
1403 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1404 record!(self.tables.span[def_id] <- self.tcx.def_span(def_id));
1406 self.encode_item_type(def_id);
1410 fn encode_info_for_closure(&mut self, def_id: LocalDefId) {
1411 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1413 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1414 // including on the signature, which is inferred in `typeck.
1415 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1416 let ty = self.tcx.typeck(def_id).node_type(hir_id);
1418 record!(self.tables.kind[def_id.to_def_id()] <- match ty.kind {
1419 ty::Generator(..) => {
1420 let data = self.tcx.generator_kind(def_id).unwrap();
1421 EntryKind::Generator(data)
1424 ty::Closure(..) => EntryKind::Closure,
1426 _ => bug!("closure that is neither generator nor closure"),
1428 record!(self.tables.visibility[def_id.to_def_id()] <- ty::Visibility::Public);
1429 record!(self.tables.span[def_id.to_def_id()] <- self.tcx.def_span(def_id));
1430 record!(self.tables.attributes[def_id.to_def_id()] <- &self.tcx.get_attrs(def_id.to_def_id())[..]);
1431 self.encode_item_type(def_id.to_def_id());
1432 if let ty::Closure(def_id, substs) = ty.kind {
1433 record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1435 self.encode_generics(def_id.to_def_id());
1436 self.encode_optimized_mir(def_id);
1437 self.encode_promoted_mir(def_id);
1440 fn encode_info_for_anon_const(&mut self, def_id: LocalDefId) {
1441 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1442 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1443 let body_id = self.tcx.hir().body_owned_by(id);
1444 let const_data = self.encode_rendered_const_for_body(body_id);
1445 let qualifs = self.tcx.mir_const_qualif(def_id);
1447 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data));
1448 record!(self.tables.visibility[def_id.to_def_id()] <- ty::Visibility::Public);
1449 record!(self.tables.span[def_id.to_def_id()] <- self.tcx.def_span(def_id));
1450 self.encode_item_type(def_id.to_def_id());
1451 self.encode_generics(def_id.to_def_id());
1452 self.encode_explicit_predicates(def_id.to_def_id());
1453 self.encode_inferred_outlives(def_id.to_def_id());
1454 self.encode_optimized_mir(def_id);
1455 self.encode_promoted_mir(def_id);
1458 fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
1459 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1460 self.lazy(used_libraries.iter().cloned())
1463 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1464 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1465 self.lazy(foreign_modules.iter().cloned())
1468 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable) {
1469 let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1470 let mut expn_data_table: TableBuilder<_, _> = Default::default();
1472 let _: Result<(), !> = self.hygiene_ctxt.encode(
1473 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table),
1474 |(this, syntax_contexts, _), index, ctxt_data| {
1475 syntax_contexts.set(index, this.lazy(ctxt_data));
1478 |(this, _, expn_data_table), index, expn_data| {
1479 expn_data_table.set(index, this.lazy(expn_data));
1484 (syntax_contexts.encode(&mut self.opaque), expn_data_table.encode(&mut self.opaque))
1487 fn encode_proc_macros(&mut self) -> Option<Lazy<[DefIndex]>> {
1488 let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1491 Some(self.lazy(tcx.hir().krate().proc_macros.iter().map(|p| p.owner.local_def_index)))
1497 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1498 let crates = self.tcx.crates();
1500 let mut deps = crates
1503 let dep = CrateDep {
1504 name: self.tcx.original_crate_name(cnum),
1505 hash: self.tcx.crate_hash(cnum),
1506 host_hash: self.tcx.crate_host_hash(cnum),
1507 kind: self.tcx.dep_kind(cnum),
1508 extra_filename: self.tcx.extra_filename(cnum),
1512 .collect::<Vec<_>>();
1514 deps.sort_by_key(|&(cnum, _)| cnum);
1517 // Sanity-check the crate numbers
1518 let mut expected_cnum = 1;
1519 for &(n, _) in &deps {
1520 assert_eq!(n, CrateNum::new(expected_cnum));
1525 // We're just going to write a list of crate 'name-hash-version's, with
1526 // the assumption that they are numbered 1 to n.
1527 // FIXME (#2166): This is not nearly enough to support correct versioning
1528 // but is enough to get transitive crate dependencies working.
1529 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1532 fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> {
1534 let lib_features = tcx.lib_features();
1535 self.lazy(lib_features.to_vec())
1538 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1540 let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1541 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1544 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1546 let lang_items = tcx.lang_items();
1547 let lang_items = lang_items.items().iter();
1548 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1549 if let Some(def_id) = opt_def_id {
1550 if def_id.is_local() {
1551 return Some((def_id.index, i));
1558 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1560 self.lazy(&tcx.lang_items().missing)
1563 /// Encodes an index, mapping each trait to its (local) implementations.
1564 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1565 debug!("EncodeContext::encode_impls()");
1567 let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() };
1568 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1570 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1572 // Bring everything into deterministic order for hashing
1573 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1575 let all_impls: Vec<_> = all_impls
1577 .map(|(trait_def_id, mut impls)| {
1578 // Bring everything into deterministic order for hashing
1579 impls.sort_by_cached_key(|&(index, _)| {
1580 tcx.hir().definitions().def_path_hash(LocalDefId { local_def_index: index })
1584 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1585 impls: self.lazy(&impls),
1590 self.lazy(&all_impls)
1593 // Encodes all symbols exported from this crate into the metadata.
1595 // This pass is seeded off the reachability list calculated in the
1596 // middle::reachable module but filters out items that either don't have a
1597 // symbol associated with them (they weren't translated) or if they're an FFI
1598 // definition (as that's not defined in this crate).
1599 fn encode_exported_symbols(
1601 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1602 ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1603 // The metadata symbol name is special. It should not show up in
1604 // downstream crates.
1605 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1610 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1611 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1618 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1619 let formats = self.tcx.dependency_formats(LOCAL_CRATE);
1620 for (ty, arr) in formats.iter() {
1621 if *ty != CrateType::Dylib {
1624 return self.lazy(arr.iter().map(|slot| match *slot {
1625 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1627 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1628 Linkage::Static => Some(LinkagePreference::RequireStatic),
1634 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1637 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1639 record!(self.tables.kind[def_id] <- match nitem.kind {
1640 hir::ForeignItemKind::Fn(_, ref names, _) => {
1642 asyncness: hir::IsAsync::NotAsync,
1643 constness: if self.tcx.is_const_fn_raw(def_id) {
1644 hir::Constness::Const
1646 hir::Constness::NotConst
1648 param_names: self.encode_fn_param_names(names),
1650 EntryKind::ForeignFn(self.lazy(data))
1652 hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => EntryKind::ForeignMutStatic,
1653 hir::ForeignItemKind::Static(_, hir::Mutability::Not) => EntryKind::ForeignImmStatic,
1654 hir::ForeignItemKind::Type => EntryKind::ForeignType,
1656 record!(self.tables.visibility[def_id] <-
1657 ty::Visibility::from_hir(&nitem.vis, nitem.hir_id, self.tcx));
1658 record!(self.tables.span[def_id] <- nitem.span);
1659 record!(self.tables.attributes[def_id] <- nitem.attrs);
1660 self.encode_ident_span(def_id, nitem.ident);
1661 self.encode_stability(def_id);
1662 self.encode_const_stability(def_id);
1663 self.encode_deprecation(def_id);
1664 self.encode_item_type(def_id);
1665 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1666 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1667 self.encode_variances_of(def_id);
1669 self.encode_generics(def_id);
1670 self.encode_explicit_predicates(def_id);
1671 self.encode_inferred_outlives(def_id);
1675 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1676 impl Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1677 type Map = Map<'tcx>;
1679 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1680 NestedVisitorMap::OnlyBodies(self.tcx.hir())
1682 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1683 intravisit::walk_expr(self, ex);
1684 self.encode_info_for_expr(ex);
1686 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1687 intravisit::walk_anon_const(self, c);
1688 let def_id = self.tcx.hir().local_def_id(c.hir_id);
1689 self.encode_info_for_anon_const(def_id);
1691 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1692 intravisit::walk_item(self, item);
1693 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1695 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1696 _ => self.encode_info_for_item(def_id.to_def_id(), item),
1698 self.encode_addl_info_for_item(item);
1700 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1701 intravisit::walk_foreign_item(self, ni);
1702 let def_id = self.tcx.hir().local_def_id(ni.hir_id);
1703 self.encode_info_for_foreign_item(def_id.to_def_id(), ni);
1705 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1706 intravisit::walk_generics(self, generics);
1707 self.encode_info_for_generics(generics);
1709 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) {
1710 self.encode_info_for_macro_def(macro_def);
1714 impl EncodeContext<'a, 'tcx> {
1715 fn encode_fields(&mut self, adt_def: &ty::AdtDef) {
1716 for (variant_index, variant) in adt_def.variants.iter_enumerated() {
1717 for (field_index, _field) in variant.fields.iter().enumerate() {
1718 self.encode_field(adt_def, variant_index, field_index);
1723 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1724 for param in generics.params {
1725 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1727 GenericParamKind::Lifetime { .. } => continue,
1728 GenericParamKind::Type { ref default, .. } => {
1729 self.encode_info_for_generic_param(
1731 EntryKind::TypeParam,
1735 GenericParamKind::Const { .. } => {
1736 self.encode_info_for_generic_param(
1738 EntryKind::ConstParam,
1746 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1747 if let hir::ExprKind::Closure(..) = expr.kind {
1748 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1749 self.encode_info_for_closure(def_id);
1753 fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) {
1754 record!(self.tables.ident_span[def_id] <- ident.span);
1757 /// In some cases, along with the item itself, we also
1758 /// encode some sub-items. Usually we want some info from the item
1759 /// so it's easier to do that here then to wait until we would encounter
1760 /// normally in the visitor walk.
1761 fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1762 let def_id = self.tcx.hir().local_def_id(item.hir_id);
1764 hir::ItemKind::Static(..)
1765 | hir::ItemKind::Const(..)
1766 | hir::ItemKind::Fn(..)
1767 | hir::ItemKind::Mod(..)
1768 | hir::ItemKind::ForeignMod(..)
1769 | hir::ItemKind::GlobalAsm(..)
1770 | hir::ItemKind::ExternCrate(..)
1771 | hir::ItemKind::Use(..)
1772 | hir::ItemKind::TyAlias(..)
1773 | hir::ItemKind::OpaqueTy(..)
1774 | hir::ItemKind::TraitAlias(..) => {
1775 // no sub-item recording needed in these cases
1777 hir::ItemKind::Enum(..) => {
1778 let def = self.tcx.adt_def(def_id.to_def_id());
1779 self.encode_fields(def);
1781 for (i, variant) in def.variants.iter_enumerated() {
1782 self.encode_enum_variant_info(def, i);
1784 if let Some(_ctor_def_id) = variant.ctor_def_id {
1785 self.encode_enum_variant_ctor(def, i);
1789 hir::ItemKind::Struct(ref struct_def, _) => {
1790 let def = self.tcx.adt_def(def_id.to_def_id());
1791 self.encode_fields(def);
1793 // If the struct has a constructor, encode it.
1794 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1795 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1796 self.encode_struct_ctor(def, ctor_def_id.to_def_id());
1799 hir::ItemKind::Union(..) => {
1800 let def = self.tcx.adt_def(def_id.to_def_id());
1801 self.encode_fields(def);
1803 hir::ItemKind::Impl { .. } => {
1804 for &trait_item_def_id in
1805 self.tcx.associated_item_def_ids(def_id.to_def_id()).iter()
1807 self.encode_info_for_impl_item(trait_item_def_id);
1810 hir::ItemKind::Trait(..) => {
1811 for &item_def_id in self.tcx.associated_item_def_ids(def_id.to_def_id()).iter() {
1812 self.encode_info_for_trait_item(item_def_id);
1819 struct ImplVisitor<'tcx> {
1821 impls: FxHashMap<DefId, Vec<(DefIndex, Option<ty::fast_reject::SimplifiedType>)>>,
1824 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1825 fn visit_item(&mut self, item: &hir::Item<'_>) {
1826 if let hir::ItemKind::Impl { .. } = item.kind {
1827 let impl_id = self.tcx.hir().local_def_id(item.hir_id);
1828 if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id.to_def_id()) {
1829 let simplified_self_ty =
1830 ty::fast_reject::simplify_type(self.tcx, trait_ref.self_ty(), false);
1833 .entry(trait_ref.def_id)
1835 .push((impl_id.local_def_index, simplified_self_ty));
1840 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
1842 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
1843 // handled in `visit_item` above
1847 /// Used to prefetch queries which will be needed later by metadata encoding.
1848 /// Only a subset of the queries are actually prefetched to keep this code smaller.
1849 struct PrefetchVisitor<'tcx> {
1851 mir_keys: &'tcx FxHashSet<LocalDefId>,
1854 impl<'tcx> PrefetchVisitor<'tcx> {
1855 fn prefetch_mir(&self, def_id: LocalDefId) {
1856 if self.mir_keys.contains(&def_id) {
1857 self.tcx.ensure().optimized_mir(def_id);
1858 self.tcx.ensure().promoted_mir(def_id);
1863 impl<'tcx, 'v> ParItemLikeVisitor<'v> for PrefetchVisitor<'tcx> {
1864 fn visit_item(&self, item: &hir::Item<'_>) {
1865 // This should be kept in sync with `encode_info_for_item`.
1868 hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => {
1869 self.prefetch_mir(tcx.hir().local_def_id(item.hir_id))
1871 hir::ItemKind::Fn(ref sig, ..) => {
1872 let def_id = tcx.hir().local_def_id(item.hir_id);
1873 let generics = tcx.generics_of(def_id.to_def_id());
1874 let needs_inline = generics.requires_monomorphization(tcx)
1875 || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline();
1876 if needs_inline || sig.header.constness == hir::Constness::Const {
1877 self.prefetch_mir(def_id)
1884 fn visit_trait_item(&self, trait_item: &'v hir::TraitItem<'v>) {
1885 // This should be kept in sync with `encode_info_for_trait_item`.
1886 self.prefetch_mir(self.tcx.hir().local_def_id(trait_item.hir_id));
1889 fn visit_impl_item(&self, impl_item: &'v hir::ImplItem<'v>) {
1890 // This should be kept in sync with `encode_info_for_impl_item`.
1892 match impl_item.kind {
1893 hir::ImplItemKind::Const(..) => {
1894 self.prefetch_mir(tcx.hir().local_def_id(impl_item.hir_id))
1896 hir::ImplItemKind::Fn(ref sig, _) => {
1897 let def_id = tcx.hir().local_def_id(impl_item.hir_id);
1898 let generics = tcx.generics_of(def_id.to_def_id());
1899 let needs_inline = generics.requires_monomorphization(tcx)
1900 || tcx.codegen_fn_attrs(def_id.to_def_id()).requests_inline();
1901 let is_const_fn = sig.header.constness == hir::Constness::Const;
1902 if needs_inline || is_const_fn {
1903 self.prefetch_mir(def_id)
1906 hir::ImplItemKind::TyAlias(..) => (),
1911 // NOTE(eddyb) The following comment was preserved for posterity, even
1912 // though it's no longer relevant as EBML (which uses nested & tagged
1913 // "documents") was replaced with a scheme that can't go out of bounds.
1915 // And here we run into yet another obscure archive bug: in which metadata
1916 // loaded from archives may have trailing garbage bytes. Awhile back one of
1917 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
1918 // and opt) by having ebml generate an out-of-bounds panic when looking at
1921 // Upon investigation it turned out that the metadata file inside of an rlib
1922 // (and ar archive) was being corrupted. Some compilations would generate a
1923 // metadata file which would end in a few extra bytes, while other
1924 // compilations would not have these extra bytes appended to the end. These
1925 // extra bytes were interpreted by ebml as an extra tag, so they ended up
1926 // being interpreted causing the out-of-bounds.
1928 // The root cause of why these extra bytes were appearing was never
1929 // discovered, and in the meantime the solution we're employing is to insert
1930 // the length of the metadata to the start of the metadata. Later on this
1931 // will allow us to slice the metadata to the precise length that we just
1932 // generated regardless of trailing bytes that end up in it.
1934 pub(super) fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
1935 // Since encoding metadata is not in a query, and nothing is cached,
1936 // there's no need to do dep-graph tracking for any of it.
1937 tcx.dep_graph.assert_ignored();
1940 || encode_metadata_impl(tcx),
1942 if tcx.sess.threads() == 1 {
1945 // Prefetch some queries used by metadata encoding.
1946 // This is not necessary for correctness, but is only done for performance reasons.
1947 // It can be removed if it turns out to cause trouble or be detrimental to performance.
1950 if !tcx.sess.opts.output_types.should_codegen() {
1951 // We won't emit MIR, so don't prefetch it.
1954 tcx.hir().krate().par_visit_all_item_likes(&PrefetchVisitor {
1956 mir_keys: tcx.mir_keys(LOCAL_CRATE),
1959 || tcx.exported_symbols(LOCAL_CRATE),
1966 fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata {
1967 let mut encoder = opaque::Encoder::new(vec![]);
1968 encoder.emit_raw_bytes(METADATA_HEADER);
1970 // Will be filled with the root position after encoding everything.
1971 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
1973 let source_map_files = tcx.sess.source_map().files();
1974 let hygiene_ctxt = HygieneEncodeContext::default();
1976 let mut ecx = EncodeContext {
1979 tables: Default::default(),
1980 lazy_state: LazyState::NoNode,
1981 type_shorthands: Default::default(),
1982 predicate_shorthands: Default::default(),
1983 source_file_cache: (source_map_files[0].clone(), 0),
1984 interpret_allocs: Default::default(),
1985 required_source_files: Some(GrowableBitSet::with_capacity(source_map_files.len())),
1986 is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
1987 hygiene_ctxt: &hygiene_ctxt,
1989 drop(source_map_files);
1991 // Encode the rustc version string in a predictable location.
1992 rustc_version().encode(&mut ecx).unwrap();
1994 // Encode all the entries and extra information in the crate,
1995 // culminating in the `CrateRoot` which points to all of it.
1996 let root = ecx.encode_crate_root();
1998 let mut result = ecx.opaque.into_inner();
2000 // Encode the root position.
2001 let header = METADATA_HEADER.len();
2002 let pos = root.position.get();
2003 result[header + 0] = (pos >> 24) as u8;
2004 result[header + 1] = (pos >> 16) as u8;
2005 result[header + 2] = (pos >> 8) as u8;
2006 result[header + 3] = (pos >> 0) as u8;
2008 EncodedMetadata { raw_data: result }