1 use crate::rmeta::table::{FixedSizeEncoding, TableBuilder};
4 use rustc_data_structures::fingerprint::{Fingerprint, FingerprintEncoder};
5 use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
6 use rustc_data_structures::stable_hasher::StableHasher;
7 use rustc_data_structures::sync::{join, par_iter, Lrc, ParallelIterator};
9 use rustc_hir::def::{CtorOf, DefKind};
10 use rustc_hir::def_id::{
11 CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE,
13 use rustc_hir::definitions::DefPathData;
14 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
15 use rustc_hir::itemlikevisit::ItemLikeVisitor;
16 use rustc_hir::lang_items;
17 use rustc_hir::{AnonConst, GenericParamKind};
18 use rustc_index::bit_set::GrowableBitSet;
19 use rustc_index::vec::Idx;
20 use rustc_middle::hir::map::Map;
21 use rustc_middle::middle::cstore::{EncodedMetadata, ForeignModule, LinkagePreference, NativeLib};
22 use rustc_middle::middle::dependency_format::Linkage;
23 use rustc_middle::middle::exported_symbols::{
24 metadata_symbol_name, ExportedSymbol, SymbolExportLevel,
26 use rustc_middle::mir::interpret;
27 use rustc_middle::traits::specialization_graph;
28 use rustc_middle::ty::codec::TyEncoder;
29 use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
30 use rustc_serialize::{opaque, Encodable, Encoder};
31 use rustc_session::config::CrateType;
32 use rustc_span::hygiene::{ExpnDataEncodeMode, HygieneEncodeContext, MacroKind};
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,
44 feat: &'tcx rustc_feature::Features,
46 tables: TableBuilders<'tcx>,
48 lazy_state: LazyState,
49 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
50 predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
52 interpret_allocs: FxIndexSet<interpret::AllocId>,
54 // This is used to speed up Span encoding.
55 // The `usize` is an index into the `MonotonicVec`
56 // that stores the `SourceFile`
57 source_file_cache: (Lrc<SourceFile>, usize),
58 // The indices (into the `SourceMap`'s `MonotonicVec`)
59 // of all of the `SourceFiles` that we need to serialize.
60 // When we serialize a `Span`, we insert the index of its
61 // `SourceFile` into the `GrowableBitSet`.
63 // This needs to be a `GrowableBitSet` and not a
64 // regular `BitSet` because we may actually import new `SourceFiles`
65 // during metadata encoding, due to executing a query
66 // with a result containing a foreign `Span`.
67 required_source_files: Option<GrowableBitSet<usize>>,
69 hygiene_ctxt: &'a HygieneEncodeContext,
72 /// If the current crate is a proc-macro, returns early with `Lazy:empty()`.
73 /// This is useful for skipping the encoding of things that aren't needed
74 /// for proc-macro crates.
75 macro_rules! empty_proc_macro {
77 if $self.is_proc_macro {
83 macro_rules! encoder_methods {
84 ($($name:ident($ty:ty);)*) => {
85 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
86 self.opaque.$name(value)
91 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
92 type Error = <opaque::Encoder as Encoder>::Error;
95 fn emit_unit(&mut self) -> Result<(), Self::Error> {
122 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
125 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
126 e.emit_lazy_distance(*self)
130 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
133 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
134 e.emit_usize(self.meta)?;
138 e.emit_lazy_distance(*self)
142 impl<'a, 'tcx, I: Idx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
143 for Lazy<Table<I, T>>
145 Option<T>: FixedSizeEncoding,
147 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
148 e.emit_usize(self.meta)?;
149 e.emit_lazy_distance(*self)
153 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum {
154 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
155 if *self != LOCAL_CRATE && s.is_proc_macro {
156 panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self);
158 s.emit_u32(self.as_u32())
162 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex {
163 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
164 s.emit_u32(self.as_u32())
168 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
169 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
170 rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s)
174 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
175 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
176 rustc_span::hygiene::raw_encode_expn_id(
179 ExpnDataEncodeMode::Metadata,
185 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
186 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
187 if *self == rustc_span::DUMMY_SP {
188 return TAG_INVALID_SPAN.encode(s);
191 let span = self.data();
193 // The Span infrastructure should make sure that this invariant holds:
194 debug_assert!(span.lo <= span.hi);
196 if !s.source_file_cache.0.contains(span.lo) {
197 let source_map = s.tcx.sess.source_map();
198 let source_file_index = source_map.lookup_source_file_idx(span.lo);
199 s.source_file_cache =
200 (source_map.files()[source_file_index].clone(), source_file_index);
203 if !s.source_file_cache.0.contains(span.hi) {
204 // Unfortunately, macro expansion still sometimes generates Spans
205 // that malformed in this way.
206 return TAG_INVALID_SPAN.encode(s);
209 let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!");
210 // Record the fact that we need to encode the data for this `SourceFile`
211 source_files.insert(s.source_file_cache.1);
213 // There are two possible cases here:
214 // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
215 // crate we are writing metadata for. When the metadata for *this* crate gets
216 // deserialized, the deserializer will need to know which crate it originally came
217 // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
218 // be deserialized after the rest of the span data, which tells the deserializer
219 // which crate contains the source map information.
220 // 2. This span comes from our own crate. No special hamdling is needed - we just
221 // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
222 // our own source map information.
224 // If we're a proc-macro crate, we always treat this as a local `Span`.
225 // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
226 // if we're a proc-macro crate.
227 // This allows us to avoid loading the dependencies of proc-macro crates: all of
228 // the information we need to decode `Span`s is stored in the proc-macro crate.
229 let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro {
230 // To simplify deserialization, we 'rebase' this span onto the crate it originally came from
231 // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values
232 // are relative to the source map information for the 'foreign' crate whose CrateNum
233 // we write into the metadata. This allows `imported_source_files` to binary
234 // search through the 'foreign' crate's source map information, using the
235 // deserialized 'lo' and 'hi' values directly.
237 // All of this logic ensures that the final result of deserialization is a 'normal'
238 // Span that can be used without any additional trouble.
239 let external_start_pos = {
240 // Introduce a new scope so that we drop the 'lock()' temporary
241 match &*s.source_file_cache.0.external_src.lock() {
242 ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos,
243 src => panic!("Unexpected external source {:?}", src),
246 let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos;
247 let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos;
249 (TAG_VALID_SPAN_FOREIGN, lo, hi)
251 (TAG_VALID_SPAN_LOCAL, span.lo, span.hi)
257 // Encode length which is usually less than span.hi and profits more
258 // from the variable-length integer encoding that we use.
262 // Don't serialize any `SyntaxContext`s from a proc-macro crate,
263 // since we don't load proc-macro dependencies during serialization.
264 // This means that any hygiene information from macros used *within*
265 // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
266 // definition) will be lost.
268 // This can show up in two ways:
270 // 1. Any hygiene information associated with identifier of
271 // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
272 // Since proc-macros can only be invoked from a different crate,
273 // real code should never need to care about this.
275 // 2. Using `Span::def_site` or `Span::mixed_site` will not
276 // include any hygiene information associated with the definition
277 // site. This means that a proc-macro cannot emit a `$crate`
278 // identifier which resolves to one of its dependencies,
279 // which also should never come up in practice.
281 // Additionally, this affects `Span::parent`, and any other
282 // span inspection APIs that would otherwise allow traversing
283 // the `SyntaxContexts` associated with a span.
285 // None of these user-visible effects should result in any
286 // cross-crate inconsistencies (getting one behavior in the same
287 // crate, and a different behavior in another crate) due to the
288 // limited surface that proc-macros can expose.
290 // IMPORTANT: If this is ever changed, be sure to update
291 // `rustc_span::hygiene::raw_encode_expn_id` to handle
292 // encoding `ExpnData` for proc-macro crates.
294 SyntaxContext::root().encode(s)?;
296 span.ctxt.encode(s)?;
299 if tag == TAG_VALID_SPAN_FOREIGN {
300 // This needs to be two lines to avoid holding the `s.source_file_cache`
301 // while calling `cnum.encode(s)`
302 let cnum = s.source_file_cache.0.cnum;
310 impl<'a, 'tcx> FingerprintEncoder for EncodeContext<'a, 'tcx> {
311 fn encode_fingerprint(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
312 self.opaque.encode_fingerprint(f)
316 impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
317 const CLEAR_CROSS_CRATE: bool = true;
319 fn position(&self) -> usize {
320 self.opaque.position()
323 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
324 &mut self.type_shorthands
327 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
328 &mut self.predicate_shorthands
333 alloc_id: &rustc_middle::mir::interpret::AllocId,
334 ) -> Result<(), Self::Error> {
335 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
341 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [mir::abstract_const::Node<'tcx>] {
342 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
347 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
348 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
353 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
354 trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> {
355 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta;
358 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for &T {
359 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
360 self.encode(ecx).unwrap()
364 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for T {
365 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
366 self.encode(ecx).unwrap()
370 impl<'a, 'tcx, I, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, [T]> for I
373 I::Item: EncodeContentsForLazy<'a, 'tcx, T>,
375 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize {
376 self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
380 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would
381 // normally need extra variables to avoid errors about multiple mutable borrows.
382 macro_rules! record {
383 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
386 let lazy = $self.lazy(value);
387 $self.$tables.$table.set($def_id.index, lazy);
392 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
393 fn emit_lazy_distance<T: ?Sized + LazyMeta>(
396 ) -> Result<(), <Self as Encoder>::Error> {
397 let min_end = lazy.position.get() + T::min_size(lazy.meta);
398 let distance = match self.lazy_state {
399 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
400 LazyState::NodeStart(start) => {
401 let start = start.get();
402 assert!(min_end <= start);
405 LazyState::Previous(last_min_end) => {
407 last_min_end <= lazy.position,
408 "make sure that the calls to `lazy*` \
409 are in the same order as the metadata fields",
411 lazy.position.get() - last_min_end.get()
414 self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap());
415 self.emit_usize(distance)
418 fn lazy<T: ?Sized + LazyMeta>(
420 value: impl EncodeContentsForLazy<'a, 'tcx, T>,
422 let pos = NonZeroUsize::new(self.position()).unwrap();
424 assert_eq!(self.lazy_state, LazyState::NoNode);
425 self.lazy_state = LazyState::NodeStart(pos);
426 let meta = value.encode_contents_for_lazy(self);
427 self.lazy_state = LazyState::NoNode;
429 assert!(pos.get() + <T>::min_size(meta) <= self.position());
431 Lazy::from_position_and_meta(pos, meta)
434 fn encode_info_for_items(&mut self) {
435 let krate = self.tcx.hir().krate();
436 self.encode_info_for_mod(CRATE_DEF_ID, &krate.item.module);
438 // Proc-macro crates only export proc-macro items, which are looked
439 // up using `proc_macro_data`
440 if self.is_proc_macro {
444 krate.visit_all_item_likes(&mut self.as_deep_visitor());
445 for macro_def in krate.exported_macros {
446 self.visit_macro_def(macro_def);
450 fn encode_def_path_table(&mut self) {
451 let table = self.tcx.hir().definitions().def_path_table();
452 if self.is_proc_macro {
453 for def_index in std::iter::once(CRATE_DEF_INDEX)
454 .chain(self.tcx.hir().krate().proc_macros.iter().map(|p| p.owner.local_def_index))
456 let def_key = self.lazy(table.def_key(def_index));
457 let def_path_hash = self.lazy(table.def_path_hash(def_index));
458 self.tables.def_keys.set(def_index, def_key);
459 self.tables.def_path_hashes.set(def_index, def_path_hash);
462 for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
463 let def_key = self.lazy(def_key);
464 let def_path_hash = self.lazy(def_path_hash);
465 self.tables.def_keys.set(def_index, def_key);
466 self.tables.def_path_hashes.set(def_index, def_path_hash);
471 fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> {
472 let source_map = self.tcx.sess.source_map();
473 let all_source_files = source_map.files();
475 let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
476 // By replacing the `Option` with `None`, we ensure that we can't
477 // accidentally serialize any more `Span`s after the source map encoding
479 let required_source_files = self.required_source_files.take().unwrap();
481 let adapted = all_source_files
484 .filter(|(idx, source_file)| {
485 // Only serialize `SourceFile`s that were used
486 // during the encoding of a `Span`
487 required_source_files.contains(*idx) &&
488 // Don't serialize imported `SourceFile`s, unless
489 // we're in a proc-macro crate.
490 (!source_file.is_imported() || self.is_proc_macro)
492 .map(|(_, source_file)| {
493 let mut adapted = match source_file.name {
494 // This path of this SourceFile has been modified by
495 // path-remapping, so we use it verbatim (and avoid
496 // cloning the whole map in the process).
497 _ if source_file.name_was_remapped => source_file.clone(),
499 // Otherwise expand all paths to absolute paths because
500 // any relative paths are potentially relative to a
502 FileName::Real(ref name) => {
503 let name = name.stable_name();
504 let mut adapted = (**source_file).clone();
505 adapted.name = Path::new(&working_dir).join(name).into();
506 adapted.name_hash = {
507 let mut hasher: StableHasher = StableHasher::new();
508 adapted.name.hash(&mut hasher);
509 hasher.finish::<u128>()
514 // expanded code, not from a file
515 _ => source_file.clone(),
518 // We're serializing this `SourceFile` into our crate metadata,
519 // so mark it as coming from this crate.
520 // This also ensures that we don't try to deserialize the
521 // `CrateNum` for a proc-macro dependency - since proc macro
522 // dependencies aren't loaded when we deserialize a proc-macro,
523 // trying to remap the `CrateNum` would fail.
524 if self.is_proc_macro {
525 Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE;
529 .collect::<Vec<_>>();
531 self.lazy(adapted.iter().map(|rc| &**rc))
534 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
535 let mut i = self.position();
537 // Encode the crate deps
538 let crate_deps = self.encode_crate_deps();
539 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
540 let dep_bytes = self.position() - i;
542 // Encode the lib features.
544 let lib_features = self.encode_lib_features();
545 let lib_feature_bytes = self.position() - i;
547 // Encode the language items.
549 let lang_items = self.encode_lang_items();
550 let lang_items_missing = self.encode_lang_items_missing();
551 let lang_item_bytes = self.position() - i;
553 // Encode the diagnostic items.
555 let diagnostic_items = self.encode_diagnostic_items();
556 let diagnostic_item_bytes = self.position() - i;
558 // Encode the native libraries used
560 let native_libraries = self.encode_native_libraries();
561 let native_lib_bytes = self.position() - i;
563 let foreign_modules = self.encode_foreign_modules();
565 // Encode DefPathTable
567 self.encode_def_path_table();
568 let def_path_table_bytes = self.position() - i;
570 // Encode the def IDs of impls, for coherence checking.
572 let impls = self.encode_impls();
573 let impl_bytes = self.position() - i;
580 let mir_bytes = self.position() - i;
584 self.encode_def_ids();
585 self.encode_info_for_items();
586 let item_bytes = self.position() - i;
588 // Encode the allocation index
589 let interpret_alloc_index = {
590 let mut interpret_alloc_index = Vec::new();
592 trace!("beginning to encode alloc ids");
594 let new_n = self.interpret_allocs.len();
595 // if we have found new ids, serialize those, too
600 trace!("encoding {} further alloc ids", new_n - n);
601 for idx in n..new_n {
602 let id = self.interpret_allocs[idx];
603 let pos = self.position() as u32;
604 interpret_alloc_index.push(pos);
605 interpret::specialized_encode_alloc_id(self, tcx, id).unwrap();
609 self.lazy(interpret_alloc_index)
612 // Encode the proc macro data. This affects 'tables',
613 // so we need to do this before we encode the tables
615 let proc_macro_data = self.encode_proc_macros();
616 let proc_macro_data_bytes = self.position() - i;
619 let tables = self.tables.encode(&mut self.opaque);
620 let tables_bytes = self.position() - i;
622 // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
623 // this as late as possible to give the prefetching as much time as possible to complete.
625 let exported_symbols = tcx.exported_symbols(LOCAL_CRATE);
626 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
627 let exported_symbols_bytes = self.position() - i;
629 // Encode the hygiene data,
630 // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process
631 // of encoding other items (e.g. `optimized_mir`) may cause us to load
632 // data from the incremental cache. If this causes us to deserialize a `Span`,
633 // then we may load additional `SyntaxContext`s into the global `HygieneData`.
634 // Therefore, we need to encode the hygiene data last to ensure that we encode
635 // any `SyntaxContext`s that might be used.
637 let (syntax_contexts, expn_data) = self.encode_hygiene();
638 let hygiene_bytes = self.position() - i;
640 // Encode source_map. This needs to be done last,
641 // since encoding `Span`s tells us which `SourceFiles` we actually
644 let source_map = self.encode_source_map();
645 let source_map_bytes = self.position() - i;
647 let attrs = tcx.hir().krate_attrs();
648 let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator);
650 let root = self.lazy(CrateRoot {
651 name: tcx.crate_name(LOCAL_CRATE),
652 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
653 triple: tcx.sess.opts.target_triple.clone(),
654 hash: tcx.crate_hash(LOCAL_CRATE),
655 disambiguator: tcx.sess.local_crate_disambiguator(),
656 panic_strategy: tcx.sess.panic_strategy(),
657 edition: tcx.sess.edition(),
658 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
659 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
660 has_default_lib_allocator,
661 plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
663 compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
664 needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
665 needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
666 no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
667 panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
668 profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
669 symbol_mangling_version: tcx.sess.opts.debugging_opts.get_symbol_mangling_version(),
672 dylib_dependency_formats,
682 interpret_alloc_index,
688 let total_bytes = self.position();
690 if tcx.sess.meta_stats() {
691 let mut zero_bytes = 0;
692 for e in self.opaque.data.iter() {
698 eprintln!("metadata stats:");
699 eprintln!(" dep bytes: {}", dep_bytes);
700 eprintln!(" lib feature bytes: {}", lib_feature_bytes);
701 eprintln!(" lang item bytes: {}", lang_item_bytes);
702 eprintln!(" diagnostic item bytes: {}", diagnostic_item_bytes);
703 eprintln!(" native bytes: {}", native_lib_bytes);
704 eprintln!(" source_map bytes: {}", source_map_bytes);
705 eprintln!(" impl bytes: {}", impl_bytes);
706 eprintln!(" exp. symbols bytes: {}", exported_symbols_bytes);
707 eprintln!(" def-path table bytes: {}", def_path_table_bytes);
708 eprintln!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
709 eprintln!(" mir bytes: {}", mir_bytes);
710 eprintln!(" item bytes: {}", item_bytes);
711 eprintln!(" table bytes: {}", tables_bytes);
712 eprintln!(" hygiene bytes: {}", hygiene_bytes);
713 eprintln!(" zero bytes: {}", zero_bytes);
714 eprintln!(" total bytes: {}", total_bytes);
721 fn should_encode_visibility(def_kind: DefKind) -> bool {
731 | DefKind::TraitAlias
738 | DefKind::AssocConst
741 | DefKind::ForeignMod
744 | DefKind::Field => true,
746 | DefKind::ConstParam
747 | DefKind::LifetimeParam
752 | DefKind::ExternCrate => false,
756 fn should_encode_stability(def_kind: DefKind) -> bool {
765 | DefKind::AssocConst
767 | DefKind::ConstParam
771 | DefKind::ForeignMod
778 | DefKind::TraitAlias
780 | DefKind::ForeignTy => true,
782 | DefKind::LifetimeParam
787 | DefKind::ExternCrate => false,
791 /// Whether we should encode MIR.
793 /// Computing, optimizing and encoding the MIR is a relatively expensive operation.
794 /// We want to avoid this work when not required. Therefore:
795 /// - we only compute `mir_for_ctfe` on items with const-eval semantics;
796 /// - we skip `optimized_mir` for check runs.
798 /// Return a pair, resp. for CTFE and for LLVM.
799 fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) {
800 match tcx.def_kind(def_id) {
802 DefKind::Ctor(_, _) => {
803 let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
804 || tcx.sess.opts.debugging_opts.always_encode_mir;
808 DefKind::AnonConst | DefKind::AssocConst | DefKind::Static | DefKind::Const => {
811 // Full-fledged functions
812 DefKind::AssocFn | DefKind::Fn => {
813 let generics = tcx.generics_of(def_id);
814 let needs_inline = (generics.requires_monomorphization(tcx)
815 || tcx.codegen_fn_attrs(def_id).requests_inline())
816 && tcx.sess.opts.output_types.should_codegen();
817 // Only check the presence of the `const` modifier.
818 let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id());
819 let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir;
820 (is_const_fn, needs_inline || always_encode_mir)
822 // Closures can't be const fn.
823 DefKind::Closure => {
824 let generics = tcx.generics_of(def_id);
825 let needs_inline = (generics.requires_monomorphization(tcx)
826 || tcx.codegen_fn_attrs(def_id).requests_inline())
827 && tcx.sess.opts.output_types.should_codegen();
828 let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir;
829 (false, needs_inline || always_encode_mir)
831 // Generators require optimized MIR to compute layout.
832 DefKind::Generator => (false, true),
833 // The others don't have MIR.
838 impl EncodeContext<'a, 'tcx> {
839 fn encode_def_ids(&mut self) {
840 if self.is_proc_macro {
845 for local_id in hir.iter_local_def_id() {
846 let def_id = local_id.to_def_id();
847 let def_kind = tcx.opt_def_kind(local_id);
848 let def_kind = if let Some(def_kind) = def_kind { def_kind } else { continue };
849 record!(self.tables.def_kind[def_id] <- match def_kind {
850 // Replace Ctor by the enclosing object to avoid leaking details in children crates.
851 DefKind::Ctor(CtorOf::Struct, _) => DefKind::Struct,
852 DefKind::Ctor(CtorOf::Variant, _) => DefKind::Variant,
853 def_kind => def_kind,
855 record!(self.tables.span[def_id] <- tcx.def_span(def_id));
856 record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id));
857 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expansion_that_defined(def_id));
858 if should_encode_visibility(def_kind) {
859 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
861 if should_encode_stability(def_kind) {
862 self.encode_stability(def_id);
863 self.encode_const_stability(def_id);
864 self.encode_deprecation(def_id);
869 fn encode_variances_of(&mut self, def_id: DefId) {
870 debug!("EncodeContext::encode_variances_of({:?})", def_id);
871 record!(self.tables.variances[def_id] <- self.tcx.variances_of(def_id));
874 fn encode_item_type(&mut self, def_id: DefId) {
875 debug!("EncodeContext::encode_item_type({:?})", def_id);
876 record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id));
879 fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) {
881 let variant = &def.variants[index];
882 let def_id = variant.def_id;
883 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
885 let data = VariantData {
886 ctor_kind: variant.ctor_kind,
887 discr: variant.discr,
888 ctor: variant.ctor_def_id.map(|did| did.index),
889 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
892 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
893 record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
894 assert!(f.did.is_local());
897 self.encode_ident_span(def_id, variant.ident);
898 self.encode_item_type(def_id);
899 if variant.ctor_kind == CtorKind::Fn {
900 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
901 if let Some(ctor_def_id) = variant.ctor_def_id {
902 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
904 // FIXME(eddyb) is this ever used?
905 self.encode_variances_of(def_id);
907 self.encode_generics(def_id);
908 self.encode_explicit_predicates(def_id);
909 self.encode_inferred_outlives(def_id);
912 fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) {
914 let variant = &def.variants[index];
915 let def_id = variant.ctor_def_id.unwrap();
916 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
918 // FIXME(eddyb) encode only the `CtorKind` for constructors.
919 let data = VariantData {
920 ctor_kind: variant.ctor_kind,
921 discr: variant.discr,
922 ctor: Some(def_id.index),
923 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
926 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
927 self.encode_item_type(def_id);
928 if variant.ctor_kind == CtorKind::Fn {
929 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
930 self.encode_variances_of(def_id);
932 self.encode_generics(def_id);
933 self.encode_explicit_predicates(def_id);
934 self.encode_inferred_outlives(def_id);
937 fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) {
939 let def_id = local_def_id.to_def_id();
940 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
942 // If we are encoding a proc-macro crates, `encode_info_for_mod` will
943 // only ever get called for the crate root. We still want to encode
944 // the crate root for consistency with other crates (some of the resolver
945 // code uses it). However, we skip encoding anything relating to child
946 // items - we encode information about proc-macros later on.
947 let reexports = if !self.is_proc_macro {
948 match tcx.module_exports(local_def_id) {
950 let hir = self.tcx.hir();
954 .map(|export| export.map_id(|id| hir.local_def_id_to_hir_id(id))),
965 expansion: tcx.hir().definitions().expansion_that_defined(local_def_id),
968 record!(self.tables.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
969 if self.is_proc_macro {
970 record!(self.tables.children[def_id] <- &[]);
972 record!(self.tables.children[def_id] <- md.item_ids.iter().map(|item_id| {
973 item_id.def_id.local_def_index
980 adt_def: &ty::AdtDef,
981 variant_index: VariantIdx,
984 let variant = &adt_def.variants[variant_index];
985 let field = &variant.fields[field_index];
987 let def_id = field.did;
988 debug!("EncodeContext::encode_field({:?})", def_id);
990 record!(self.tables.kind[def_id] <- EntryKind::Field);
991 self.encode_ident_span(def_id, field.ident);
992 self.encode_item_type(def_id);
993 self.encode_generics(def_id);
994 self.encode_explicit_predicates(def_id);
995 self.encode_inferred_outlives(def_id);
998 fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) {
999 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
1001 let variant = adt_def.non_enum_variant();
1003 let data = VariantData {
1004 ctor_kind: variant.ctor_kind,
1005 discr: variant.discr,
1006 ctor: Some(def_id.index),
1007 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1010 record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
1011 self.encode_item_type(def_id);
1012 if variant.ctor_kind == CtorKind::Fn {
1013 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1014 self.encode_variances_of(def_id);
1016 self.encode_generics(def_id);
1017 self.encode_explicit_predicates(def_id);
1018 self.encode_inferred_outlives(def_id);
1021 fn encode_generics(&mut self, def_id: DefId) {
1022 debug!("EncodeContext::encode_generics({:?})", def_id);
1023 record!(self.tables.generics[def_id] <- self.tcx.generics_of(def_id));
1026 fn encode_explicit_predicates(&mut self, def_id: DefId) {
1027 debug!("EncodeContext::encode_explicit_predicates({:?})", def_id);
1028 record!(self.tables.explicit_predicates[def_id] <-
1029 self.tcx.explicit_predicates_of(def_id));
1032 fn encode_inferred_outlives(&mut self, def_id: DefId) {
1033 debug!("EncodeContext::encode_inferred_outlives({:?})", def_id);
1034 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1035 if !inferred_outlives.is_empty() {
1036 record!(self.tables.inferred_outlives[def_id] <- inferred_outlives);
1040 fn encode_super_predicates(&mut self, def_id: DefId) {
1041 debug!("EncodeContext::encode_super_predicates({:?})", def_id);
1042 record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
1045 fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1046 debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1047 let bounds = self.tcx.explicit_item_bounds(def_id);
1048 if !bounds.is_empty() {
1049 record!(self.tables.explicit_item_bounds[def_id] <- bounds);
1053 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
1054 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
1057 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1058 let ast_item = tcx.hir().expect_trait_item(hir_id);
1059 let trait_item = tcx.associated_item(def_id);
1061 let container = match trait_item.defaultness {
1062 hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
1063 hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
1064 hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
1067 match trait_item.kind {
1068 ty::AssocKind::Const => {
1069 let rendered = rustc_hir_pretty::to_string(
1070 &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
1071 |s| s.print_trait_item(ast_item),
1073 let rendered_const = self.lazy(RenderedConst(rendered));
1075 record!(self.tables.kind[def_id] <- EntryKind::AssocConst(
1081 ty::AssocKind::Fn => {
1082 let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind {
1083 let param_names = match *m {
1084 hir::TraitFn::Required(ref names) => self.encode_fn_param_names(names),
1085 hir::TraitFn::Provided(body) => self.encode_fn_param_names_for_body(body),
1088 asyncness: m_sig.header.asyncness,
1089 constness: hir::Constness::NotConst,
1095 record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData {
1098 has_self: trait_item.fn_has_self_parameter,
1101 ty::AssocKind::Type => {
1102 self.encode_explicit_item_bounds(def_id);
1103 record!(self.tables.kind[def_id] <- EntryKind::AssocType(container));
1106 self.encode_ident_span(def_id, ast_item.ident);
1107 match trait_item.kind {
1108 ty::AssocKind::Const | ty::AssocKind::Fn => {
1109 self.encode_item_type(def_id);
1111 ty::AssocKind::Type => {
1112 if trait_item.defaultness.has_value() {
1113 self.encode_item_type(def_id);
1117 if trait_item.kind == ty::AssocKind::Fn {
1118 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1119 self.encode_variances_of(def_id);
1121 self.encode_generics(def_id);
1122 self.encode_explicit_predicates(def_id);
1123 self.encode_inferred_outlives(def_id);
1126 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1127 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1130 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1131 let ast_item = self.tcx.hir().expect_impl_item(hir_id);
1132 let impl_item = self.tcx.associated_item(def_id);
1134 let container = match impl_item.defaultness {
1135 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
1136 hir::Defaultness::Final => AssocContainer::ImplFinal,
1137 hir::Defaultness::Default { has_value: false } => {
1138 span_bug!(ast_item.span, "impl items always have values (currently)")
1142 match impl_item.kind {
1143 ty::AssocKind::Const => {
1144 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1145 let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1147 record!(self.tables.kind[def_id] <- EntryKind::AssocConst(
1150 self.encode_rendered_const_for_body(body_id))
1156 ty::AssocKind::Fn => {
1157 let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind {
1159 asyncness: sig.header.asyncness,
1160 constness: sig.header.constness,
1161 param_names: self.encode_fn_param_names_for_body(body),
1166 record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData {
1169 has_self: impl_item.fn_has_self_parameter,
1172 ty::AssocKind::Type => {
1173 record!(self.tables.kind[def_id] <- EntryKind::AssocType(container));
1176 self.encode_ident_span(def_id, impl_item.ident);
1177 self.encode_item_type(def_id);
1178 if impl_item.kind == ty::AssocKind::Fn {
1179 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1180 self.encode_variances_of(def_id);
1182 self.encode_generics(def_id);
1183 self.encode_explicit_predicates(def_id);
1184 self.encode_inferred_outlives(def_id);
1187 fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> {
1188 self.lazy(self.tcx.hir().body_param_names(body_id))
1191 fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> {
1192 self.lazy(param_names.iter())
1195 fn encode_mir(&mut self) {
1196 if self.is_proc_macro {
1200 let mut keys_and_jobs = self
1202 .mir_keys(LOCAL_CRATE)
1204 .filter_map(|&def_id| {
1205 let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id);
1206 if encode_const || encode_opt {
1207 Some((def_id, encode_const, encode_opt))
1212 .collect::<Vec<_>>();
1213 // Sort everything to ensure a stable order for diagnotics.
1214 keys_and_jobs.sort_by_key(|&(def_id, _, _)| def_id);
1215 for (def_id, encode_const, encode_opt) in keys_and_jobs.into_iter() {
1216 debug_assert!(encode_const || encode_opt);
1218 debug!("EntryBuilder::encode_mir({:?})", def_id);
1220 record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1223 record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id));
1225 let abstract_const = self.tcx.mir_abstract_const(def_id);
1226 if let Ok(Some(abstract_const)) = abstract_const {
1227 record!(self.tables.mir_abstract_consts[def_id.to_def_id()] <- abstract_const);
1230 record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1232 let unused = self.tcx.unused_generic_params(def_id);
1233 if !unused.is_empty() {
1234 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1239 // Encodes the inherent implementations of a structure, enumeration, or trait.
1240 fn encode_inherent_implementations(&mut self, def_id: DefId) {
1241 debug!("EncodeContext::encode_inherent_implementations({:?})", def_id);
1242 let implementations = self.tcx.inherent_impls(def_id);
1243 if !implementations.is_empty() {
1244 record!(self.tables.inherent_impls[def_id] <- implementations.iter().map(|&def_id| {
1245 assert!(def_id.is_local());
1251 fn encode_stability(&mut self, def_id: DefId) {
1252 debug!("EncodeContext::encode_stability({:?})", def_id);
1254 // The query lookup can take a measurable amount of time in crates with many items. Check if
1255 // the stability attributes are even enabled before using their queries.
1256 if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1257 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1258 record!(self.tables.stability[def_id] <- stab)
1263 fn encode_const_stability(&mut self, def_id: DefId) {
1264 debug!("EncodeContext::encode_const_stability({:?})", def_id);
1266 // The query lookup can take a measurable amount of time in crates with many items. Check if
1267 // the stability attributes are even enabled before using their queries.
1268 if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1269 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1270 record!(self.tables.const_stability[def_id] <- stab)
1275 fn encode_deprecation(&mut self, def_id: DefId) {
1276 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1277 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1278 record!(self.tables.deprecation[def_id] <- depr);
1282 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> {
1283 let hir = self.tcx.hir();
1284 let body = hir.body(body_id);
1285 let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1286 s.print_expr(&body.value)
1288 let rendered_const = &RenderedConst(rendered);
1289 self.lazy(rendered_const)
1292 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1295 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1297 self.encode_ident_span(def_id, item.ident);
1299 let entry_kind = match item.kind {
1300 hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic,
1301 hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic,
1302 hir::ItemKind::Const(_, body_id) => {
1303 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1304 EntryKind::Const(qualifs, self.encode_rendered_const_for_body(body_id))
1306 hir::ItemKind::Fn(ref sig, .., body) => {
1308 asyncness: sig.header.asyncness,
1309 constness: sig.header.constness,
1310 param_names: self.encode_fn_param_names_for_body(body),
1313 EntryKind::Fn(self.lazy(data))
1315 hir::ItemKind::Mod(ref m) => {
1316 return self.encode_info_for_mod(item.def_id, m);
1318 hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod,
1319 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1320 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1321 hir::ItemKind::OpaqueTy(..) => {
1322 self.encode_explicit_item_bounds(def_id);
1325 hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr),
1326 hir::ItemKind::Struct(ref struct_def, _) => {
1327 let adt_def = self.tcx.adt_def(def_id);
1328 let variant = adt_def.non_enum_variant();
1330 // Encode def_ids for each field and method
1331 // for methods, write all the stuff get_trait_method
1333 let ctor = struct_def
1335 .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index);
1338 self.lazy(VariantData {
1339 ctor_kind: variant.ctor_kind,
1340 discr: variant.discr,
1342 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1347 hir::ItemKind::Union(..) => {
1348 let adt_def = self.tcx.adt_def(def_id);
1349 let variant = adt_def.non_enum_variant();
1352 self.lazy(VariantData {
1353 ctor_kind: variant.ctor_kind,
1354 discr: variant.discr,
1356 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1361 hir::ItemKind::Impl(hir::Impl { defaultness, .. }) => {
1362 let trait_ref = self.tcx.impl_trait_ref(def_id);
1363 let polarity = self.tcx.impl_polarity(def_id);
1364 let parent = if let Some(trait_ref) = trait_ref {
1365 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1366 trait_def.ancestors(self.tcx, def_id).ok().and_then(|mut an| {
1367 an.nth(1).and_then(|node| match node {
1368 specialization_graph::Node::Impl(parent) => Some(parent),
1376 // if this is an impl of `CoerceUnsized`, create its
1377 // "unsized info", else just store None
1378 let coerce_unsized_info = trait_ref.and_then(|t| {
1379 if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1380 Some(self.tcx.at(item.span).coerce_unsized_info(def_id))
1387 ImplData { polarity, defaultness, parent_impl: parent, coerce_unsized_info };
1389 EntryKind::Impl(self.lazy(data))
1391 hir::ItemKind::Trait(..) => {
1392 let trait_def = self.tcx.trait_def(def_id);
1393 let data = TraitData {
1394 unsafety: trait_def.unsafety,
1395 paren_sugar: trait_def.paren_sugar,
1396 has_auto_impl: self.tcx.trait_is_auto(def_id),
1397 is_marker: trait_def.is_marker,
1398 specialization_kind: trait_def.specialization_kind,
1401 EntryKind::Trait(self.lazy(data))
1403 hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias,
1404 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {
1405 bug!("cannot encode info for item {:?}", item)
1408 record!(self.tables.kind[def_id] <- entry_kind);
1409 // FIXME(eddyb) there should be a nicer way to do this.
1411 hir::ItemKind::ForeignMod { items, .. } => record!(self.tables.children[def_id] <-
1414 .map(|foreign_item| foreign_item.id.def_id.local_def_index)
1416 hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <-
1417 self.tcx.adt_def(def_id).variants.iter().map(|v| {
1418 assert!(v.def_id.is_local());
1422 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1423 record!(self.tables.children[def_id] <-
1424 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1425 assert!(f.did.is_local());
1430 hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1431 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1432 record!(self.tables.children[def_id] <-
1433 associated_item_def_ids.iter().map(|&def_id| {
1434 assert!(def_id.is_local());
1442 hir::ItemKind::Static(..)
1443 | hir::ItemKind::Const(..)
1444 | hir::ItemKind::Fn(..)
1445 | hir::ItemKind::TyAlias(..)
1446 | hir::ItemKind::OpaqueTy(..)
1447 | hir::ItemKind::Enum(..)
1448 | hir::ItemKind::Struct(..)
1449 | hir::ItemKind::Union(..)
1450 | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1453 if let hir::ItemKind::Fn(..) = item.kind {
1454 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1456 if let hir::ItemKind::Impl { .. } = item.kind {
1457 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1458 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1461 self.encode_inherent_implementations(def_id);
1463 hir::ItemKind::Enum(..)
1464 | hir::ItemKind::Struct(..)
1465 | hir::ItemKind::Union(..)
1466 | hir::ItemKind::Fn(..) => self.encode_variances_of(def_id),
1470 hir::ItemKind::Static(..)
1471 | hir::ItemKind::Const(..)
1472 | hir::ItemKind::Fn(..)
1473 | hir::ItemKind::TyAlias(..)
1474 | hir::ItemKind::Enum(..)
1475 | hir::ItemKind::Struct(..)
1476 | hir::ItemKind::Union(..)
1477 | hir::ItemKind::Impl { .. }
1478 | hir::ItemKind::OpaqueTy(..)
1479 | hir::ItemKind::Trait(..)
1480 | hir::ItemKind::TraitAlias(..) => {
1481 self.encode_generics(def_id);
1482 self.encode_explicit_predicates(def_id);
1483 self.encode_inferred_outlives(def_id);
1488 hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => {
1489 self.encode_super_predicates(def_id);
1495 /// Serialize the text of exported macros
1496 fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef<'_>) {
1497 let def_id = macro_def.def_id.to_def_id();
1498 record!(self.tables.kind[def_id] <- EntryKind::MacroDef(self.lazy(macro_def.ast.clone())));
1499 self.encode_ident_span(def_id, macro_def.ident);
1502 fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1503 record!(self.tables.kind[def_id] <- kind);
1505 self.encode_item_type(def_id);
1509 fn encode_info_for_closure(&mut self, def_id: LocalDefId) {
1510 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1512 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1513 // including on the signature, which is inferred in `typeck.
1514 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1515 let ty = self.tcx.typeck(def_id).node_type(hir_id);
1518 ty::Generator(..) => {
1519 let data = self.tcx.generator_kind(def_id).unwrap();
1520 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Generator(data));
1523 ty::Closure(..) => {
1524 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Closure);
1527 _ => bug!("closure that is neither generator nor closure"),
1529 self.encode_item_type(def_id.to_def_id());
1530 if let ty::Closure(def_id, substs) = *ty.kind() {
1531 record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1533 self.encode_generics(def_id.to_def_id());
1536 fn encode_info_for_anon_const(&mut self, def_id: LocalDefId) {
1537 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1538 let id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1539 let body_id = self.tcx.hir().body_owned_by(id);
1540 let const_data = self.encode_rendered_const_for_body(body_id);
1541 let qualifs = self.tcx.mir_const_qualif(def_id);
1543 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data));
1544 self.encode_item_type(def_id.to_def_id());
1545 self.encode_generics(def_id.to_def_id());
1546 self.encode_explicit_predicates(def_id.to_def_id());
1547 self.encode_inferred_outlives(def_id.to_def_id());
1550 fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
1551 empty_proc_macro!(self);
1552 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1553 self.lazy(used_libraries.iter().cloned())
1556 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1557 empty_proc_macro!(self);
1558 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1559 self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned())
1562 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable) {
1563 let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1564 let mut expn_data_table: TableBuilder<_, _> = Default::default();
1566 let _: Result<(), !> = self.hygiene_ctxt.encode(
1567 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table),
1568 |(this, syntax_contexts, _), index, ctxt_data| {
1569 syntax_contexts.set(index, this.lazy(ctxt_data));
1572 |(this, _, expn_data_table), index, expn_data| {
1573 expn_data_table.set(index, this.lazy(expn_data));
1578 (syntax_contexts.encode(&mut self.opaque), expn_data_table.encode(&mut self.opaque))
1581 fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1582 let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1585 let hir = tcx.hir();
1587 let proc_macro_decls_static = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap().index;
1588 let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied();
1589 let macros = self.lazy(hir.krate().proc_macros.iter().map(|p| p.owner.local_def_index));
1591 record!(self.tables.def_kind[LOCAL_CRATE.as_def_id()] <- DefKind::Mod);
1592 record!(self.tables.span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1593 record!(self.tables.attributes[LOCAL_CRATE.as_def_id()] <- tcx.get_attrs(LOCAL_CRATE.as_def_id()));
1594 record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- tcx.visibility(LOCAL_CRATE.as_def_id()));
1595 if let Some(stability) = stability {
1596 record!(self.tables.stability[LOCAL_CRATE.as_def_id()] <- stability);
1598 self.encode_deprecation(LOCAL_CRATE.as_def_id());
1600 // Normally, this information is encoded when we walk the items
1601 // defined in this crate. However, we skip doing that for proc-macro crates,
1602 // so we manually encode just the information that we need
1603 for proc_macro in &hir.krate().proc_macros {
1604 let id = proc_macro.owner.local_def_index;
1605 let mut name = hir.name(*proc_macro);
1606 let span = hir.span(*proc_macro);
1607 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1608 // so downstream crates need access to them.
1609 let attrs = hir.attrs(*proc_macro);
1610 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1612 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1614 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1615 // This unwrap chain should have been checked by the proc-macro harness.
1616 name = attr.meta_item_list().unwrap()[0]
1624 bug!("Unknown proc-macro type for item {:?}", id);
1627 let mut def_key = self.tcx.hir().def_key(proc_macro.owner);
1628 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1630 let def_id = DefId::local(id);
1631 record!(self.tables.def_kind[def_id] <- DefKind::Macro(macro_kind));
1632 record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind));
1633 record!(self.tables.attributes[def_id] <- attrs);
1634 record!(self.tables.def_keys[def_id] <- def_key);
1635 record!(self.tables.ident_span[def_id] <- span);
1636 record!(self.tables.span[def_id] <- span);
1637 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1638 if let Some(stability) = stability {
1639 record!(self.tables.stability[def_id] <- stability);
1643 Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1649 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1650 empty_proc_macro!(self);
1651 let crates = self.tcx.crates();
1653 let mut deps = crates
1656 let dep = CrateDep {
1657 name: self.tcx.original_crate_name(cnum),
1658 hash: self.tcx.crate_hash(cnum),
1659 host_hash: self.tcx.crate_host_hash(cnum),
1660 kind: self.tcx.dep_kind(cnum),
1661 extra_filename: self.tcx.extra_filename(cnum),
1665 .collect::<Vec<_>>();
1667 deps.sort_by_key(|&(cnum, _)| cnum);
1670 // Sanity-check the crate numbers
1671 let mut expected_cnum = 1;
1672 for &(n, _) in &deps {
1673 assert_eq!(n, CrateNum::new(expected_cnum));
1678 // We're just going to write a list of crate 'name-hash-version's, with
1679 // the assumption that they are numbered 1 to n.
1680 // FIXME (#2166): This is not nearly enough to support correct versioning
1681 // but is enough to get transitive crate dependencies working.
1682 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1685 fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> {
1686 empty_proc_macro!(self);
1688 let lib_features = tcx.lib_features();
1689 self.lazy(lib_features.to_vec())
1692 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1693 empty_proc_macro!(self);
1695 let diagnostic_items = tcx.diagnostic_items(LOCAL_CRATE);
1696 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1699 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1700 empty_proc_macro!(self);
1702 let lang_items = tcx.lang_items();
1703 let lang_items = lang_items.items().iter();
1704 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1705 if let Some(def_id) = opt_def_id {
1706 if def_id.is_local() {
1707 return Some((def_id.index, i));
1714 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1715 empty_proc_macro!(self);
1717 self.lazy(&tcx.lang_items().missing)
1720 /// Encodes an index, mapping each trait to its (local) implementations.
1721 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1722 empty_proc_macro!(self);
1723 debug!("EncodeContext::encode_impls()");
1725 let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() };
1726 tcx.hir().krate().visit_all_item_likes(&mut visitor);
1728 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1730 // Bring everything into deterministic order for hashing
1731 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1733 let all_impls: Vec<_> = all_impls
1735 .map(|(trait_def_id, mut impls)| {
1736 // Bring everything into deterministic order for hashing
1737 impls.sort_by_cached_key(|&(index, _)| {
1738 tcx.hir().definitions().def_path_hash(LocalDefId { local_def_index: index })
1742 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1743 impls: self.lazy(&impls),
1748 self.lazy(&all_impls)
1751 // Encodes all symbols exported from this crate into the metadata.
1753 // This pass is seeded off the reachability list calculated in the
1754 // middle::reachable module but filters out items that either don't have a
1755 // symbol associated with them (they weren't translated) or if they're an FFI
1756 // definition (as that's not defined in this crate).
1757 fn encode_exported_symbols(
1759 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1760 ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1761 empty_proc_macro!(self);
1762 // The metadata symbol name is special. It should not show up in
1763 // downstream crates.
1764 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1769 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1770 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1777 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1778 empty_proc_macro!(self);
1779 let formats = self.tcx.dependency_formats(LOCAL_CRATE);
1780 for (ty, arr) in formats.iter() {
1781 if *ty != CrateType::Dylib {
1784 return self.lazy(arr.iter().map(|slot| match *slot {
1785 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1787 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1788 Linkage::Static => Some(LinkagePreference::RequireStatic),
1794 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1797 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1800 hir::ForeignItemKind::Fn(_, ref names, _) => {
1802 asyncness: hir::IsAsync::NotAsync,
1803 constness: if self.tcx.is_const_fn_raw(def_id) {
1804 hir::Constness::Const
1806 hir::Constness::NotConst
1808 param_names: self.encode_fn_param_names(names),
1810 record!(self.tables.kind[def_id] <- EntryKind::ForeignFn(self.lazy(data)));
1812 hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => {
1813 record!(self.tables.kind[def_id] <- EntryKind::ForeignMutStatic);
1815 hir::ForeignItemKind::Static(_, hir::Mutability::Not) => {
1816 record!(self.tables.kind[def_id] <- EntryKind::ForeignImmStatic);
1818 hir::ForeignItemKind::Type => {
1819 record!(self.tables.kind[def_id] <- EntryKind::ForeignType);
1822 self.encode_ident_span(def_id, nitem.ident);
1823 self.encode_item_type(def_id);
1824 self.encode_inherent_implementations(def_id);
1825 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1826 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1827 self.encode_variances_of(def_id);
1829 self.encode_generics(def_id);
1830 self.encode_explicit_predicates(def_id);
1831 self.encode_inferred_outlives(def_id);
1835 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1836 impl Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1837 type Map = Map<'tcx>;
1839 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1840 NestedVisitorMap::OnlyBodies(self.tcx.hir())
1842 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1843 intravisit::walk_expr(self, ex);
1844 self.encode_info_for_expr(ex);
1846 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1847 intravisit::walk_anon_const(self, c);
1848 let def_id = self.tcx.hir().local_def_id(c.hir_id);
1849 self.encode_info_for_anon_const(def_id);
1851 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1852 intravisit::walk_item(self, item);
1854 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1855 _ => self.encode_info_for_item(item.def_id.to_def_id(), item),
1857 self.encode_addl_info_for_item(item);
1859 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1860 intravisit::walk_foreign_item(self, ni);
1861 self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni);
1863 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1864 intravisit::walk_generics(self, generics);
1865 self.encode_info_for_generics(generics);
1867 fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef<'tcx>) {
1868 self.encode_info_for_macro_def(macro_def);
1872 impl EncodeContext<'a, 'tcx> {
1873 fn encode_fields(&mut self, adt_def: &ty::AdtDef) {
1874 for (variant_index, variant) in adt_def.variants.iter_enumerated() {
1875 for (field_index, _field) in variant.fields.iter().enumerate() {
1876 self.encode_field(adt_def, variant_index, field_index);
1881 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1882 for param in generics.params {
1883 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1885 GenericParamKind::Lifetime { .. } => continue,
1886 GenericParamKind::Type { default, .. } => {
1887 self.encode_info_for_generic_param(
1889 EntryKind::TypeParam,
1893 GenericParamKind::Const { .. } => {
1894 self.encode_info_for_generic_param(
1896 EntryKind::ConstParam,
1899 // FIXME(const_generics_defaults)
1905 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1906 if let hir::ExprKind::Closure(..) = expr.kind {
1907 let def_id = self.tcx.hir().local_def_id(expr.hir_id);
1908 self.encode_info_for_closure(def_id);
1912 fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) {
1913 record!(self.tables.ident_span[def_id] <- ident.span);
1916 /// In some cases, along with the item itself, we also
1917 /// encode some sub-items. Usually we want some info from the item
1918 /// so it's easier to do that here then to wait until we would encounter
1919 /// normally in the visitor walk.
1920 fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1922 hir::ItemKind::Static(..)
1923 | hir::ItemKind::Const(..)
1924 | hir::ItemKind::Fn(..)
1925 | hir::ItemKind::Mod(..)
1926 | hir::ItemKind::ForeignMod { .. }
1927 | hir::ItemKind::GlobalAsm(..)
1928 | hir::ItemKind::ExternCrate(..)
1929 | hir::ItemKind::Use(..)
1930 | hir::ItemKind::TyAlias(..)
1931 | hir::ItemKind::OpaqueTy(..)
1932 | hir::ItemKind::TraitAlias(..) => {
1933 // no sub-item recording needed in these cases
1935 hir::ItemKind::Enum(..) => {
1936 let def = self.tcx.adt_def(item.def_id.to_def_id());
1937 self.encode_fields(def);
1939 for (i, variant) in def.variants.iter_enumerated() {
1940 self.encode_enum_variant_info(def, i);
1942 if let Some(_ctor_def_id) = variant.ctor_def_id {
1943 self.encode_enum_variant_ctor(def, i);
1947 hir::ItemKind::Struct(ref struct_def, _) => {
1948 let def = self.tcx.adt_def(item.def_id.to_def_id());
1949 self.encode_fields(def);
1951 // If the struct has a constructor, encode it.
1952 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
1953 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
1954 self.encode_struct_ctor(def, ctor_def_id.to_def_id());
1957 hir::ItemKind::Union(..) => {
1958 let def = self.tcx.adt_def(item.def_id.to_def_id());
1959 self.encode_fields(def);
1961 hir::ItemKind::Impl { .. } => {
1962 for &trait_item_def_id in
1963 self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
1965 self.encode_info_for_impl_item(trait_item_def_id);
1968 hir::ItemKind::Trait(..) => {
1969 for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
1971 self.encode_info_for_trait_item(item_def_id);
1978 struct ImplVisitor<'tcx> {
1980 impls: FxHashMap<DefId, Vec<(DefIndex, Option<ty::fast_reject::SimplifiedType>)>>,
1983 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> {
1984 fn visit_item(&mut self, item: &hir::Item<'_>) {
1985 if let hir::ItemKind::Impl { .. } = item.kind {
1986 if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) {
1987 let simplified_self_ty =
1988 ty::fast_reject::simplify_type(self.tcx, trait_ref.self_ty(), false);
1991 .entry(trait_ref.def_id)
1993 .push((item.def_id.local_def_index, simplified_self_ty));
1998 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
2000 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
2001 // handled in `visit_item` above
2004 fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {}
2007 /// Used to prefetch queries which will be needed later by metadata encoding.
2008 /// Only a subset of the queries are actually prefetched to keep this code smaller.
2009 fn prefetch_mir(tcx: TyCtxt<'_>) {
2010 if !tcx.sess.opts.output_types.should_codegen() {
2011 // We won't emit MIR, so don't prefetch it.
2015 par_iter(tcx.mir_keys(LOCAL_CRATE)).for_each(|&def_id| {
2016 let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
2019 tcx.ensure().mir_for_ctfe(def_id);
2022 tcx.ensure().optimized_mir(def_id);
2024 if encode_opt || encode_const {
2025 tcx.ensure().promoted_mir(def_id);
2030 // NOTE(eddyb) The following comment was preserved for posterity, even
2031 // though it's no longer relevant as EBML (which uses nested & tagged
2032 // "documents") was replaced with a scheme that can't go out of bounds.
2034 // And here we run into yet another obscure archive bug: in which metadata
2035 // loaded from archives may have trailing garbage bytes. Awhile back one of
2036 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2037 // and opt) by having ebml generate an out-of-bounds panic when looking at
2040 // Upon investigation it turned out that the metadata file inside of an rlib
2041 // (and ar archive) was being corrupted. Some compilations would generate a
2042 // metadata file which would end in a few extra bytes, while other
2043 // compilations would not have these extra bytes appended to the end. These
2044 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2045 // being interpreted causing the out-of-bounds.
2047 // The root cause of why these extra bytes were appearing was never
2048 // discovered, and in the meantime the solution we're employing is to insert
2049 // the length of the metadata to the start of the metadata. Later on this
2050 // will allow us to slice the metadata to the precise length that we just
2051 // generated regardless of trailing bytes that end up in it.
2053 pub(super) fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
2054 // Since encoding metadata is not in a query, and nothing is cached,
2055 // there's no need to do dep-graph tracking for any of it.
2056 tcx.dep_graph.assert_ignored();
2059 || encode_metadata_impl(tcx),
2061 if tcx.sess.threads() == 1 {
2064 // Prefetch some queries used by metadata encoding.
2065 // This is not necessary for correctness, but is only done for performance reasons.
2066 // It can be removed if it turns out to cause trouble or be detrimental to performance.
2067 join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2073 fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata {
2074 let mut encoder = opaque::Encoder::new(vec![]);
2075 encoder.emit_raw_bytes(METADATA_HEADER);
2077 // Will be filled with the root position after encoding everything.
2078 encoder.emit_raw_bytes(&[0, 0, 0, 0]);
2080 let source_map_files = tcx.sess.source_map().files();
2081 let source_file_cache = (source_map_files[0].clone(), 0);
2082 let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len()));
2083 drop(source_map_files);
2085 let hygiene_ctxt = HygieneEncodeContext::default();
2087 let mut ecx = EncodeContext {
2090 feat: tcx.features(),
2091 tables: Default::default(),
2092 lazy_state: LazyState::NoNode,
2093 type_shorthands: Default::default(),
2094 predicate_shorthands: Default::default(),
2096 interpret_allocs: Default::default(),
2097 required_source_files,
2098 is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2099 hygiene_ctxt: &hygiene_ctxt,
2102 // Encode the rustc version string in a predictable location.
2103 rustc_version().encode(&mut ecx).unwrap();
2105 // Encode all the entries and extra information in the crate,
2106 // culminating in the `CrateRoot` which points to all of it.
2107 let root = ecx.encode_crate_root();
2109 let mut result = ecx.opaque.into_inner();
2111 // Encode the root position.
2112 let header = METADATA_HEADER.len();
2113 let pos = root.position.get();
2114 result[header + 0] = (pos >> 24) as u8;
2115 result[header + 1] = (pos >> 16) as u8;
2116 result[header + 2] = (pos >> 8) as u8;
2117 result[header + 3] = (pos >> 0) as u8;
2119 EncodedMetadata { raw_data: result }