1 use crate::rmeta::def_path_hash_map::DefPathHashMapRef;
2 use crate::rmeta::table::{FixedSizeEncoding, TableBuilder};
5 use rustc_data_structures::fingerprint::Fingerprint;
6 use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
7 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
8 use rustc_data_structures::sync::{join, par_iter, Lrc, ParallelIterator};
10 use rustc_hir::def::DefKind;
11 use rustc_hir::def_id::{
12 CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE,
14 use rustc_hir::definitions::DefPathData;
15 use rustc_hir::intravisit::{self, Visitor};
16 use rustc_hir::itemlikevisit::ItemLikeVisitor;
17 use rustc_hir::lang_items;
18 use rustc_hir::{AnonConst, GenericParamKind};
19 use rustc_index::bit_set::GrowableBitSet;
20 use rustc_index::vec::Idx;
21 use rustc_middle::hir::nested_filter;
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::thir;
28 use rustc_middle::traits::specialization_graph;
29 use rustc_middle::ty::codec::TyEncoder;
30 use rustc_middle::ty::fast_reject::{self, SimplifiedType, TreatParams};
31 use rustc_middle::ty::query::Providers;
32 use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
33 use rustc_serialize::{opaque, Encodable, Encoder};
34 use rustc_session::config::CrateType;
35 use rustc_session::cstore::{ForeignModule, LinkagePreference, NativeLib};
36 use rustc_span::symbol::{sym, Ident, Symbol};
37 use rustc_span::{self, ExternalSource, FileName, SourceFile, Span, SyntaxContext};
39 hygiene::{ExpnIndex, HygieneEncodeContext, MacroKind},
42 use rustc_target::abi::VariantIdx;
44 use std::num::NonZeroUsize;
46 use tracing::{debug, trace};
48 pub(super) struct EncodeContext<'a, 'tcx> {
49 opaque: opaque::Encoder,
51 feat: &'tcx rustc_feature::Features,
53 tables: TableBuilders<'tcx>,
55 lazy_state: LazyState,
56 type_shorthands: FxHashMap<Ty<'tcx>, usize>,
57 predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
59 interpret_allocs: FxIndexSet<interpret::AllocId>,
61 // This is used to speed up Span encoding.
62 // The `usize` is an index into the `MonotonicVec`
63 // that stores the `SourceFile`
64 source_file_cache: (Lrc<SourceFile>, usize),
65 // The indices (into the `SourceMap`'s `MonotonicVec`)
66 // of all of the `SourceFiles` that we need to serialize.
67 // When we serialize a `Span`, we insert the index of its
68 // `SourceFile` into the `GrowableBitSet`.
70 // This needs to be a `GrowableBitSet` and not a
71 // regular `BitSet` because we may actually import new `SourceFiles`
72 // during metadata encoding, due to executing a query
73 // with a result containing a foreign `Span`.
74 required_source_files: Option<GrowableBitSet<usize>>,
76 hygiene_ctxt: &'a HygieneEncodeContext,
79 /// If the current crate is a proc-macro, returns early with `Lazy:empty()`.
80 /// This is useful for skipping the encoding of things that aren't needed
81 /// for proc-macro crates.
82 macro_rules! empty_proc_macro {
84 if $self.is_proc_macro {
90 macro_rules! encoder_methods {
91 ($($name:ident($ty:ty);)*) => {
92 $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
93 self.opaque.$name(value)
98 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
99 type Error = <opaque::Encoder as Encoder>::Error;
102 fn emit_unit(&mut self) -> Result<(), Self::Error> {
126 emit_raw_bytes(&[u8]);
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_lazy_distance(*self)
138 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>>
141 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
142 e.emit_usize(self.meta)?;
146 e.emit_lazy_distance(*self)
150 impl<'a, 'tcx, I: Idx, T> Encodable<EncodeContext<'a, 'tcx>> for Lazy<Table<I, T>>
152 Option<T>: FixedSizeEncoding,
154 fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
155 e.emit_usize(self.meta)?;
156 e.emit_lazy_distance(*self)
160 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum {
161 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
162 if *self != LOCAL_CRATE && s.is_proc_macro {
163 panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self);
165 s.emit_u32(self.as_u32())
169 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex {
170 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
171 s.emit_u32(self.as_u32())
175 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
176 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
177 s.emit_u32(self.as_u32())
181 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
182 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
183 rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s)
187 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
188 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
189 if self.krate == LOCAL_CRATE {
190 // We will only write details for local expansions. Non-local expansions will fetch
191 // data from the corresponding crate's metadata.
192 // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external
193 // metadata from proc-macro crates.
194 s.hygiene_ctxt.schedule_expn_data_for_encoding(*self);
196 self.krate.encode(s)?;
197 self.local_id.encode(s)
201 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
202 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
203 let span = self.data();
205 // Don't serialize any `SyntaxContext`s from a proc-macro crate,
206 // since we don't load proc-macro dependencies during serialization.
207 // This means that any hygiene information from macros used *within*
208 // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
209 // definition) will be lost.
211 // This can show up in two ways:
213 // 1. Any hygiene information associated with identifier of
214 // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
215 // Since proc-macros can only be invoked from a different crate,
216 // real code should never need to care about this.
218 // 2. Using `Span::def_site` or `Span::mixed_site` will not
219 // include any hygiene information associated with the definition
220 // site. This means that a proc-macro cannot emit a `$crate`
221 // identifier which resolves to one of its dependencies,
222 // which also should never come up in practice.
224 // Additionally, this affects `Span::parent`, and any other
225 // span inspection APIs that would otherwise allow traversing
226 // the `SyntaxContexts` associated with a span.
228 // None of these user-visible effects should result in any
229 // cross-crate inconsistencies (getting one behavior in the same
230 // crate, and a different behavior in another crate) due to the
231 // limited surface that proc-macros can expose.
233 // IMPORTANT: If this is ever changed, be sure to update
234 // `rustc_span::hygiene::raw_encode_expn_id` to handle
235 // encoding `ExpnData` for proc-macro crates.
237 SyntaxContext::root().encode(s)?;
239 span.ctxt.encode(s)?;
243 return TAG_PARTIAL_SPAN.encode(s);
246 // The Span infrastructure should make sure that this invariant holds:
247 debug_assert!(span.lo <= span.hi);
249 if !s.source_file_cache.0.contains(span.lo) {
250 let source_map = s.tcx.sess.source_map();
251 let source_file_index = source_map.lookup_source_file_idx(span.lo);
252 s.source_file_cache =
253 (source_map.files()[source_file_index].clone(), source_file_index);
256 if !s.source_file_cache.0.contains(span.hi) {
257 // Unfortunately, macro expansion still sometimes generates Spans
258 // that malformed in this way.
259 return TAG_PARTIAL_SPAN.encode(s);
262 let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!");
263 // Record the fact that we need to encode the data for this `SourceFile`
264 source_files.insert(s.source_file_cache.1);
266 // There are two possible cases here:
267 // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
268 // crate we are writing metadata for. When the metadata for *this* crate gets
269 // deserialized, the deserializer will need to know which crate it originally came
270 // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
271 // be deserialized after the rest of the span data, which tells the deserializer
272 // which crate contains the source map information.
273 // 2. This span comes from our own crate. No special handling is needed - we just
274 // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
275 // our own source map information.
277 // If we're a proc-macro crate, we always treat this as a local `Span`.
278 // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
279 // if we're a proc-macro crate.
280 // This allows us to avoid loading the dependencies of proc-macro crates: all of
281 // the information we need to decode `Span`s is stored in the proc-macro crate.
282 let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro {
283 // To simplify deserialization, we 'rebase' this span onto the crate it originally came from
284 // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values
285 // are relative to the source map information for the 'foreign' crate whose CrateNum
286 // we write into the metadata. This allows `imported_source_files` to binary
287 // search through the 'foreign' crate's source map information, using the
288 // deserialized 'lo' and 'hi' values directly.
290 // All of this logic ensures that the final result of deserialization is a 'normal'
291 // Span that can be used without any additional trouble.
292 let external_start_pos = {
293 // Introduce a new scope so that we drop the 'lock()' temporary
294 match &*s.source_file_cache.0.external_src.lock() {
295 ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos,
296 src => panic!("Unexpected external source {:?}", src),
299 let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos;
300 let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos;
302 (TAG_VALID_SPAN_FOREIGN, lo, hi)
304 (TAG_VALID_SPAN_LOCAL, span.lo, span.hi)
310 // Encode length which is usually less than span.hi and profits more
311 // from the variable-length integer encoding that we use.
315 if tag == TAG_VALID_SPAN_FOREIGN {
316 // This needs to be two lines to avoid holding the `s.source_file_cache`
317 // while calling `cnum.encode(s)`
318 let cnum = s.source_file_cache.0.cnum;
326 impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
327 const CLEAR_CROSS_CRATE: bool = true;
329 fn position(&self) -> usize {
330 self.opaque.position()
333 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
334 &mut self.type_shorthands
337 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
338 &mut self.predicate_shorthands
343 alloc_id: &rustc_middle::mir::interpret::AllocId,
344 ) -> Result<(), Self::Error> {
345 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
351 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [thir::abstract_const::Node<'tcx>] {
352 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
357 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] {
358 fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult {
363 /// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
364 trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> {
365 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta;
368 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for &T {
369 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
370 self.encode(ecx).unwrap()
374 impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for T {
375 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) {
376 self.encode(ecx).unwrap()
380 impl<'a, 'tcx, I, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, [T]> for I
383 I::Item: EncodeContentsForLazy<'a, 'tcx, T>,
385 fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize {
386 self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
390 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would
391 // normally need extra variables to avoid errors about multiple mutable borrows.
392 macro_rules! record {
393 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
396 let lazy = $self.lazy(value);
397 $self.$tables.$table.set($def_id.index, lazy);
402 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
403 fn emit_lazy_distance<T: ?Sized + LazyMeta>(
406 ) -> Result<(), <Self as Encoder>::Error> {
407 let pos = lazy.position.get();
408 let distance = match self.lazy_state {
409 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
410 LazyState::NodeStart(start) => {
411 let start = start.get();
412 assert!(pos <= start);
415 LazyState::Previous(last_pos) => {
417 last_pos <= lazy.position,
418 "make sure that the calls to `lazy*` \
419 are in the same order as the metadata fields",
421 lazy.position.get() - last_pos.get()
424 self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap());
425 self.emit_usize(distance)
428 fn lazy<T: ?Sized + LazyMeta>(
430 value: impl EncodeContentsForLazy<'a, 'tcx, T>,
432 let pos = NonZeroUsize::new(self.position()).unwrap();
434 assert_eq!(self.lazy_state, LazyState::NoNode);
435 self.lazy_state = LazyState::NodeStart(pos);
436 let meta = value.encode_contents_for_lazy(self);
437 self.lazy_state = LazyState::NoNode;
439 assert!(pos.get() <= self.position());
441 Lazy::from_position_and_meta(pos, meta)
444 fn encode_info_for_items(&mut self) {
445 self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module());
447 // Proc-macro crates only export proc-macro items, which are looked
448 // up using `proc_macro_data`
449 if self.is_proc_macro {
453 self.tcx.hir().visit_all_item_likes(&mut self.as_deep_visitor());
456 fn encode_def_path_table(&mut self) {
457 let table = self.tcx.resolutions(()).definitions.def_path_table();
458 if self.is_proc_macro {
459 for def_index in std::iter::once(CRATE_DEF_INDEX)
460 .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index))
462 let def_key = self.lazy(table.def_key(def_index));
463 let def_path_hash = table.def_path_hash(def_index);
464 self.tables.def_keys.set(def_index, def_key);
465 self.tables.def_path_hashes.set(def_index, def_path_hash);
468 for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
469 let def_key = self.lazy(def_key);
470 self.tables.def_keys.set(def_index, def_key);
471 self.tables.def_path_hashes.set(def_index, *def_path_hash);
476 fn encode_def_path_hash_map(&mut self) -> Lazy<DefPathHashMapRef<'tcx>> {
477 self.lazy(DefPathHashMapRef::BorrowedFromTcx(
478 self.tcx.resolutions(()).definitions.def_path_hash_to_def_index_map(),
482 fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> {
483 let source_map = self.tcx.sess.source_map();
484 let all_source_files = source_map.files();
486 // By replacing the `Option` with `None`, we ensure that we can't
487 // accidentally serialize any more `Span`s after the source map encoding
489 let required_source_files = self.required_source_files.take().unwrap();
491 let adapted = all_source_files
494 .filter(|(idx, source_file)| {
495 // Only serialize `SourceFile`s that were used
496 // during the encoding of a `Span`
497 required_source_files.contains(*idx) &&
498 // Don't serialize imported `SourceFile`s, unless
499 // we're in a proc-macro crate.
500 (!source_file.is_imported() || self.is_proc_macro)
502 .map(|(_, source_file)| {
503 let mut adapted = match source_file.name {
504 FileName::Real(ref realname) => {
505 let mut adapted = (**source_file).clone();
506 adapted.name = FileName::Real(match realname {
507 RealFileName::LocalPath(path_to_file) => {
508 // Prepend path of working directory onto potentially
509 // relative paths, because they could become relative
510 // to a wrong directory.
511 // We include `working_dir` as part of the crate hash,
512 // so it's okay for us to use it as part of the encoded
514 let working_dir = &self.tcx.sess.opts.working_dir;
516 RealFileName::LocalPath(absolute) => {
517 // Although neither working_dir or the file name were subject
518 // to path remapping, the concatenation between the two may
519 // be. Hence we need to do a remapping here.
520 let joined = Path::new(absolute).join(path_to_file);
521 let (joined, remapped) =
522 source_map.path_mapping().map_prefix(joined);
524 RealFileName::Remapped {
526 virtual_name: joined,
529 RealFileName::LocalPath(joined)
532 RealFileName::Remapped { local_path: _, virtual_name } => {
533 // If working_dir has been remapped, then we emit
534 // Remapped variant as the expanded path won't be valid
535 RealFileName::Remapped {
537 virtual_name: Path::new(virtual_name)
543 RealFileName::Remapped { local_path: _, virtual_name } => {
544 RealFileName::Remapped {
545 // We do not want any local path to be exported into metadata
547 virtual_name: virtual_name.clone(),
551 adapted.name_hash = {
552 let mut hasher: StableHasher = StableHasher::new();
553 adapted.name.hash(&mut hasher);
554 hasher.finish::<u128>()
559 // expanded code, not from a file
560 _ => source_file.clone(),
563 // We're serializing this `SourceFile` into our crate metadata,
564 // so mark it as coming from this crate.
565 // This also ensures that we don't try to deserialize the
566 // `CrateNum` for a proc-macro dependency - since proc macro
567 // dependencies aren't loaded when we deserialize a proc-macro,
568 // trying to remap the `CrateNum` would fail.
569 if self.is_proc_macro {
570 Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE;
574 .collect::<Vec<_>>();
576 self.lazy(adapted.iter().map(|rc| &**rc))
579 fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
581 let mut i = self.position();
583 // Encode the crate deps
584 let crate_deps = self.encode_crate_deps();
585 let dylib_dependency_formats = self.encode_dylib_dependency_formats();
586 let dep_bytes = self.position() - i;
588 // Encode the lib features.
590 let lib_features = self.encode_lib_features();
591 let lib_feature_bytes = self.position() - i;
593 // Encode the language items.
595 let lang_items = self.encode_lang_items();
596 let lang_items_missing = self.encode_lang_items_missing();
597 let lang_item_bytes = self.position() - i;
599 // Encode the diagnostic items.
601 let diagnostic_items = self.encode_diagnostic_items();
602 let diagnostic_item_bytes = self.position() - i;
604 // Encode the native libraries used
606 let native_libraries = self.encode_native_libraries();
607 let native_lib_bytes = self.position() - i;
609 let foreign_modules = self.encode_foreign_modules();
611 // Encode DefPathTable
613 self.encode_def_path_table();
614 let def_path_table_bytes = self.position() - i;
616 // Encode the def IDs of traits, for rustdoc and diagnostics.
618 let traits = self.encode_traits();
619 let traits_bytes = self.position() - i;
621 // Encode the def IDs of impls, for coherence checking.
623 let impls = self.encode_impls();
624 let impls_bytes = self.position() - i;
627 let incoherent_impls = self.encode_incoherent_impls();
628 let incoherent_impls_bytes = self.position() - i;
632 let mir_bytes = self.position() - i;
636 self.encode_def_ids();
637 self.encode_info_for_items();
638 let item_bytes = self.position() - i;
640 // Encode the allocation index
641 let interpret_alloc_index = {
642 let mut interpret_alloc_index = Vec::new();
644 trace!("beginning to encode alloc ids");
646 let new_n = self.interpret_allocs.len();
647 // if we have found new ids, serialize those, too
652 trace!("encoding {} further alloc ids", new_n - n);
653 for idx in n..new_n {
654 let id = self.interpret_allocs[idx];
655 let pos = self.position() as u32;
656 interpret_alloc_index.push(pos);
657 interpret::specialized_encode_alloc_id(self, tcx, id).unwrap();
661 self.lazy(interpret_alloc_index)
664 // Encode the proc macro data. This affects 'tables',
665 // so we need to do this before we encode the tables
667 let proc_macro_data = self.encode_proc_macros();
668 let proc_macro_data_bytes = self.position() - i;
671 let tables = self.tables.encode(&mut self.opaque);
672 let tables_bytes = self.position() - i;
674 // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
675 // this as late as possible to give the prefetching as much time as possible to complete.
677 let exported_symbols = tcx.exported_symbols(LOCAL_CRATE);
678 let exported_symbols = self.encode_exported_symbols(&exported_symbols);
679 let exported_symbols_bytes = self.position() - i;
681 // Encode the hygiene data,
682 // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process
683 // of encoding other items (e.g. `optimized_mir`) may cause us to load
684 // data from the incremental cache. If this causes us to deserialize a `Span`,
685 // then we may load additional `SyntaxContext`s into the global `HygieneData`.
686 // Therefore, we need to encode the hygiene data last to ensure that we encode
687 // any `SyntaxContext`s that might be used.
689 let (syntax_contexts, expn_data, expn_hashes) = self.encode_hygiene();
690 let hygiene_bytes = self.position() - i;
693 let def_path_hash_map = self.encode_def_path_hash_map();
694 let def_path_hash_map_bytes = self.position() - i;
696 // Encode source_map. This needs to be done last,
697 // since encoding `Span`s tells us which `SourceFiles` we actually
700 let source_map = self.encode_source_map();
701 let source_map_bytes = self.position() - i;
703 let attrs = tcx.hir().krate_attrs();
704 let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator);
706 let root = self.lazy(CrateRoot {
707 name: tcx.crate_name(LOCAL_CRATE),
708 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
709 triple: tcx.sess.opts.target_triple.clone(),
710 hash: tcx.crate_hash(LOCAL_CRATE),
711 stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(),
712 panic_strategy: tcx.sess.panic_strategy(),
713 panic_in_drop_strategy: tcx.sess.opts.debugging_opts.panic_in_drop,
714 edition: tcx.sess.edition(),
715 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
716 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
717 has_default_lib_allocator,
719 compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
720 needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
721 needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
722 no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
723 panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
724 profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
725 symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
728 dylib_dependency_formats,
740 interpret_alloc_index,
748 let total_bytes = self.position();
750 if tcx.sess.meta_stats() {
751 let mut zero_bytes = 0;
752 for e in self.opaque.data.iter() {
758 eprintln!("metadata stats:");
759 eprintln!(" dep bytes: {}", dep_bytes);
760 eprintln!(" lib feature bytes: {}", lib_feature_bytes);
761 eprintln!(" lang item bytes: {}", lang_item_bytes);
762 eprintln!(" diagnostic item bytes: {}", diagnostic_item_bytes);
763 eprintln!(" native bytes: {}", native_lib_bytes);
764 eprintln!(" source_map bytes: {}", source_map_bytes);
765 eprintln!(" traits bytes: {}", traits_bytes);
766 eprintln!(" impls bytes: {}", impls_bytes);
767 eprintln!("incoherent_impls bytes: {}", incoherent_impls_bytes);
768 eprintln!(" exp. symbols bytes: {}", exported_symbols_bytes);
769 eprintln!(" def-path table bytes: {}", def_path_table_bytes);
770 eprintln!(" def-path hashes bytes: {}", def_path_hash_map_bytes);
771 eprintln!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
772 eprintln!(" mir bytes: {}", mir_bytes);
773 eprintln!(" item bytes: {}", item_bytes);
774 eprintln!(" table bytes: {}", tables_bytes);
775 eprintln!(" hygiene bytes: {}", hygiene_bytes);
776 eprintln!(" zero bytes: {}", zero_bytes);
777 eprintln!(" total bytes: {}", total_bytes);
784 fn should_encode_visibility(def_kind: DefKind) -> bool {
794 | DefKind::TraitAlias
798 | DefKind::Static(..)
801 | DefKind::AssocConst
804 | DefKind::ForeignMod
807 | DefKind::Field => true,
809 | DefKind::ConstParam
810 | DefKind::LifetimeParam
812 | DefKind::InlineConst
816 | DefKind::ExternCrate => false,
820 fn should_encode_stability(def_kind: DefKind) -> bool {
829 | DefKind::AssocConst
831 | DefKind::ConstParam
832 | DefKind::Static(..)
835 | DefKind::ForeignMod
842 | DefKind::TraitAlias
844 | DefKind::ForeignTy => true,
846 | DefKind::LifetimeParam
848 | DefKind::InlineConst
852 | DefKind::ExternCrate => false,
856 /// Whether we should encode MIR.
858 /// Computing, optimizing and encoding the MIR is a relatively expensive operation.
859 /// We want to avoid this work when not required. Therefore:
860 /// - we only compute `mir_for_ctfe` on items with const-eval semantics;
861 /// - we skip `optimized_mir` for check runs.
863 /// Return a pair, resp. for CTFE and for LLVM.
864 fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) {
865 match tcx.def_kind(def_id) {
867 DefKind::Ctor(_, _) => {
868 let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
869 || tcx.sess.opts.debugging_opts.always_encode_mir;
874 | DefKind::InlineConst
875 | DefKind::AssocConst
876 | DefKind::Static(..)
877 | DefKind::Const => (true, false),
878 // Full-fledged functions
879 DefKind::AssocFn | DefKind::Fn => {
880 let generics = tcx.generics_of(def_id);
881 let needs_inline = (generics.requires_monomorphization(tcx)
882 || tcx.codegen_fn_attrs(def_id).requests_inline())
883 && tcx.sess.opts.output_types.should_codegen();
884 // The function has a `const` modifier or is annotated with `default_method_body_is_const`.
885 let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id())
886 || tcx.has_attr(def_id.to_def_id(), sym::default_method_body_is_const);
887 let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir;
888 (is_const_fn, needs_inline || always_encode_mir)
890 // Closures can't be const fn.
891 DefKind::Closure => {
892 let generics = tcx.generics_of(def_id);
893 let needs_inline = (generics.requires_monomorphization(tcx)
894 || tcx.codegen_fn_attrs(def_id).requests_inline())
895 && tcx.sess.opts.output_types.should_codegen();
896 let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir;
897 (false, needs_inline || always_encode_mir)
899 // Generators require optimized MIR to compute layout.
900 DefKind::Generator => (false, true),
901 // The others don't have MIR.
906 fn should_encode_variances(def_kind: DefKind) -> bool {
914 | DefKind::AssocFn => true,
918 | DefKind::AssocConst
920 | DefKind::ConstParam
921 | DefKind::Static(..)
923 | DefKind::ForeignMod
928 | DefKind::TraitAlias
932 | DefKind::LifetimeParam
934 | DefKind::InlineConst
938 | DefKind::ExternCrate => false,
942 fn should_encode_generics(def_kind: DefKind) -> bool {
951 | DefKind::TraitAlias
955 | DefKind::Static(..)
958 | DefKind::AssocConst
960 | DefKind::InlineConst
966 | DefKind::Generator => true,
968 | DefKind::ForeignMod
969 | DefKind::ConstParam
972 | DefKind::LifetimeParam
974 | DefKind::ExternCrate => false,
978 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
979 fn encode_def_ids(&mut self) {
980 if self.is_proc_macro {
985 for local_id in hir.iter_local_def_id() {
986 let def_id = local_id.to_def_id();
987 let def_kind = tcx.opt_def_kind(local_id);
988 let Some(def_kind) = def_kind else { continue };
989 self.tables.opt_def_kind.set(def_id.index, def_kind);
990 record!(self.tables.def_span[def_id] <- tcx.def_span(def_id));
991 record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id));
992 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
993 if should_encode_visibility(def_kind) {
994 record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id));
996 if should_encode_stability(def_kind) {
997 self.encode_stability(def_id);
998 self.encode_const_stability(def_id);
999 self.encode_deprecation(def_id);
1001 if should_encode_variances(def_kind) {
1002 let v = self.tcx.variances_of(def_id);
1003 record!(self.tables.variances_of[def_id] <- v);
1005 if should_encode_generics(def_kind) {
1006 let g = tcx.generics_of(def_id);
1007 record!(self.tables.generics_of[def_id] <- g);
1008 record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id));
1009 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1010 if !inferred_outlives.is_empty() {
1011 record!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives);
1014 if let DefKind::Trait | DefKind::TraitAlias = def_kind {
1015 record!(self.tables.super_predicates_of[def_id] <- self.tcx.super_predicates_of(def_id));
1018 let inherent_impls = tcx.crate_inherent_impls(());
1019 for (def_id, implementations) in inherent_impls.inherent_impls.iter() {
1020 if implementations.is_empty() {
1023 record!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| {
1024 assert!(def_id.is_local());
1030 fn encode_item_type(&mut self, def_id: DefId) {
1031 debug!("EncodeContext::encode_item_type({:?})", def_id);
1032 record!(self.tables.type_of[def_id] <- self.tcx.type_of(def_id));
1035 fn encode_enum_variant_info(&mut self, def: ty::AdtDef<'tcx>, index: VariantIdx) {
1037 let variant = &def.variant(index);
1038 let def_id = variant.def_id;
1039 debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
1041 let data = VariantData {
1042 ctor_kind: variant.ctor_kind,
1043 discr: variant.discr,
1044 ctor: variant.ctor_def_id.map(|did| did.index),
1045 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1048 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
1049 self.tables.impl_constness.set(def_id.index, hir::Constness::Const);
1050 record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
1051 assert!(f.did.is_local());
1054 self.encode_ident_span(def_id, variant.ident(tcx));
1055 self.encode_item_type(def_id);
1056 if variant.ctor_kind == CtorKind::Fn {
1057 // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
1058 if let Some(ctor_def_id) = variant.ctor_def_id {
1059 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
1064 fn encode_enum_variant_ctor(&mut self, def: ty::AdtDef<'tcx>, index: VariantIdx) {
1066 let variant = &def.variant(index);
1067 let def_id = variant.ctor_def_id.unwrap();
1068 debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
1070 // FIXME(eddyb) encode only the `CtorKind` for constructors.
1071 let data = VariantData {
1072 ctor_kind: variant.ctor_kind,
1073 discr: variant.discr,
1074 ctor: Some(def_id.index),
1075 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1078 record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
1079 self.tables.impl_constness.set(def_id.index, hir::Constness::Const);
1080 self.encode_item_type(def_id);
1081 if variant.ctor_kind == CtorKind::Fn {
1082 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1086 fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) {
1088 let def_id = local_def_id.to_def_id();
1089 debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
1091 // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1092 // only ever get called for the crate root. We still want to encode
1093 // the crate root for consistency with other crates (some of the resolver
1094 // code uses it). However, we skip encoding anything relating to child
1095 // items - we encode information about proc-macros later on.
1096 let reexports = if !self.is_proc_macro {
1097 match tcx.module_reexports(local_def_id) {
1098 Some(exports) => self.lazy(exports),
1105 record!(self.tables.kind[def_id] <- EntryKind::Mod(reexports));
1106 if self.is_proc_macro {
1107 // Encode this here because we don't do it in encode_def_ids.
1108 record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1110 let direct_children = md.item_ids.iter().map(|item_id| item_id.def_id.local_def_index);
1111 // Foreign items are planted into their parent modules from name resolution point of view.
1113 let foreign_item_children = md
1116 .filter_map(|item_id| match tcx.hir().item(*item_id).kind {
1117 hir::ItemKind::ForeignMod { items, .. } => {
1118 Some(items.iter().map(|fi_ref| fi_ref.id.def_id.local_def_index))
1124 record!(self.tables.children[def_id] <- direct_children.chain(foreign_item_children));
1130 adt_def: ty::AdtDef<'tcx>,
1131 variant_index: VariantIdx,
1134 let variant = &adt_def.variant(variant_index);
1135 let field = &variant.fields[field_index];
1137 let def_id = field.did;
1138 debug!("EncodeContext::encode_field({:?})", def_id);
1140 record!(self.tables.kind[def_id] <- EntryKind::Field);
1141 self.encode_ident_span(def_id, field.ident(self.tcx));
1142 self.encode_item_type(def_id);
1145 fn encode_struct_ctor(&mut self, adt_def: ty::AdtDef<'tcx>, def_id: DefId) {
1146 debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
1148 let variant = adt_def.non_enum_variant();
1150 let data = VariantData {
1151 ctor_kind: variant.ctor_kind,
1152 discr: variant.discr,
1153 ctor: Some(def_id.index),
1154 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1157 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1158 self.tables.impl_constness.set(def_id.index, hir::Constness::Const);
1159 record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data)));
1160 self.encode_item_type(def_id);
1161 if variant.ctor_kind == CtorKind::Fn {
1162 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1166 fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1167 debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1168 let bounds = self.tcx.explicit_item_bounds(def_id);
1169 if !bounds.is_empty() {
1170 record!(self.tables.explicit_item_bounds[def_id] <- bounds);
1174 fn encode_info_for_trait_item(&mut self, def_id: DefId) {
1175 debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
1178 let ast_item = tcx.hir().expect_trait_item(def_id.expect_local());
1179 let trait_item = tcx.associated_item(def_id);
1181 let container = match trait_item.defaultness {
1182 hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
1183 hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
1184 hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
1187 match trait_item.kind {
1188 ty::AssocKind::Const => {
1189 let rendered = rustc_hir_pretty::to_string(
1190 &(&self.tcx.hir() as &dyn intravisit::Map<'_>),
1191 |s| s.print_trait_item(ast_item),
1194 record!(self.tables.kind[def_id] <- EntryKind::AssocConst(container));
1195 record!(self.tables.mir_const_qualif[def_id] <- mir::ConstQualifs::default());
1196 record!(self.tables.rendered_const[def_id] <- rendered);
1198 ty::AssocKind::Fn => {
1199 let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind else { bug!() };
1201 hir::TraitFn::Required(ref names) => {
1202 record!(self.tables.fn_arg_names[def_id] <- *names)
1204 hir::TraitFn::Provided(body) => {
1205 record!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body))
1208 self.tables.asyncness.set(def_id.index, m_sig.header.asyncness);
1209 self.tables.impl_constness.set(def_id.index, hir::Constness::NotConst);
1210 record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData {
1212 has_self: trait_item.fn_has_self_parameter,
1215 ty::AssocKind::Type => {
1216 self.encode_explicit_item_bounds(def_id);
1217 record!(self.tables.kind[def_id] <- EntryKind::AssocType(container));
1220 self.encode_ident_span(def_id, ast_item.ident);
1221 match trait_item.kind {
1222 ty::AssocKind::Const | ty::AssocKind::Fn => {
1223 self.encode_item_type(def_id);
1225 ty::AssocKind::Type => {
1226 if trait_item.defaultness.has_value() {
1227 self.encode_item_type(def_id);
1231 if trait_item.kind == ty::AssocKind::Fn {
1232 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1236 fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1237 debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1240 let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local());
1241 let impl_item = self.tcx.associated_item(def_id);
1243 let container = match impl_item.defaultness {
1244 hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
1245 hir::Defaultness::Final => AssocContainer::ImplFinal,
1246 hir::Defaultness::Default { has_value: false } => {
1247 span_bug!(ast_item.span, "impl items always have values (currently)")
1251 match impl_item.kind {
1252 ty::AssocKind::Const => {
1253 if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
1254 let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
1255 let const_data = self.encode_rendered_const_for_body(body_id);
1257 record!(self.tables.kind[def_id] <- EntryKind::AssocConst(container));
1258 record!(self.tables.mir_const_qualif[def_id] <- qualifs);
1259 record!(self.tables.rendered_const[def_id] <- const_data);
1264 ty::AssocKind::Fn => {
1265 let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind else { bug!() };
1266 self.tables.asyncness.set(def_id.index, sig.header.asyncness);
1267 record!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1268 // Can be inside `impl const Trait`, so using sig.header.constness is not reliable
1269 let constness = if self.tcx.is_const_fn_raw(def_id) {
1270 hir::Constness::Const
1272 hir::Constness::NotConst
1274 self.tables.impl_constness.set(def_id.index, constness);
1275 record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData {
1277 has_self: impl_item.fn_has_self_parameter,
1280 ty::AssocKind::Type => {
1281 record!(self.tables.kind[def_id] <- EntryKind::AssocType(container));
1284 self.encode_ident_span(def_id, impl_item.ident(self.tcx));
1285 self.encode_item_type(def_id);
1286 if let Some(trait_item_def_id) = impl_item.trait_item_def_id {
1287 self.tables.trait_item_def_id.set(def_id.index, trait_item_def_id.into());
1289 if impl_item.kind == ty::AssocKind::Fn {
1290 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1294 fn encode_mir(&mut self) {
1295 if self.is_proc_macro {
1299 let keys_and_jobs = self
1303 .filter_map(|&def_id| {
1304 let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id);
1305 if encode_const || encode_opt {
1306 Some((def_id, encode_const, encode_opt))
1311 .collect::<Vec<_>>();
1312 for (def_id, encode_const, encode_opt) in keys_and_jobs.into_iter() {
1313 debug_assert!(encode_const || encode_opt);
1315 debug!("EntryBuilder::encode_mir({:?})", def_id);
1317 record!(self.tables.optimized_mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id));
1320 record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id));
1322 // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1323 let abstract_const = self.tcx.thir_abstract_const(def_id);
1324 if let Ok(Some(abstract_const)) = abstract_const {
1325 record!(self.tables.thir_abstract_const[def_id.to_def_id()] <- abstract_const);
1328 record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id));
1331 ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id()));
1332 let unused = self.tcx.unused_generic_params(instance);
1333 if !unused.is_empty() {
1334 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1339 fn encode_stability(&mut self, def_id: DefId) {
1340 debug!("EncodeContext::encode_stability({:?})", def_id);
1342 // The query lookup can take a measurable amount of time in crates with many items. Check if
1343 // the stability attributes are even enabled before using their queries.
1344 if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1345 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1346 record!(self.tables.lookup_stability[def_id] <- stab)
1351 fn encode_const_stability(&mut self, def_id: DefId) {
1352 debug!("EncodeContext::encode_const_stability({:?})", def_id);
1354 // The query lookup can take a measurable amount of time in crates with many items. Check if
1355 // the stability attributes are even enabled before using their queries.
1356 if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked {
1357 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1358 record!(self.tables.lookup_const_stability[def_id] <- stab)
1363 fn encode_deprecation(&mut self, def_id: DefId) {
1364 debug!("EncodeContext::encode_deprecation({:?})", def_id);
1365 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1366 record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1370 fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> String {
1371 let hir = self.tcx.hir();
1372 let body = hir.body(body_id);
1373 rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1374 s.print_expr(&body.value)
1378 fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1381 debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1383 self.encode_ident_span(def_id, item.ident);
1385 let entry_kind = match item.kind {
1386 hir::ItemKind::Static(..) => EntryKind::Static,
1387 hir::ItemKind::Const(_, body_id) => {
1388 let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id);
1389 let const_data = self.encode_rendered_const_for_body(body_id);
1390 record!(self.tables.mir_const_qualif[def_id] <- qualifs);
1391 record!(self.tables.rendered_const[def_id] <- const_data);
1394 hir::ItemKind::Fn(ref sig, .., body) => {
1395 self.tables.asyncness.set(def_id.index, sig.header.asyncness);
1396 record!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1397 self.tables.impl_constness.set(def_id.index, sig.header.constness);
1400 hir::ItemKind::Macro(ref macro_def, _) => {
1401 EntryKind::MacroDef(self.lazy(&*macro_def.body), macro_def.macro_rules)
1403 hir::ItemKind::Mod(ref m) => {
1404 return self.encode_info_for_mod(item.def_id, m);
1406 hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod,
1407 hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm,
1408 hir::ItemKind::TyAlias(..) => EntryKind::Type,
1409 hir::ItemKind::OpaqueTy(..) => {
1410 self.encode_explicit_item_bounds(def_id);
1413 hir::ItemKind::Enum(..) => {
1414 let adt_def = self.tcx.adt_def(def_id);
1415 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1418 hir::ItemKind::Struct(ref struct_def, _) => {
1419 let adt_def = self.tcx.adt_def(def_id);
1420 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1421 self.tables.impl_constness.set(def_id.index, hir::Constness::Const);
1423 // Encode def_ids for each field and method
1424 // for methods, write all the stuff get_trait_method
1426 let ctor = struct_def
1428 .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index);
1430 let variant = adt_def.non_enum_variant();
1431 EntryKind::Struct(self.lazy(VariantData {
1432 ctor_kind: variant.ctor_kind,
1433 discr: variant.discr,
1435 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1438 hir::ItemKind::Union(..) => {
1439 let adt_def = self.tcx.adt_def(def_id);
1440 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1442 let variant = adt_def.non_enum_variant();
1443 EntryKind::Union(self.lazy(VariantData {
1444 ctor_kind: variant.ctor_kind,
1445 discr: variant.discr,
1447 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1450 hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => {
1451 self.tables.impl_defaultness.set(def_id.index, defaultness);
1452 self.tables.impl_constness.set(def_id.index, constness);
1454 let trait_ref = self.tcx.impl_trait_ref(def_id);
1455 if let Some(trait_ref) = trait_ref {
1456 let trait_def = self.tcx.trait_def(trait_ref.def_id);
1457 if let Some(mut an) = trait_def.ancestors(self.tcx, def_id).ok() {
1458 if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) {
1459 self.tables.impl_parent.set(def_id.index, parent.into());
1463 // if this is an impl of `CoerceUnsized`, create its
1464 // "unsized info", else just store None
1465 if Some(trait_ref.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1466 let coerce_unsized_info =
1467 self.tcx.at(item.span).coerce_unsized_info(def_id);
1468 record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
1472 let polarity = self.tcx.impl_polarity(def_id);
1473 self.tables.impl_polarity.set(def_id.index, polarity);
1477 hir::ItemKind::Trait(..) => {
1478 let trait_def = self.tcx.trait_def(def_id);
1479 record!(self.tables.trait_def[def_id] <- trait_def);
1483 hir::ItemKind::TraitAlias(..) => {
1484 let trait_def = self.tcx.trait_def(def_id);
1485 record!(self.tables.trait_def[def_id] <- trait_def);
1487 EntryKind::TraitAlias
1489 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {
1490 bug!("cannot encode info for item {:?}", item)
1493 record!(self.tables.kind[def_id] <- entry_kind);
1494 // FIXME(eddyb) there should be a nicer way to do this.
1496 hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <-
1497 self.tcx.adt_def(def_id).variants().iter().map(|v| {
1498 assert!(v.def_id.is_local());
1502 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1503 record!(self.tables.children[def_id] <-
1504 self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1505 assert!(f.did.is_local());
1510 hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1511 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1512 record!(self.tables.children[def_id] <-
1513 associated_item_def_ids.iter().map(|&def_id| {
1514 assert!(def_id.is_local());
1522 hir::ItemKind::Static(..)
1523 | hir::ItemKind::Const(..)
1524 | hir::ItemKind::Fn(..)
1525 | hir::ItemKind::TyAlias(..)
1526 | hir::ItemKind::OpaqueTy(..)
1527 | hir::ItemKind::Enum(..)
1528 | hir::ItemKind::Struct(..)
1529 | hir::ItemKind::Union(..)
1530 | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id),
1533 if let hir::ItemKind::Fn(..) = item.kind {
1534 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1536 if let hir::ItemKind::Impl { .. } = item.kind {
1537 if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1538 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1543 fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
1544 record!(self.tables.kind[def_id] <- kind);
1546 self.encode_item_type(def_id);
1550 fn encode_info_for_closure(&mut self, hir_id: hir::HirId) {
1551 let def_id = self.tcx.hir().local_def_id(hir_id);
1552 debug!("EncodeContext::encode_info_for_closure({:?})", def_id);
1554 // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1555 // including on the signature, which is inferred in `typeck.
1556 let ty = self.tcx.typeck(def_id).node_type(hir_id);
1559 ty::Generator(..) => {
1560 let data = self.tcx.generator_kind(def_id).unwrap();
1561 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Generator);
1562 record!(self.tables.generator_kind[def_id.to_def_id()] <- data);
1565 ty::Closure(..) => {
1566 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Closure);
1569 _ => bug!("closure that is neither generator nor closure"),
1571 self.encode_item_type(def_id.to_def_id());
1572 if let ty::Closure(def_id, substs) = *ty.kind() {
1573 record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig());
1577 fn encode_info_for_anon_const(&mut self, id: hir::HirId) {
1578 let def_id = self.tcx.hir().local_def_id(id);
1579 debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id);
1580 let body_id = self.tcx.hir().body_owned_by(id);
1581 let const_data = self.encode_rendered_const_for_body(body_id);
1582 let qualifs = self.tcx.mir_const_qualif(def_id);
1584 record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst);
1585 record!(self.tables.mir_const_qualif[def_id.to_def_id()] <- qualifs);
1586 record!(self.tables.rendered_const[def_id.to_def_id()] <- const_data);
1587 self.encode_item_type(def_id.to_def_id());
1590 fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> {
1591 empty_proc_macro!(self);
1592 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1593 self.lazy(used_libraries.iter())
1596 fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> {
1597 empty_proc_macro!(self);
1598 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1599 self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned())
1602 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1603 let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1604 let mut expn_data_table: TableBuilder<_, _> = Default::default();
1605 let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1607 let _: Result<(), !> = self.hygiene_ctxt.encode(
1608 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1609 |(this, syntax_contexts, _, _), index, ctxt_data| {
1610 syntax_contexts.set(index, this.lazy(ctxt_data));
1613 |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1614 if let Some(index) = index.as_local() {
1615 expn_data_table.set(index.as_raw(), this.lazy(expn_data));
1616 expn_hash_table.set(index.as_raw(), this.lazy(hash));
1623 syntax_contexts.encode(&mut self.opaque),
1624 expn_data_table.encode(&mut self.opaque),
1625 expn_hash_table.encode(&mut self.opaque),
1629 fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1630 let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1633 let hir = tcx.hir();
1635 let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1636 let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX));
1638 self.lazy(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1639 let spans = self.tcx.sess.parse_sess.proc_macro_quoted_spans();
1640 for (i, span) in spans.into_iter().enumerate() {
1641 let span = self.lazy(span);
1642 self.tables.proc_macro_quoted_spans.set(i, span);
1645 self.tables.opt_def_kind.set(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
1646 record!(self.tables.def_span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1647 record!(self.tables.attributes[LOCAL_CRATE.as_def_id()] <- tcx.get_attrs(LOCAL_CRATE.as_def_id()));
1648 record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- tcx.visibility(LOCAL_CRATE.as_def_id()));
1649 if let Some(stability) = stability {
1650 record!(self.tables.lookup_stability[LOCAL_CRATE.as_def_id()] <- stability);
1652 self.encode_deprecation(LOCAL_CRATE.as_def_id());
1654 // Normally, this information is encoded when we walk the items
1655 // defined in this crate. However, we skip doing that for proc-macro crates,
1656 // so we manually encode just the information that we need
1657 for &proc_macro in &tcx.resolutions(()).proc_macros {
1658 let id = proc_macro;
1659 let proc_macro = hir.local_def_id_to_hir_id(proc_macro);
1660 let mut name = hir.name(proc_macro);
1661 let span = hir.span(proc_macro);
1662 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1663 // so downstream crates need access to them.
1664 let attrs = hir.attrs(proc_macro);
1665 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1667 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1669 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1670 // This unwrap chain should have been checked by the proc-macro harness.
1671 name = attr.meta_item_list().unwrap()[0]
1679 bug!("Unknown proc-macro type for item {:?}", id);
1682 let mut def_key = self.tcx.hir().def_key(id);
1683 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1685 let def_id = id.to_def_id();
1686 self.tables.opt_def_kind.set(def_id.index, DefKind::Macro(macro_kind));
1687 record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind));
1688 record!(self.tables.attributes[def_id] <- attrs);
1689 record!(self.tables.def_keys[def_id] <- def_key);
1690 record!(self.tables.def_ident_span[def_id] <- span);
1691 record!(self.tables.def_span[def_id] <- span);
1692 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1693 if let Some(stability) = stability {
1694 record!(self.tables.lookup_stability[def_id] <- stability);
1698 Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1704 fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> {
1705 empty_proc_macro!(self);
1712 let dep = CrateDep {
1713 name: self.tcx.crate_name(cnum),
1714 hash: self.tcx.crate_hash(cnum),
1715 host_hash: self.tcx.crate_host_hash(cnum),
1716 kind: self.tcx.dep_kind(cnum),
1717 extra_filename: self.tcx.extra_filename(cnum).clone(),
1721 .collect::<Vec<_>>();
1724 // Sanity-check the crate numbers
1725 let mut expected_cnum = 1;
1726 for &(n, _) in &deps {
1727 assert_eq!(n, CrateNum::new(expected_cnum));
1732 // We're just going to write a list of crate 'name-hash-version's, with
1733 // the assumption that they are numbered 1 to n.
1734 // FIXME (#2166): This is not nearly enough to support correct versioning
1735 // but is enough to get transitive crate dependencies working.
1736 self.lazy(deps.iter().map(|&(_, ref dep)| dep))
1739 fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> {
1740 empty_proc_macro!(self);
1742 let lib_features = tcx.lib_features(());
1743 self.lazy(lib_features.to_vec())
1746 fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> {
1747 empty_proc_macro!(self);
1749 let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
1750 self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1753 fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> {
1754 empty_proc_macro!(self);
1756 let lang_items = tcx.lang_items();
1757 let lang_items = lang_items.items().iter();
1758 self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
1759 if let Some(def_id) = opt_def_id {
1760 if def_id.is_local() {
1761 return Some((def_id.index, i));
1768 fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> {
1769 empty_proc_macro!(self);
1771 self.lazy(&tcx.lang_items().missing)
1774 fn encode_traits(&mut self) -> Lazy<[DefIndex]> {
1775 empty_proc_macro!(self);
1776 self.lazy(self.tcx.traits_in_crate(LOCAL_CRATE).iter().map(|def_id| def_id.index))
1779 /// Encodes an index, mapping each trait to its (local) implementations.
1780 fn encode_impls(&mut self) -> Lazy<[TraitImpls]> {
1781 debug!("EncodeContext::encode_traits_and_impls()");
1782 empty_proc_macro!(self);
1784 let mut visitor = ImplsVisitor { tcx, impls: FxHashMap::default() };
1785 tcx.hir().visit_all_item_likes(&mut visitor);
1787 let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
1789 // Bring everything into deterministic order for hashing
1790 all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1792 let all_impls: Vec<_> = all_impls
1794 .map(|(trait_def_id, mut impls)| {
1795 // Bring everything into deterministic order for hashing
1796 impls.sort_by_cached_key(|&(index, _)| {
1797 tcx.hir().def_path_hash(LocalDefId { local_def_index: index })
1801 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1802 impls: self.lazy(&impls),
1807 self.lazy(&all_impls)
1810 fn encode_incoherent_impls(&mut self) -> Lazy<[IncoherentImpls]> {
1811 debug!("EncodeContext::encode_traits_and_impls()");
1812 empty_proc_macro!(self);
1814 let mut ctx = tcx.create_stable_hashing_context();
1815 let mut all_impls: Vec<_> = tcx.crate_inherent_impls(()).incoherent_impls.iter().collect();
1816 all_impls.sort_by_cached_key(|&(&simp, _)| {
1817 let mut hasher = StableHasher::new();
1818 simp.hash_stable(&mut ctx, &mut hasher);
1819 hasher.finish::<Fingerprint>();
1821 let all_impls: Vec<_> = all_impls
1823 .map(|(&simp, impls)| {
1824 let mut impls: Vec<_> =
1825 impls.into_iter().map(|def_id| def_id.local_def_index).collect();
1826 impls.sort_by_cached_key(|&local_def_index| {
1827 tcx.hir().def_path_hash(LocalDefId { local_def_index })
1830 IncoherentImpls { self_ty: simp, impls: self.lazy(impls) }
1834 self.lazy(&all_impls)
1837 // Encodes all symbols exported from this crate into the metadata.
1839 // This pass is seeded off the reachability list calculated in the
1840 // middle::reachable module but filters out items that either don't have a
1841 // symbol associated with them (they weren't translated) or if they're an FFI
1842 // definition (as that's not defined in this crate).
1843 fn encode_exported_symbols(
1845 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)],
1846 ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> {
1847 empty_proc_macro!(self);
1848 // The metadata symbol name is special. It should not show up in
1849 // downstream crates.
1850 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1855 .filter(|&&(ref exported_symbol, _)| match *exported_symbol {
1856 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1863 fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> {
1864 empty_proc_macro!(self);
1865 let formats = self.tcx.dependency_formats(());
1866 for (ty, arr) in formats.iter() {
1867 if *ty != CrateType::Dylib {
1870 return self.lazy(arr.iter().map(|slot| match *slot {
1871 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
1873 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
1874 Linkage::Static => Some(LinkagePreference::RequireStatic),
1880 fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
1883 debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
1886 hir::ForeignItemKind::Fn(_, ref names, _) => {
1887 self.tables.asyncness.set(def_id.index, hir::IsAsync::NotAsync);
1888 record!(self.tables.fn_arg_names[def_id] <- *names);
1889 let constness = if self.tcx.is_const_fn_raw(def_id) {
1890 hir::Constness::Const
1892 hir::Constness::NotConst
1894 self.tables.impl_constness.set(def_id.index, constness);
1895 record!(self.tables.kind[def_id] <- EntryKind::ForeignFn);
1897 hir::ForeignItemKind::Static(..) => {
1898 record!(self.tables.kind[def_id] <- EntryKind::ForeignStatic);
1900 hir::ForeignItemKind::Type => {
1901 record!(self.tables.kind[def_id] <- EntryKind::ForeignType);
1904 self.encode_ident_span(def_id, nitem.ident);
1905 self.encode_item_type(def_id);
1906 if let hir::ForeignItemKind::Fn(..) = nitem.kind {
1907 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1912 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
1913 impl<'a, 'tcx> Visitor<'tcx> for EncodeContext<'a, 'tcx> {
1914 type NestedFilter = nested_filter::OnlyBodies;
1916 fn nested_visit_map(&mut self) -> Self::Map {
1919 fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
1920 intravisit::walk_expr(self, ex);
1921 self.encode_info_for_expr(ex);
1923 fn visit_anon_const(&mut self, c: &'tcx AnonConst) {
1924 intravisit::walk_anon_const(self, c);
1925 self.encode_info_for_anon_const(c.hir_id);
1927 fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
1928 intravisit::walk_item(self, item);
1930 hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
1931 _ => self.encode_info_for_item(item.def_id.to_def_id(), item),
1933 self.encode_addl_info_for_item(item);
1935 fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
1936 intravisit::walk_foreign_item(self, ni);
1937 self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni);
1939 fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
1940 intravisit::walk_generics(self, generics);
1941 self.encode_info_for_generics(generics);
1945 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1946 fn encode_fields(&mut self, adt_def: ty::AdtDef<'tcx>) {
1947 for (variant_index, variant) in adt_def.variants().iter_enumerated() {
1948 for (field_index, _field) in variant.fields.iter().enumerate() {
1949 self.encode_field(adt_def, variant_index, field_index);
1954 fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
1955 for param in generics.params {
1956 let def_id = self.tcx.hir().local_def_id(param.hir_id);
1958 GenericParamKind::Lifetime { .. } => continue,
1959 GenericParamKind::Type { default, .. } => {
1960 self.encode_info_for_generic_param(
1962 EntryKind::TypeParam,
1966 GenericParamKind::Const { ref default, .. } => {
1967 let def_id = def_id.to_def_id();
1968 self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true);
1969 if default.is_some() {
1970 record!(self.tables.const_param_default[def_id] <- self.tcx.const_param_default(def_id))
1977 fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
1978 if let hir::ExprKind::Closure(..) = expr.kind {
1979 self.encode_info_for_closure(expr.hir_id);
1983 fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) {
1984 record!(self.tables.def_ident_span[def_id] <- ident.span);
1987 /// In some cases, along with the item itself, we also
1988 /// encode some sub-items. Usually we want some info from the item
1989 /// so it's easier to do that here then to wait until we would encounter
1990 /// normally in the visitor walk.
1991 fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) {
1993 hir::ItemKind::Static(..)
1994 | hir::ItemKind::Const(..)
1995 | hir::ItemKind::Fn(..)
1996 | hir::ItemKind::Macro(..)
1997 | hir::ItemKind::Mod(..)
1998 | hir::ItemKind::ForeignMod { .. }
1999 | hir::ItemKind::GlobalAsm(..)
2000 | hir::ItemKind::ExternCrate(..)
2001 | hir::ItemKind::Use(..)
2002 | hir::ItemKind::TyAlias(..)
2003 | hir::ItemKind::OpaqueTy(..)
2004 | hir::ItemKind::TraitAlias(..) => {
2005 // no sub-item recording needed in these cases
2007 hir::ItemKind::Enum(..) => {
2008 let def = self.tcx.adt_def(item.def_id.to_def_id());
2009 self.encode_fields(def);
2011 for (i, variant) in def.variants().iter_enumerated() {
2012 self.encode_enum_variant_info(def, i);
2014 if let Some(_ctor_def_id) = variant.ctor_def_id {
2015 self.encode_enum_variant_ctor(def, i);
2019 hir::ItemKind::Struct(ref struct_def, _) => {
2020 let def = self.tcx.adt_def(item.def_id.to_def_id());
2021 self.encode_fields(def);
2023 // If the struct has a constructor, encode it.
2024 if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
2025 let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id);
2026 self.encode_struct_ctor(def, ctor_def_id.to_def_id());
2029 hir::ItemKind::Union(..) => {
2030 let def = self.tcx.adt_def(item.def_id.to_def_id());
2031 self.encode_fields(def);
2033 hir::ItemKind::Impl { .. } => {
2034 for &trait_item_def_id in
2035 self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
2037 self.encode_info_for_impl_item(trait_item_def_id);
2040 hir::ItemKind::Trait(..) => {
2041 for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter()
2043 self.encode_info_for_trait_item(item_def_id);
2050 struct ImplsVisitor<'tcx> {
2052 impls: FxHashMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>>,
2055 impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplsVisitor<'tcx> {
2056 fn visit_item(&mut self, item: &hir::Item<'_>) {
2058 hir::ItemKind::Impl(..) => {
2059 if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) {
2060 let simplified_self_ty = fast_reject::simplify_type(
2062 trait_ref.self_ty(),
2063 TreatParams::AsPlaceholders,
2067 .entry(trait_ref.def_id)
2069 .push((item.def_id.local_def_index, simplified_self_ty));
2076 fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {}
2078 fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) {
2079 // handled in `visit_item` above
2082 fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {}
2085 /// Used to prefetch queries which will be needed later by metadata encoding.
2086 /// Only a subset of the queries are actually prefetched to keep this code smaller.
2087 fn prefetch_mir(tcx: TyCtxt<'_>) {
2088 if !tcx.sess.opts.output_types.should_codegen() {
2089 // We won't emit MIR, so don't prefetch it.
2093 par_iter(tcx.mir_keys(())).for_each(|&def_id| {
2094 let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
2097 tcx.ensure().mir_for_ctfe(def_id);
2100 tcx.ensure().optimized_mir(def_id);
2102 if encode_opt || encode_const {
2103 tcx.ensure().promoted_mir(def_id);
2108 // NOTE(eddyb) The following comment was preserved for posterity, even
2109 // though it's no longer relevant as EBML (which uses nested & tagged
2110 // "documents") was replaced with a scheme that can't go out of bounds.
2112 // And here we run into yet another obscure archive bug: in which metadata
2113 // loaded from archives may have trailing garbage bytes. Awhile back one of
2114 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2115 // and opt) by having ebml generate an out-of-bounds panic when looking at
2118 // Upon investigation it turned out that the metadata file inside of an rlib
2119 // (and ar archive) was being corrupted. Some compilations would generate a
2120 // metadata file which would end in a few extra bytes, while other
2121 // compilations would not have these extra bytes appended to the end. These
2122 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2123 // being interpreted causing the out-of-bounds.
2125 // The root cause of why these extra bytes were appearing was never
2126 // discovered, and in the meantime the solution we're employing is to insert
2127 // the length of the metadata to the start of the metadata. Later on this
2128 // will allow us to slice the metadata to the precise length that we just
2129 // generated regardless of trailing bytes that end up in it.
2131 #[derive(Encodable, Decodable)]
2132 pub struct EncodedMetadata {
2136 impl EncodedMetadata {
2138 pub fn new() -> EncodedMetadata {
2139 EncodedMetadata { raw_data: Vec::new() }
2143 pub fn raw_data(&self) -> &[u8] {
2148 pub fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata {
2149 let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2151 // Since encoding metadata is not in a query, and nothing is cached,
2152 // there's no need to do dep-graph tracking for any of it.
2153 tcx.dep_graph.assert_ignored();
2156 || encode_metadata_impl(tcx),
2158 if tcx.sess.threads() == 1 {
2161 // Prefetch some queries used by metadata encoding.
2162 // This is not necessary for correctness, but is only done for performance reasons.
2163 // It can be removed if it turns out to cause trouble or be detrimental to performance.
2164 join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2170 fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata {
2171 let mut encoder = opaque::Encoder::new(vec![]);
2172 encoder.emit_raw_bytes(METADATA_HEADER).unwrap();
2174 // Will be filled with the root position after encoding everything.
2175 encoder.emit_raw_bytes(&[0, 0, 0, 0]).unwrap();
2177 let source_map_files = tcx.sess.source_map().files();
2178 let source_file_cache = (source_map_files[0].clone(), 0);
2179 let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len()));
2180 drop(source_map_files);
2182 let hygiene_ctxt = HygieneEncodeContext::default();
2184 let mut ecx = EncodeContext {
2187 feat: tcx.features(),
2188 tables: Default::default(),
2189 lazy_state: LazyState::NoNode,
2190 type_shorthands: Default::default(),
2191 predicate_shorthands: Default::default(),
2193 interpret_allocs: Default::default(),
2194 required_source_files,
2195 is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2196 hygiene_ctxt: &hygiene_ctxt,
2199 // Encode the rustc version string in a predictable location.
2200 rustc_version().encode(&mut ecx).unwrap();
2202 // Encode all the entries and extra information in the crate,
2203 // culminating in the `CrateRoot` which points to all of it.
2204 let root = ecx.encode_crate_root();
2206 let mut result = ecx.opaque.into_inner();
2208 // Encode the root position.
2209 let header = METADATA_HEADER.len();
2210 let pos = root.position.get();
2211 result[header + 0] = (pos >> 24) as u8;
2212 result[header + 1] = (pos >> 16) as u8;
2213 result[header + 2] = (pos >> 8) as u8;
2214 result[header + 3] = (pos >> 0) as u8;
2216 // Record metadata size for self-profiling
2217 tcx.prof.artifact_size("crate_metadata", "crate_metadata", result.len() as u64);
2219 EncodedMetadata { raw_data: result }
2222 pub fn provide(providers: &mut Providers) {
2223 *providers = Providers {
2224 traits_in_crate: |tcx, cnum| {
2225 assert_eq!(cnum, LOCAL_CRATE);
2228 struct TraitsVisitor {
2231 impl ItemLikeVisitor<'_> for TraitsVisitor {
2232 fn visit_item(&mut self, item: &hir::Item<'_>) {
2233 if let hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) = item.kind {
2234 self.traits.push(item.def_id.to_def_id());
2237 fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {}
2238 fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {}
2239 fn visit_foreign_item(&mut self, _foreign_item: &hir::ForeignItem<'_>) {}
2242 let mut visitor = TraitsVisitor::default();
2243 tcx.hir().visit_all_item_likes(&mut visitor);
2244 // Bring everything into deterministic order.
2245 visitor.traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id));
2246 tcx.arena.alloc_slice(&visitor.traits)