]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_metadata/src/rmeta/encoder.rs
rustc_metadata: Support non-`Option` nullable values in metadata tables
[rust.git] / compiler / rustc_metadata / src / rmeta / encoder.rs
1 use crate::errors::{FailCreateFileEncoder, FailSeekFile, FailWriteFile};
2 use crate::rmeta::def_path_hash_map::DefPathHashMapRef;
3 use crate::rmeta::table::TableBuilder;
4 use crate::rmeta::*;
5
6 use rustc_ast::Attribute;
7 use rustc_data_structures::fingerprint::Fingerprint;
8 use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
9 use rustc_data_structures::memmap::{Mmap, MmapMut};
10 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
11 use rustc_data_structures::sync::{join, par_iter, Lrc, ParallelIterator};
12 use rustc_data_structures::temp_dir::MaybeTempDir;
13 use rustc_hir as hir;
14 use rustc_hir::def::DefKind;
15 use rustc_hir::def_id::{
16     CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE,
17 };
18 use rustc_hir::definitions::DefPathData;
19 use rustc_hir::intravisit::{self, Visitor};
20 use rustc_hir::lang_items::LangItem;
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, SymbolExportInfo,
25 };
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::fast_reject::{self, SimplifiedType, TreatParams};
30 use rustc_middle::ty::query::Providers;
31 use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt};
32 use rustc_middle::util::common::to_readable_str;
33 use rustc_serialize::{opaque, Decodable, Decoder, Encodable, Encoder};
34 use rustc_session::config::{CrateType, OptLevel};
35 use rustc_session::cstore::{ForeignModule, LinkagePreference, NativeLib};
36 use rustc_span::hygiene::{ExpnIndex, HygieneEncodeContext, MacroKind};
37 use rustc_span::symbol::{sym, Symbol};
38 use rustc_span::{
39     self, DebuggerVisualizerFile, ExternalSource, FileName, SourceFile, Span, SyntaxContext,
40 };
41 use rustc_target::abi::VariantIdx;
42 use std::borrow::Borrow;
43 use std::collections::hash_map::Entry;
44 use std::hash::Hash;
45 use std::io::{Read, Seek, Write};
46 use std::iter;
47 use std::num::NonZeroUsize;
48 use std::path::{Path, PathBuf};
49
50 pub(super) struct EncodeContext<'a, 'tcx> {
51     opaque: opaque::FileEncoder,
52     tcx: TyCtxt<'tcx>,
53     feat: &'tcx rustc_feature::Features,
54
55     tables: TableBuilders,
56
57     lazy_state: LazyState,
58     type_shorthands: FxHashMap<Ty<'tcx>, usize>,
59     predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
60
61     interpret_allocs: FxIndexSet<interpret::AllocId>,
62
63     // This is used to speed up Span encoding.
64     // The `usize` is an index into the `MonotonicVec`
65     // that stores the `SourceFile`
66     source_file_cache: (Lrc<SourceFile>, usize),
67     // The indices (into the `SourceMap`'s `MonotonicVec`)
68     // of all of the `SourceFiles` that we need to serialize.
69     // When we serialize a `Span`, we insert the index of its
70     // `SourceFile` into the `FxIndexSet`.
71     // The order inside the `FxIndexSet` is used as on-disk
72     // order of `SourceFiles`, and encoded inside `Span`s.
73     required_source_files: Option<FxIndexSet<usize>>,
74     is_proc_macro: bool,
75     hygiene_ctxt: &'a HygieneEncodeContext,
76     symbol_table: FxHashMap<Symbol, usize>,
77 }
78
79 /// If the current crate is a proc-macro, returns early with `LazyArray::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 {
83     ($self:ident) => {
84         if $self.is_proc_macro {
85             return LazyArray::empty();
86         }
87     };
88 }
89
90 macro_rules! encoder_methods {
91     ($($name:ident($ty:ty);)*) => {
92         $(fn $name(&mut self, value: $ty) {
93             self.opaque.$name(value)
94         })*
95     }
96 }
97
98 impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
99     encoder_methods! {
100         emit_usize(usize);
101         emit_u128(u128);
102         emit_u64(u64);
103         emit_u32(u32);
104         emit_u16(u16);
105         emit_u8(u8);
106
107         emit_isize(isize);
108         emit_i128(i128);
109         emit_i64(i64);
110         emit_i32(i32);
111         emit_i16(i16);
112         emit_i8(i8);
113
114         emit_bool(bool);
115         emit_f64(f64);
116         emit_f32(f32);
117         emit_char(char);
118         emit_str(&str);
119         emit_raw_bytes(&[u8]);
120     }
121 }
122
123 impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyValue<T> {
124     fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
125         e.emit_lazy_distance(self.position);
126     }
127 }
128
129 impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyArray<T> {
130     fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
131         e.emit_usize(self.num_elems);
132         if self.num_elems > 0 {
133             e.emit_lazy_distance(self.position)
134         }
135     }
136 }
137
138 impl<'a, 'tcx, I, T> Encodable<EncodeContext<'a, 'tcx>> for LazyTable<I, T> {
139     fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
140         e.emit_usize(self.encoded_size);
141         e.emit_lazy_distance(self.position);
142     }
143 }
144
145 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum {
146     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
147         if *self != LOCAL_CRATE && s.is_proc_macro {
148             panic!("Attempted to encode non-local CrateNum {self:?} for proc-macro crate");
149         }
150         s.emit_u32(self.as_u32());
151     }
152 }
153
154 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex {
155     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
156         s.emit_u32(self.as_u32());
157     }
158 }
159
160 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
161     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
162         s.emit_u32(self.as_u32());
163     }
164 }
165
166 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext {
167     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
168         rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s);
169     }
170 }
171
172 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId {
173     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
174         if self.krate == LOCAL_CRATE {
175             // We will only write details for local expansions. Non-local expansions will fetch
176             // data from the corresponding crate's metadata.
177             // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external
178             // metadata from proc-macro crates.
179             s.hygiene_ctxt.schedule_expn_data_for_encoding(*self);
180         }
181         self.krate.encode(s);
182         self.local_id.encode(s);
183     }
184 }
185
186 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span {
187     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
188         let span = self.data();
189
190         // Don't serialize any `SyntaxContext`s from a proc-macro crate,
191         // since we don't load proc-macro dependencies during serialization.
192         // This means that any hygiene information from macros used *within*
193         // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
194         // definition) will be lost.
195         //
196         // This can show up in two ways:
197         //
198         // 1. Any hygiene information associated with identifier of
199         // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
200         // Since proc-macros can only be invoked from a different crate,
201         // real code should never need to care about this.
202         //
203         // 2. Using `Span::def_site` or `Span::mixed_site` will not
204         // include any hygiene information associated with the definition
205         // site. This means that a proc-macro cannot emit a `$crate`
206         // identifier which resolves to one of its dependencies,
207         // which also should never come up in practice.
208         //
209         // Additionally, this affects `Span::parent`, and any other
210         // span inspection APIs that would otherwise allow traversing
211         // the `SyntaxContexts` associated with a span.
212         //
213         // None of these user-visible effects should result in any
214         // cross-crate inconsistencies (getting one behavior in the same
215         // crate, and a different behavior in another crate) due to the
216         // limited surface that proc-macros can expose.
217         //
218         // IMPORTANT: If this is ever changed, be sure to update
219         // `rustc_span::hygiene::raw_encode_expn_id` to handle
220         // encoding `ExpnData` for proc-macro crates.
221         if s.is_proc_macro {
222             SyntaxContext::root().encode(s);
223         } else {
224             span.ctxt.encode(s);
225         }
226
227         if self.is_dummy() {
228             return TAG_PARTIAL_SPAN.encode(s);
229         }
230
231         // The Span infrastructure should make sure that this invariant holds:
232         debug_assert!(span.lo <= span.hi);
233
234         if !s.source_file_cache.0.contains(span.lo) {
235             let source_map = s.tcx.sess.source_map();
236             let source_file_index = source_map.lookup_source_file_idx(span.lo);
237             s.source_file_cache =
238                 (source_map.files()[source_file_index].clone(), source_file_index);
239         }
240         let (ref source_file, source_file_index) = s.source_file_cache;
241         debug_assert!(source_file.contains(span.lo));
242
243         if !source_file.contains(span.hi) {
244             // Unfortunately, macro expansion still sometimes generates Spans
245             // that malformed in this way.
246             return TAG_PARTIAL_SPAN.encode(s);
247         }
248
249         // There are two possible cases here:
250         // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
251         // crate we are writing metadata for. When the metadata for *this* crate gets
252         // deserialized, the deserializer will need to know which crate it originally came
253         // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
254         // be deserialized after the rest of the span data, which tells the deserializer
255         // which crate contains the source map information.
256         // 2. This span comes from our own crate. No special handling is needed - we just
257         // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
258         // our own source map information.
259         //
260         // If we're a proc-macro crate, we always treat this as a local `Span`.
261         // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
262         // if we're a proc-macro crate.
263         // This allows us to avoid loading the dependencies of proc-macro crates: all of
264         // the information we need to decode `Span`s is stored in the proc-macro crate.
265         let (tag, metadata_index) = if source_file.is_imported() && !s.is_proc_macro {
266             // To simplify deserialization, we 'rebase' this span onto the crate it originally came
267             // from (the crate that 'owns' the file it references. These rebased 'lo' and 'hi'
268             // values are relative to the source map information for the 'foreign' crate whose
269             // CrateNum we write into the metadata. This allows `imported_source_files` to binary
270             // search through the 'foreign' crate's source map information, using the
271             // deserialized 'lo' and 'hi' values directly.
272             //
273             // All of this logic ensures that the final result of deserialization is a 'normal'
274             // Span that can be used without any additional trouble.
275             let metadata_index = {
276                 // Introduce a new scope so that we drop the 'lock()' temporary
277                 match &*source_file.external_src.lock() {
278                     ExternalSource::Foreign { metadata_index, .. } => *metadata_index,
279                     src => panic!("Unexpected external source {src:?}"),
280                 }
281             };
282
283             (TAG_VALID_SPAN_FOREIGN, metadata_index)
284         } else {
285             // Record the fact that we need to encode the data for this `SourceFile`
286             let source_files =
287                 s.required_source_files.as_mut().expect("Already encoded SourceMap!");
288             let (metadata_index, _) = source_files.insert_full(source_file_index);
289             let metadata_index: u32 =
290                 metadata_index.try_into().expect("cannot export more than U32_MAX files");
291
292             (TAG_VALID_SPAN_LOCAL, metadata_index)
293         };
294
295         // Encode the start position relative to the file start, so we profit more from the
296         // variable-length integer encoding.
297         let lo = span.lo - source_file.start_pos;
298
299         // Encode length which is usually less than span.hi and profits more
300         // from the variable-length integer encoding that we use.
301         let len = span.hi - span.lo;
302
303         tag.encode(s);
304         lo.encode(s);
305         len.encode(s);
306
307         // Encode the index of the `SourceFile` for the span, in order to make decoding faster.
308         metadata_index.encode(s);
309
310         if tag == TAG_VALID_SPAN_FOREIGN {
311             // This needs to be two lines to avoid holding the `s.source_file_cache`
312             // while calling `cnum.encode(s)`
313             let cnum = s.source_file_cache.0.cnum;
314             cnum.encode(s);
315         }
316     }
317 }
318
319 impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Symbol {
320     fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
321         // if symbol preinterned, emit tag and symbol index
322         if self.is_preinterned() {
323             s.opaque.emit_u8(SYMBOL_PREINTERNED);
324             s.opaque.emit_u32(self.as_u32());
325         } else {
326             // otherwise write it as string or as offset to it
327             match s.symbol_table.entry(*self) {
328                 Entry::Vacant(o) => {
329                     s.opaque.emit_u8(SYMBOL_STR);
330                     let pos = s.opaque.position();
331                     o.insert(pos);
332                     s.emit_str(self.as_str());
333                 }
334                 Entry::Occupied(o) => {
335                     let x = *o.get();
336                     s.emit_u8(SYMBOL_OFFSET);
337                     s.emit_usize(x);
338                 }
339             }
340         }
341     }
342 }
343
344 impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> {
345     const CLEAR_CROSS_CRATE: bool = true;
346
347     type I = TyCtxt<'tcx>;
348
349     fn position(&self) -> usize {
350         self.opaque.position()
351     }
352
353     fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
354         &mut self.type_shorthands
355     }
356
357     fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
358         &mut self.predicate_shorthands
359     }
360
361     fn encode_alloc_id(&mut self, alloc_id: &rustc_middle::mir::interpret::AllocId) {
362         let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
363
364         index.encode(self);
365     }
366 }
367
368 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy_value($value))`, which would
369 // normally need extra variables to avoid errors about multiple mutable borrows.
370 macro_rules! record {
371     ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
372         {
373             let value = $value;
374             let lazy = $self.lazy(value);
375             $self.$tables.$table.set($def_id.index, lazy);
376         }
377     }};
378 }
379
380 // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy_value($value))`, which would
381 // normally need extra variables to avoid errors about multiple mutable borrows.
382 macro_rules! record_array {
383     ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
384         {
385             let value = $value;
386             let lazy = $self.lazy_array(value);
387             $self.$tables.$table.set($def_id.index, lazy);
388         }
389     }};
390 }
391
392 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
393     fn emit_lazy_distance(&mut self, position: NonZeroUsize) {
394         let pos = position.get();
395         let distance = match self.lazy_state {
396             LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
397             LazyState::NodeStart(start) => {
398                 let start = start.get();
399                 assert!(pos <= start);
400                 start - pos
401             }
402             LazyState::Previous(last_pos) => {
403                 assert!(
404                     last_pos <= position,
405                     "make sure that the calls to `lazy*` \
406                      are in the same order as the metadata fields",
407                 );
408                 position.get() - last_pos.get()
409             }
410         };
411         self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap());
412         self.emit_usize(distance);
413     }
414
415     fn lazy<T: ParameterizedOverTcx, B: Borrow<T::Value<'tcx>>>(&mut self, value: B) -> LazyValue<T>
416     where
417         T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
418     {
419         let pos = NonZeroUsize::new(self.position()).unwrap();
420
421         assert_eq!(self.lazy_state, LazyState::NoNode);
422         self.lazy_state = LazyState::NodeStart(pos);
423         value.borrow().encode(self);
424         self.lazy_state = LazyState::NoNode;
425
426         assert!(pos.get() <= self.position());
427
428         LazyValue::from_position(pos)
429     }
430
431     fn lazy_array<T: ParameterizedOverTcx, I: IntoIterator<Item = B>, B: Borrow<T::Value<'tcx>>>(
432         &mut self,
433         values: I,
434     ) -> LazyArray<T>
435     where
436         T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
437     {
438         let pos = NonZeroUsize::new(self.position()).unwrap();
439
440         assert_eq!(self.lazy_state, LazyState::NoNode);
441         self.lazy_state = LazyState::NodeStart(pos);
442         let len = values.into_iter().map(|value| value.borrow().encode(self)).count();
443         self.lazy_state = LazyState::NoNode;
444
445         assert!(pos.get() <= self.position());
446
447         LazyArray::from_position_and_num_elems(pos, len)
448     }
449
450     fn encode_info_for_items(&mut self) {
451         self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module());
452
453         // Proc-macro crates only export proc-macro items, which are looked
454         // up using `proc_macro_data`
455         if self.is_proc_macro {
456             return;
457         }
458
459         self.tcx.hir().visit_all_item_likes_in_crate(self);
460     }
461
462     fn encode_def_path_table(&mut self) {
463         let table = self.tcx.def_path_table();
464         if self.is_proc_macro {
465             for def_index in std::iter::once(CRATE_DEF_INDEX)
466                 .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index))
467             {
468                 let def_key = self.lazy(table.def_key(def_index));
469                 let def_path_hash = table.def_path_hash(def_index);
470                 self.tables.def_keys.set(def_index, def_key);
471                 self.tables.def_path_hashes.set(def_index, def_path_hash);
472             }
473         } else {
474             for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
475                 let def_key = self.lazy(def_key);
476                 self.tables.def_keys.set(def_index, def_key);
477                 self.tables.def_path_hashes.set(def_index, *def_path_hash);
478             }
479         }
480     }
481
482     fn encode_def_path_hash_map(&mut self) -> LazyValue<DefPathHashMapRef<'static>> {
483         self.lazy(DefPathHashMapRef::BorrowedFromTcx(self.tcx.def_path_hash_to_def_index_map()))
484     }
485
486     fn encode_source_map(&mut self) -> LazyTable<u32, Option<LazyValue<rustc_span::SourceFile>>> {
487         let source_map = self.tcx.sess.source_map();
488         let all_source_files = source_map.files();
489
490         // By replacing the `Option` with `None`, we ensure that we can't
491         // accidentally serialize any more `Span`s after the source map encoding
492         // is done.
493         let required_source_files = self.required_source_files.take().unwrap();
494
495         let working_directory = &self.tcx.sess.opts.working_dir;
496
497         let mut adapted = TableBuilder::default();
498
499         // Only serialize `SourceFile`s that were used during the encoding of a `Span`.
500         //
501         // The order in which we encode source files is important here: the on-disk format for
502         // `Span` contains the index of the corresponding `SourceFile`.
503         for (on_disk_index, &source_file_index) in required_source_files.iter().enumerate() {
504             let source_file = &all_source_files[source_file_index];
505             // Don't serialize imported `SourceFile`s, unless we're in a proc-macro crate.
506             assert!(!source_file.is_imported() || self.is_proc_macro);
507
508             // At export time we expand all source file paths to absolute paths because
509             // downstream compilation sessions can have a different compiler working
510             // directory, so relative paths from this or any other upstream crate
511             // won't be valid anymore.
512             //
513             // At this point we also erase the actual on-disk path and only keep
514             // the remapped version -- as is necessary for reproducible builds.
515             let mut source_file = match source_file.name {
516                 FileName::Real(ref original_file_name) => {
517                     let adapted_file_name = source_map
518                         .path_mapping()
519                         .to_embeddable_absolute_path(original_file_name.clone(), working_directory);
520
521                     if adapted_file_name != *original_file_name {
522                         let mut adapted: SourceFile = (**source_file).clone();
523                         adapted.name = FileName::Real(adapted_file_name);
524                         adapted.name_hash = {
525                             let mut hasher: StableHasher = StableHasher::new();
526                             adapted.name.hash(&mut hasher);
527                             hasher.finish::<u128>()
528                         };
529                         Lrc::new(adapted)
530                     } else {
531                         // Nothing to adapt
532                         source_file.clone()
533                     }
534                 }
535                 // expanded code, not from a file
536                 _ => source_file.clone(),
537             };
538
539             // We're serializing this `SourceFile` into our crate metadata,
540             // so mark it as coming from this crate.
541             // This also ensures that we don't try to deserialize the
542             // `CrateNum` for a proc-macro dependency - since proc macro
543             // dependencies aren't loaded when we deserialize a proc-macro,
544             // trying to remap the `CrateNum` would fail.
545             if self.is_proc_macro {
546                 Lrc::make_mut(&mut source_file).cnum = LOCAL_CRATE;
547             }
548
549             let on_disk_index: u32 =
550                 on_disk_index.try_into().expect("cannot export more than U32_MAX files");
551             adapted.set(on_disk_index, self.lazy(source_file));
552         }
553
554         adapted.encode(&mut self.opaque)
555     }
556
557     fn encode_crate_root(&mut self) -> LazyValue<CrateRoot> {
558         let tcx = self.tcx;
559         let mut stats: Vec<(&'static str, usize)> = Vec::with_capacity(32);
560
561         macro_rules! stat {
562             ($label:literal, $f:expr) => {{
563                 let orig_pos = self.position();
564                 let res = $f();
565                 stats.push(($label, self.position() - orig_pos));
566                 res
567             }};
568         }
569
570         // We have already encoded some things. Get their combined size from the current position.
571         stats.push(("preamble", self.position()));
572
573         let (crate_deps, dylib_dependency_formats) =
574             stat!("dep", || (self.encode_crate_deps(), self.encode_dylib_dependency_formats()));
575
576         let lib_features = stat!("lib-features", || self.encode_lib_features());
577
578         let stability_implications =
579             stat!("stability-implications", || self.encode_stability_implications());
580
581         let (lang_items, lang_items_missing) = stat!("lang-items", || {
582             (self.encode_lang_items(), self.encode_lang_items_missing())
583         });
584
585         let diagnostic_items = stat!("diagnostic-items", || self.encode_diagnostic_items());
586
587         let native_libraries = stat!("native-libs", || self.encode_native_libraries());
588
589         let foreign_modules = stat!("foreign-modules", || self.encode_foreign_modules());
590
591         _ = stat!("def-path-table", || self.encode_def_path_table());
592
593         // Encode the def IDs of traits, for rustdoc and diagnostics.
594         let traits = stat!("traits", || self.encode_traits());
595
596         // Encode the def IDs of impls, for coherence checking.
597         let impls = stat!("impls", || self.encode_impls());
598
599         let incoherent_impls = stat!("incoherent-impls", || self.encode_incoherent_impls());
600
601         _ = stat!("mir", || self.encode_mir());
602
603         _ = stat!("items", || {
604             self.encode_def_ids();
605             self.encode_info_for_items();
606         });
607
608         let interpret_alloc_index = stat!("interpret-alloc-index", || {
609             let mut interpret_alloc_index = Vec::new();
610             let mut n = 0;
611             trace!("beginning to encode alloc ids");
612             loop {
613                 let new_n = self.interpret_allocs.len();
614                 // if we have found new ids, serialize those, too
615                 if n == new_n {
616                     // otherwise, abort
617                     break;
618                 }
619                 trace!("encoding {} further alloc ids", new_n - n);
620                 for idx in n..new_n {
621                     let id = self.interpret_allocs[idx];
622                     let pos = self.position() as u32;
623                     interpret_alloc_index.push(pos);
624                     interpret::specialized_encode_alloc_id(self, tcx, id);
625                 }
626                 n = new_n;
627             }
628             self.lazy_array(interpret_alloc_index)
629         });
630
631         // Encode the proc macro data. This affects `tables`, so we need to do this before we
632         // encode the tables. This overwrites def_keys, so it must happen after
633         // encode_def_path_table.
634         let proc_macro_data = stat!("proc-macro-data", || self.encode_proc_macros());
635
636         let tables = stat!("tables", || self.tables.encode(&mut self.opaque));
637
638         let debugger_visualizers =
639             stat!("debugger-visualizers", || self.encode_debugger_visualizers());
640
641         // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
642         // this as late as possible to give the prefetching as much time as possible to complete.
643         let exported_symbols = stat!("exported-symbols", || {
644             self.encode_exported_symbols(&tcx.exported_symbols(LOCAL_CRATE))
645         });
646
647         // Encode the hygiene data.
648         // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The
649         // process of encoding other items (e.g. `optimized_mir`) may cause us to load data from
650         // the incremental cache. If this causes us to deserialize a `Span`, then we may load
651         // additional `SyntaxContext`s into the global `HygieneData`. Therefore, we need to encode
652         // the hygiene data last to ensure that we encode any `SyntaxContext`s that might be used.
653         let (syntax_contexts, expn_data, expn_hashes) = stat!("hygiene", || self.encode_hygiene());
654
655         let def_path_hash_map = stat!("def-path-hash-map", || self.encode_def_path_hash_map());
656
657         // Encode source_map. This needs to be done last, because encoding `Span`s tells us which
658         // `SourceFiles` we actually need to encode.
659         let source_map = stat!("source-map", || self.encode_source_map());
660
661         let root = stat!("final", || {
662             let attrs = tcx.hir().krate_attrs();
663             self.lazy(CrateRoot {
664                 name: tcx.crate_name(LOCAL_CRATE),
665                 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
666                 triple: tcx.sess.opts.target_triple.clone(),
667                 hash: tcx.crate_hash(LOCAL_CRATE),
668                 stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(),
669                 required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
670                 panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
671                 edition: tcx.sess.edition(),
672                 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
673                 has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
674                 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
675                 has_default_lib_allocator: tcx
676                     .sess
677                     .contains_name(&attrs, sym::default_lib_allocator),
678                 proc_macro_data,
679                 debugger_visualizers,
680                 compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins),
681                 needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator),
682                 needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime),
683                 no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins),
684                 panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime),
685                 profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime),
686                 symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
687
688                 crate_deps,
689                 dylib_dependency_formats,
690                 lib_features,
691                 stability_implications,
692                 lang_items,
693                 diagnostic_items,
694                 lang_items_missing,
695                 native_libraries,
696                 foreign_modules,
697                 source_map,
698                 traits,
699                 impls,
700                 incoherent_impls,
701                 exported_symbols,
702                 interpret_alloc_index,
703                 tables,
704                 syntax_contexts,
705                 expn_data,
706                 expn_hashes,
707                 def_path_hash_map,
708             })
709         });
710
711         let total_bytes = self.position();
712
713         let computed_total_bytes: usize = stats.iter().map(|(_, size)| size).sum();
714         assert_eq!(total_bytes, computed_total_bytes);
715
716         if tcx.sess.opts.unstable_opts.meta_stats {
717             self.opaque.flush();
718
719             // Rewind and re-read all the metadata to count the zero bytes we wrote.
720             let pos_before_rewind = self.opaque.file().stream_position().unwrap();
721             let mut zero_bytes = 0;
722             self.opaque.file().rewind().unwrap();
723             let file = std::io::BufReader::new(self.opaque.file());
724             for e in file.bytes() {
725                 if e.unwrap() == 0 {
726                     zero_bytes += 1;
727                 }
728             }
729             assert_eq!(self.opaque.file().stream_position().unwrap(), pos_before_rewind);
730
731             stats.sort_by_key(|&(_, usize)| usize);
732
733             let prefix = "meta-stats";
734             let perc = |bytes| (bytes * 100) as f64 / total_bytes as f64;
735
736             eprintln!("{prefix} METADATA STATS");
737             eprintln!("{} {:<23}{:>10}", prefix, "Section", "Size");
738             eprintln!("{prefix} ----------------------------------------------------------------");
739             for (label, size) in stats {
740                 eprintln!(
741                     "{} {:<23}{:>10} ({:4.1}%)",
742                     prefix,
743                     label,
744                     to_readable_str(size),
745                     perc(size)
746                 );
747             }
748             eprintln!("{prefix} ----------------------------------------------------------------");
749             eprintln!(
750                 "{} {:<23}{:>10} (of which {:.1}% are zero bytes)",
751                 prefix,
752                 "Total",
753                 to_readable_str(total_bytes),
754                 perc(zero_bytes)
755             );
756             eprintln!("{prefix}");
757         }
758
759         root
760     }
761 }
762
763 /// Returns whether an attribute needs to be recorded in metadata, that is, if it's usable and
764 /// useful in downstream crates. Local-only attributes are an obvious example, but some
765 /// rustdoc-specific attributes can equally be of use while documenting the current crate only.
766 ///
767 /// Removing these superfluous attributes speeds up compilation by making the metadata smaller.
768 ///
769 /// Note: the `is_def_id_public` parameter is used to cache whether the given `DefId` has a public
770 /// visibility: this is a piece of data that can be computed once per defid, and not once per
771 /// attribute. Some attributes would only be usable downstream if they are public.
772 #[inline]
773 fn should_encode_attr(
774     tcx: TyCtxt<'_>,
775     attr: &Attribute,
776     def_id: LocalDefId,
777     is_def_id_public: &mut Option<bool>,
778 ) -> bool {
779     if rustc_feature::is_builtin_only_local(attr.name_or_empty()) {
780         // Attributes marked local-only don't need to be encoded for downstream crates.
781         false
782     } else if attr.doc_str().is_some() {
783         // We keep all public doc comments because they might be "imported" into downstream crates
784         // if they use `#[doc(inline)]` to copy an item's documentation into their own.
785         *is_def_id_public.get_or_insert_with(|| tcx.effective_visibilities(()).is_exported(def_id))
786     } else if attr.has_name(sym::doc) {
787         // If this is a `doc` attribute, and it's marked `inline` (as in `#[doc(inline)]`), we can
788         // remove it. It won't be inlinable in downstream crates.
789         attr.meta_item_list().map(|l| l.iter().any(|l| !l.has_name(sym::inline))).unwrap_or(false)
790     } else {
791         true
792     }
793 }
794
795 fn should_encode_visibility(def_kind: DefKind) -> bool {
796     match def_kind {
797         DefKind::Mod
798         | DefKind::Struct
799         | DefKind::Union
800         | DefKind::Enum
801         | DefKind::Variant
802         | DefKind::Trait
803         | DefKind::TyAlias
804         | DefKind::ForeignTy
805         | DefKind::TraitAlias
806         | DefKind::AssocTy
807         | DefKind::Fn
808         | DefKind::Const
809         | DefKind::Static(..)
810         | DefKind::Ctor(..)
811         | DefKind::AssocFn
812         | DefKind::AssocConst
813         | DefKind::Macro(..)
814         | DefKind::Use
815         | DefKind::ForeignMod
816         | DefKind::OpaqueTy
817         | DefKind::ImplTraitPlaceholder
818         | DefKind::Impl
819         | DefKind::Field => true,
820         DefKind::TyParam
821         | DefKind::ConstParam
822         | DefKind::LifetimeParam
823         | DefKind::AnonConst
824         | DefKind::InlineConst
825         | DefKind::GlobalAsm
826         | DefKind::Closure
827         | DefKind::Generator
828         | DefKind::ExternCrate => false,
829     }
830 }
831
832 fn should_encode_stability(def_kind: DefKind) -> bool {
833     match def_kind {
834         DefKind::Mod
835         | DefKind::Ctor(..)
836         | DefKind::Variant
837         | DefKind::Field
838         | DefKind::Struct
839         | DefKind::AssocTy
840         | DefKind::AssocFn
841         | DefKind::AssocConst
842         | DefKind::TyParam
843         | DefKind::ConstParam
844         | DefKind::Static(..)
845         | DefKind::Const
846         | DefKind::Fn
847         | DefKind::ForeignMod
848         | DefKind::TyAlias
849         | DefKind::OpaqueTy
850         | DefKind::ImplTraitPlaceholder
851         | DefKind::Enum
852         | DefKind::Union
853         | DefKind::Impl
854         | DefKind::Trait
855         | DefKind::TraitAlias
856         | DefKind::Macro(..)
857         | DefKind::ForeignTy => true,
858         DefKind::Use
859         | DefKind::LifetimeParam
860         | DefKind::AnonConst
861         | DefKind::InlineConst
862         | DefKind::GlobalAsm
863         | DefKind::Closure
864         | DefKind::Generator
865         | DefKind::ExternCrate => false,
866     }
867 }
868
869 /// Whether we should encode MIR.
870 ///
871 /// Computing, optimizing and encoding the MIR is a relatively expensive operation.
872 /// We want to avoid this work when not required. Therefore:
873 /// - we only compute `mir_for_ctfe` on items with const-eval semantics;
874 /// - we skip `optimized_mir` for check runs.
875 ///
876 /// Return a pair, resp. for CTFE and for LLVM.
877 fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) {
878     match tcx.def_kind(def_id) {
879         // Constructors
880         DefKind::Ctor(_, _) => {
881             let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
882                 || tcx.sess.opts.unstable_opts.always_encode_mir;
883             (true, mir_opt_base)
884         }
885         // Constants
886         DefKind::AnonConst
887         | DefKind::InlineConst
888         | DefKind::AssocConst
889         | DefKind::Static(..)
890         | DefKind::Const => (true, false),
891         // Full-fledged functions + closures
892         DefKind::AssocFn | DefKind::Fn | DefKind::Closure => {
893             let generics = tcx.generics_of(def_id);
894             let needs_inline = (generics.requires_monomorphization(tcx)
895                 || tcx.codegen_fn_attrs(def_id).requests_inline())
896                 && tcx.sess.opts.output_types.should_codegen();
897             // The function has a `const` modifier or is in a `#[const_trait]`.
898             let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id())
899                 || tcx.is_const_default_method(def_id.to_def_id());
900             let always_encode_mir = tcx.sess.opts.unstable_opts.always_encode_mir;
901             (is_const_fn, needs_inline || always_encode_mir)
902         }
903         // Generators require optimized MIR to compute layout.
904         DefKind::Generator => (false, true),
905         // The others don't have MIR.
906         _ => (false, false),
907     }
908 }
909
910 fn should_encode_variances(def_kind: DefKind) -> bool {
911     match def_kind {
912         DefKind::Struct
913         | DefKind::Union
914         | DefKind::Enum
915         | DefKind::Variant
916         | DefKind::OpaqueTy
917         | DefKind::ImplTraitPlaceholder
918         | DefKind::Fn
919         | DefKind::Ctor(..)
920         | DefKind::AssocFn => true,
921         DefKind::Mod
922         | DefKind::Field
923         | DefKind::AssocTy
924         | DefKind::AssocConst
925         | DefKind::TyParam
926         | DefKind::ConstParam
927         | DefKind::Static(..)
928         | DefKind::Const
929         | DefKind::ForeignMod
930         | DefKind::TyAlias
931         | DefKind::Impl
932         | DefKind::Trait
933         | DefKind::TraitAlias
934         | DefKind::Macro(..)
935         | DefKind::ForeignTy
936         | DefKind::Use
937         | DefKind::LifetimeParam
938         | DefKind::AnonConst
939         | DefKind::InlineConst
940         | DefKind::GlobalAsm
941         | DefKind::Closure
942         | DefKind::Generator
943         | DefKind::ExternCrate => false,
944     }
945 }
946
947 fn should_encode_generics(def_kind: DefKind) -> bool {
948     match def_kind {
949         DefKind::Struct
950         | DefKind::Union
951         | DefKind::Enum
952         | DefKind::Variant
953         | DefKind::Trait
954         | DefKind::TyAlias
955         | DefKind::ForeignTy
956         | DefKind::TraitAlias
957         | DefKind::AssocTy
958         | DefKind::Fn
959         | DefKind::Const
960         | DefKind::Static(..)
961         | DefKind::Ctor(..)
962         | DefKind::AssocFn
963         | DefKind::AssocConst
964         | DefKind::AnonConst
965         | DefKind::InlineConst
966         | DefKind::OpaqueTy
967         | DefKind::ImplTraitPlaceholder
968         | DefKind::Impl
969         | DefKind::Field
970         | DefKind::TyParam
971         | DefKind::Closure
972         | DefKind::Generator => true,
973         DefKind::Mod
974         | DefKind::ForeignMod
975         | DefKind::ConstParam
976         | DefKind::Macro(..)
977         | DefKind::Use
978         | DefKind::LifetimeParam
979         | DefKind::GlobalAsm
980         | DefKind::ExternCrate => false,
981     }
982 }
983
984 fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> bool {
985     match def_kind {
986         DefKind::Struct
987         | DefKind::Union
988         | DefKind::Enum
989         | DefKind::Variant
990         | DefKind::Ctor(..)
991         | DefKind::Field
992         | DefKind::Fn
993         | DefKind::Const
994         | DefKind::Static(..)
995         | DefKind::TyAlias
996         | DefKind::OpaqueTy
997         | DefKind::ForeignTy
998         | DefKind::Impl
999         | DefKind::AssocFn
1000         | DefKind::AssocConst
1001         | DefKind::Closure
1002         | DefKind::Generator
1003         | DefKind::ConstParam
1004         | DefKind::AnonConst
1005         | DefKind::InlineConst => true,
1006
1007         DefKind::ImplTraitPlaceholder => {
1008             let parent_def_id = tcx.impl_trait_in_trait_parent(def_id.to_def_id());
1009             let assoc_item = tcx.associated_item(parent_def_id);
1010             match assoc_item.container {
1011                 // Always encode an RPIT in an impl fn, since it always has a body
1012                 ty::AssocItemContainer::ImplContainer => true,
1013                 ty::AssocItemContainer::TraitContainer => {
1014                     // Encode an RPIT for a trait only if the trait has a default body
1015                     assoc_item.defaultness(tcx).has_value()
1016                 }
1017             }
1018         }
1019
1020         DefKind::AssocTy => {
1021             let assoc_item = tcx.associated_item(def_id);
1022             match assoc_item.container {
1023                 ty::AssocItemContainer::ImplContainer => true,
1024                 ty::AssocItemContainer::TraitContainer => assoc_item.defaultness(tcx).has_value(),
1025             }
1026         }
1027         DefKind::TyParam => {
1028             let hir::Node::GenericParam(param) = tcx.hir().get_by_def_id(def_id) else { bug!() };
1029             let hir::GenericParamKind::Type { default, .. } = param.kind else { bug!() };
1030             default.is_some()
1031         }
1032
1033         DefKind::Trait
1034         | DefKind::TraitAlias
1035         | DefKind::Mod
1036         | DefKind::ForeignMod
1037         | DefKind::Macro(..)
1038         | DefKind::Use
1039         | DefKind::LifetimeParam
1040         | DefKind::GlobalAsm
1041         | DefKind::ExternCrate => false,
1042     }
1043 }
1044
1045 fn should_encode_const(def_kind: DefKind) -> bool {
1046     match def_kind {
1047         DefKind::Const | DefKind::AssocConst | DefKind::AnonConst => true,
1048
1049         DefKind::Struct
1050         | DefKind::Union
1051         | DefKind::Enum
1052         | DefKind::Variant
1053         | DefKind::Ctor(..)
1054         | DefKind::Field
1055         | DefKind::Fn
1056         | DefKind::Static(..)
1057         | DefKind::TyAlias
1058         | DefKind::OpaqueTy
1059         | DefKind::ImplTraitPlaceholder
1060         | DefKind::ForeignTy
1061         | DefKind::Impl
1062         | DefKind::AssocFn
1063         | DefKind::Closure
1064         | DefKind::Generator
1065         | DefKind::ConstParam
1066         | DefKind::InlineConst
1067         | DefKind::AssocTy
1068         | DefKind::TyParam
1069         | DefKind::Trait
1070         | DefKind::TraitAlias
1071         | DefKind::Mod
1072         | DefKind::ForeignMod
1073         | DefKind::Macro(..)
1074         | DefKind::Use
1075         | DefKind::LifetimeParam
1076         | DefKind::GlobalAsm
1077         | DefKind::ExternCrate => false,
1078     }
1079 }
1080
1081 fn should_encode_trait_impl_trait_tys(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1082     if tcx.def_kind(def_id) != DefKind::AssocFn {
1083         return false;
1084     }
1085
1086     let Some(item) = tcx.opt_associated_item(def_id) else { return false; };
1087     if item.container != ty::AssocItemContainer::ImplContainer {
1088         return false;
1089     }
1090
1091     let Some(trait_item_def_id) = item.trait_item_def_id else { return false; };
1092
1093     // FIXME(RPITIT): This does a somewhat manual walk through the signature
1094     // of the trait fn to look for any RPITITs, but that's kinda doing a lot
1095     // of work. We can probably remove this when we refactor RPITITs to be
1096     // associated types.
1097     tcx.fn_sig(trait_item_def_id).skip_binder().output().walk().any(|arg| {
1098         if let ty::GenericArgKind::Type(ty) = arg.unpack()
1099             && let ty::Alias(ty::Projection, data) = ty.kind()
1100             && tcx.def_kind(data.def_id) == DefKind::ImplTraitPlaceholder
1101         {
1102             true
1103         } else {
1104             false
1105         }
1106     })
1107 }
1108
1109 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1110     fn encode_attrs(&mut self, def_id: LocalDefId) {
1111         let tcx = self.tcx;
1112         let mut is_public: Option<bool> = None;
1113
1114         let hir_attrs = tcx.hir().attrs(tcx.hir().local_def_id_to_hir_id(def_id));
1115         let mut attrs = hir_attrs
1116             .iter()
1117             .filter(move |attr| should_encode_attr(tcx, attr, def_id, &mut is_public));
1118
1119         record_array!(self.tables.attributes[def_id.to_def_id()] <- attrs.clone());
1120         let mut attr_flags = AttrFlags::empty();
1121         if attrs.any(|attr| attr.may_have_doc_links()) {
1122             attr_flags |= AttrFlags::MAY_HAVE_DOC_LINKS;
1123         }
1124         if hir_attrs
1125             .iter()
1126             .filter(|attr| attr.has_name(sym::doc))
1127             .filter_map(|attr| attr.meta_item_list())
1128             .any(|items| items.iter().any(|item| item.has_name(sym::hidden)))
1129         {
1130             attr_flags |= AttrFlags::IS_DOC_HIDDEN;
1131         }
1132         if !attr_flags.is_empty() {
1133             self.tables.attr_flags.set_nullable(def_id.local_def_index, attr_flags);
1134         }
1135     }
1136
1137     fn encode_def_ids(&mut self) {
1138         if self.is_proc_macro {
1139             return;
1140         }
1141         let tcx = self.tcx;
1142         for local_id in tcx.iter_local_def_id() {
1143             let def_id = local_id.to_def_id();
1144             let def_kind = tcx.opt_def_kind(local_id);
1145             let Some(def_kind) = def_kind else { continue };
1146             self.tables.opt_def_kind.set(def_id.index, def_kind);
1147             let def_span = tcx.def_span(local_id);
1148             record!(self.tables.def_span[def_id] <- def_span);
1149             self.encode_attrs(local_id);
1150             record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
1151             if let Some(ident_span) = tcx.def_ident_span(def_id) {
1152                 record!(self.tables.def_ident_span[def_id] <- ident_span);
1153             }
1154             if def_kind.has_codegen_attrs() {
1155                 record!(self.tables.codegen_fn_attrs[def_id] <- self.tcx.codegen_fn_attrs(def_id));
1156             }
1157             if should_encode_visibility(def_kind) {
1158                 let vis =
1159                     self.tcx.local_visibility(local_id).map_id(|def_id| def_id.local_def_index);
1160                 record!(self.tables.visibility[def_id] <- vis);
1161             }
1162             if should_encode_stability(def_kind) {
1163                 self.encode_stability(def_id);
1164                 self.encode_const_stability(def_id);
1165                 self.encode_default_body_stability(def_id);
1166                 self.encode_deprecation(def_id);
1167             }
1168             if should_encode_variances(def_kind) {
1169                 let v = self.tcx.variances_of(def_id);
1170                 record_array!(self.tables.variances_of[def_id] <- v);
1171             }
1172             if should_encode_generics(def_kind) {
1173                 let g = tcx.generics_of(def_id);
1174                 record!(self.tables.generics_of[def_id] <- g);
1175                 record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id));
1176                 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1177                 if !inferred_outlives.is_empty() {
1178                     record_array!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives);
1179                 }
1180             }
1181             if should_encode_type(tcx, local_id, def_kind) {
1182                 record!(self.tables.type_of[def_id] <- self.tcx.type_of(def_id));
1183             }
1184             if let DefKind::TyParam = def_kind {
1185                 let default = self.tcx.object_lifetime_default(def_id);
1186                 record!(self.tables.object_lifetime_default[def_id] <- default);
1187             }
1188             if let DefKind::Trait | DefKind::TraitAlias = def_kind {
1189                 record!(self.tables.super_predicates_of[def_id] <- self.tcx.super_predicates_of(def_id));
1190             }
1191             if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind {
1192                 let params_in_repr = self.tcx.params_in_repr(def_id);
1193                 record!(self.tables.params_in_repr[def_id] <- params_in_repr);
1194             }
1195             if should_encode_trait_impl_trait_tys(tcx, def_id)
1196                 && let Ok(table) = self.tcx.collect_return_position_impl_trait_in_trait_tys(def_id)
1197             {
1198                 record!(self.tables.trait_impl_trait_tys[def_id] <- table);
1199             }
1200         }
1201         let inherent_impls = tcx.with_stable_hashing_context(|hcx| {
1202             tcx.crate_inherent_impls(()).inherent_impls.to_sorted(&hcx, true)
1203         });
1204
1205         for (def_id, implementations) in inherent_impls {
1206             if implementations.is_empty() {
1207                 continue;
1208             }
1209             record_array!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| {
1210                 assert!(def_id.is_local());
1211                 def_id.index
1212             }));
1213         }
1214     }
1215
1216     fn encode_enum_variant_info(&mut self, def: ty::AdtDef<'tcx>, index: VariantIdx) {
1217         let tcx = self.tcx;
1218         let variant = &def.variant(index);
1219         let def_id = variant.def_id;
1220         debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
1221
1222         let data = VariantData {
1223             discr: variant.discr,
1224             ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)),
1225             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1226         };
1227
1228         record!(self.tables.variant_data[def_id] <- data);
1229         self.tables.constness.set(def_id.index, hir::Constness::Const);
1230         record_array!(self.tables.children[def_id] <- variant.fields.iter().map(|f| {
1231             assert!(f.did.is_local());
1232             f.did.index
1233         }));
1234         if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
1235             // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
1236             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
1237         }
1238     }
1239
1240     fn encode_enum_variant_ctor(&mut self, def: ty::AdtDef<'tcx>, index: VariantIdx) {
1241         let variant = &def.variant(index);
1242         let Some((ctor_kind, def_id)) = variant.ctor else { return };
1243         debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
1244
1245         // FIXME(eddyb) encode only the `CtorKind` for constructors.
1246         let data = VariantData {
1247             discr: variant.discr,
1248             ctor: Some((ctor_kind, def_id.index)),
1249             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1250         };
1251
1252         record!(self.tables.variant_data[def_id] <- data);
1253         self.tables.constness.set(def_id.index, hir::Constness::Const);
1254         if ctor_kind == CtorKind::Fn {
1255             record!(self.tables.fn_sig[def_id] <- self.tcx.fn_sig(def_id));
1256         }
1257     }
1258
1259     fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) {
1260         let tcx = self.tcx;
1261         let def_id = local_def_id.to_def_id();
1262         debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
1263
1264         // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1265         // only ever get called for the crate root. We still want to encode
1266         // the crate root for consistency with other crates (some of the resolver
1267         // code uses it). However, we skip encoding anything relating to child
1268         // items - we encode information about proc-macros later on.
1269         if self.is_proc_macro {
1270             // Encode this here because we don't do it in encode_def_ids.
1271             record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1272         } else {
1273             record_array!(self.tables.children[def_id] <- iter::from_generator(|| {
1274                 for item_id in md.item_ids {
1275                     match tcx.hir().item(*item_id).kind {
1276                         // Foreign items are planted into their parent modules
1277                         // from name resolution point of view.
1278                         hir::ItemKind::ForeignMod { items, .. } => {
1279                             for foreign_item in items {
1280                                 yield foreign_item.id.owner_id.def_id.local_def_index;
1281                             }
1282                         }
1283                         // Only encode named non-reexport children, reexports are encoded
1284                         // separately and unnamed items are not used by name resolution.
1285                         hir::ItemKind::ExternCrate(..) => continue,
1286                         hir::ItemKind::Struct(ref vdata, _) => {
1287                             yield item_id.owner_id.def_id.local_def_index;
1288                             // Encode constructors which take a separate slot in value namespace.
1289                             if let Some(ctor_hir_id) = vdata.ctor_hir_id() {
1290                                 yield tcx.hir().local_def_id(ctor_hir_id).local_def_index;
1291                             }
1292                         }
1293                         _ if tcx.def_key(item_id.owner_id.to_def_id()).get_opt_name().is_some() => {
1294                             yield item_id.owner_id.def_id.local_def_index;
1295                         }
1296                         _ => continue,
1297                     }
1298                 }
1299             }));
1300
1301             if let Some(reexports) = tcx.module_reexports(local_def_id) {
1302                 assert!(!reexports.is_empty());
1303                 record_array!(self.tables.module_reexports[def_id] <- reexports);
1304             }
1305         }
1306     }
1307
1308     fn encode_struct_ctor(&mut self, adt_def: ty::AdtDef<'tcx>) {
1309         let variant = adt_def.non_enum_variant();
1310         let Some((ctor_kind, def_id)) = variant.ctor else { return };
1311         debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
1312
1313         let data = VariantData {
1314             discr: variant.discr,
1315             ctor: Some((ctor_kind, def_id.index)),
1316             is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1317         };
1318
1319         record!(self.tables.repr_options[def_id] <- adt_def.repr());
1320         record!(self.tables.variant_data[def_id] <- data);
1321         self.tables.constness.set(def_id.index, hir::Constness::Const);
1322         if ctor_kind == CtorKind::Fn {
1323             record!(self.tables.fn_sig[def_id] <- self.tcx.fn_sig(def_id));
1324         }
1325     }
1326
1327     fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1328         debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1329         let bounds = self.tcx.explicit_item_bounds(def_id);
1330         if !bounds.is_empty() {
1331             record_array!(self.tables.explicit_item_bounds[def_id] <- bounds);
1332         }
1333     }
1334
1335     fn encode_info_for_trait_item(&mut self, def_id: DefId) {
1336         debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
1337         let tcx = self.tcx;
1338
1339         let impl_defaultness = tcx.impl_defaultness(def_id.expect_local());
1340         self.tables.impl_defaultness.set(def_id.index, impl_defaultness);
1341         let trait_item = tcx.associated_item(def_id);
1342         self.tables.assoc_container.set(def_id.index, trait_item.container);
1343
1344         match trait_item.kind {
1345             ty::AssocKind::Const => {}
1346             ty::AssocKind::Fn => {
1347                 record_array!(self.tables.fn_arg_names[def_id] <- tcx.fn_arg_names(def_id));
1348                 self.tables.asyncness.set(def_id.index, tcx.asyncness(def_id));
1349                 self.tables.constness.set(def_id.index, hir::Constness::NotConst);
1350             }
1351             ty::AssocKind::Type => {
1352                 self.encode_explicit_item_bounds(def_id);
1353             }
1354         }
1355         if trait_item.kind == ty::AssocKind::Fn {
1356             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1357         }
1358     }
1359
1360     fn encode_info_for_impl_item(&mut self, def_id: DefId) {
1361         debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
1362         let tcx = self.tcx;
1363
1364         let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local());
1365         self.tables.impl_defaultness.set(def_id.index, ast_item.defaultness);
1366         let impl_item = self.tcx.associated_item(def_id);
1367         self.tables.assoc_container.set(def_id.index, impl_item.container);
1368
1369         match impl_item.kind {
1370             ty::AssocKind::Fn => {
1371                 let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind else { bug!() };
1372                 self.tables.asyncness.set(def_id.index, sig.header.asyncness);
1373                 record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1374                 // Can be inside `impl const Trait`, so using sig.header.constness is not reliable
1375                 let constness = if self.tcx.is_const_fn_raw(def_id) {
1376                     hir::Constness::Const
1377                 } else {
1378                     hir::Constness::NotConst
1379                 };
1380                 self.tables.constness.set(def_id.index, constness);
1381             }
1382             ty::AssocKind::Const | ty::AssocKind::Type => {}
1383         }
1384         if let Some(trait_item_def_id) = impl_item.trait_item_def_id {
1385             self.tables.trait_item_def_id.set(def_id.index, trait_item_def_id.into());
1386         }
1387         if impl_item.kind == ty::AssocKind::Fn {
1388             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1389             if tcx.is_intrinsic(def_id) {
1390                 self.tables.is_intrinsic.set_nullable(def_id.index, true);
1391             }
1392         }
1393     }
1394
1395     fn encode_mir(&mut self) {
1396         if self.is_proc_macro {
1397             return;
1398         }
1399
1400         let tcx = self.tcx;
1401
1402         let keys_and_jobs = tcx.mir_keys(()).iter().filter_map(|&def_id| {
1403             let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
1404             if encode_const || encode_opt { Some((def_id, encode_const, encode_opt)) } else { None }
1405         });
1406         for (def_id, encode_const, encode_opt) in keys_and_jobs {
1407             debug_assert!(encode_const || encode_opt);
1408
1409             debug!("EntryBuilder::encode_mir({:?})", def_id);
1410             if encode_opt {
1411                 record!(self.tables.optimized_mir[def_id.to_def_id()] <- tcx.optimized_mir(def_id));
1412             }
1413             if encode_const {
1414                 record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- tcx.mir_for_ctfe(def_id));
1415
1416                 // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1417                 let abstract_const = tcx.thir_abstract_const(def_id);
1418                 if let Ok(Some(abstract_const)) = abstract_const {
1419                     record!(self.tables.thir_abstract_const[def_id.to_def_id()] <- abstract_const);
1420                 }
1421
1422                 if should_encode_const(tcx.def_kind(def_id)) {
1423                     let qualifs = tcx.mir_const_qualif(def_id);
1424                     record!(self.tables.mir_const_qualif[def_id.to_def_id()] <- qualifs);
1425                     let body_id = tcx.hir().maybe_body_owned_by(def_id);
1426                     if let Some(body_id) = body_id {
1427                         let const_data = self.encode_rendered_const_for_body(body_id);
1428                         record!(self.tables.rendered_const[def_id.to_def_id()] <- const_data);
1429                     }
1430                 }
1431             }
1432             record!(self.tables.promoted_mir[def_id.to_def_id()] <- tcx.promoted_mir(def_id));
1433
1434             let instance =
1435                 ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id()));
1436             let unused = tcx.unused_generic_params(instance);
1437             if !unused.all_used() {
1438                 record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused);
1439             }
1440         }
1441
1442         // Encode all the deduced parameter attributes for everything that has MIR, even for items
1443         // that can't be inlined. But don't if we aren't optimizing in non-incremental mode, to
1444         // save the query traffic.
1445         if tcx.sess.opts.output_types.should_codegen()
1446             && tcx.sess.opts.optimize != OptLevel::No
1447             && tcx.sess.opts.incremental.is_none()
1448         {
1449             for &local_def_id in tcx.mir_keys(()) {
1450                 if let DefKind::AssocFn | DefKind::Fn = tcx.def_kind(local_def_id) {
1451                     record_array!(self.tables.deduced_param_attrs[local_def_id.to_def_id()] <-
1452                         self.tcx.deduced_param_attrs(local_def_id.to_def_id()));
1453                 }
1454             }
1455         }
1456     }
1457
1458     fn encode_stability(&mut self, def_id: DefId) {
1459         debug!("EncodeContext::encode_stability({:?})", def_id);
1460
1461         // The query lookup can take a measurable amount of time in crates with many items. Check if
1462         // the stability attributes are even enabled before using their queries.
1463         if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1464             if let Some(stab) = self.tcx.lookup_stability(def_id) {
1465                 record!(self.tables.lookup_stability[def_id] <- stab)
1466             }
1467         }
1468     }
1469
1470     fn encode_const_stability(&mut self, def_id: DefId) {
1471         debug!("EncodeContext::encode_const_stability({:?})", def_id);
1472
1473         // The query lookup can take a measurable amount of time in crates with many items. Check if
1474         // the stability attributes are even enabled before using their queries.
1475         if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1476             if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1477                 record!(self.tables.lookup_const_stability[def_id] <- stab)
1478             }
1479         }
1480     }
1481
1482     fn encode_default_body_stability(&mut self, def_id: DefId) {
1483         debug!("EncodeContext::encode_default_body_stability({:?})", def_id);
1484
1485         // The query lookup can take a measurable amount of time in crates with many items. Check if
1486         // the stability attributes are even enabled before using their queries.
1487         if self.feat.staged_api || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1488             if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
1489                 record!(self.tables.lookup_default_body_stability[def_id] <- stab)
1490             }
1491         }
1492     }
1493
1494     fn encode_deprecation(&mut self, def_id: DefId) {
1495         debug!("EncodeContext::encode_deprecation({:?})", def_id);
1496         if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1497             record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1498         }
1499     }
1500
1501     fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> String {
1502         let hir = self.tcx.hir();
1503         let body = hir.body(body_id);
1504         rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| {
1505             s.print_expr(&body.value)
1506         })
1507     }
1508
1509     fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) {
1510         let tcx = self.tcx;
1511
1512         debug!("EncodeContext::encode_info_for_item({:?})", def_id);
1513
1514         match item.kind {
1515             hir::ItemKind::Fn(ref sig, .., body) => {
1516                 self.tables.asyncness.set(def_id.index, sig.header.asyncness);
1517                 record_array!(self.tables.fn_arg_names[def_id] <- self.tcx.hir().body_param_names(body));
1518                 self.tables.constness.set(def_id.index, sig.header.constness);
1519             }
1520             hir::ItemKind::Macro(ref macro_def, _) => {
1521                 if macro_def.macro_rules {
1522                     self.tables.is_macro_rules.set_nullable(def_id.index, true);
1523                 }
1524                 record!(self.tables.macro_definition[def_id] <- &*macro_def.body);
1525             }
1526             hir::ItemKind::Mod(ref m) => {
1527                 return self.encode_info_for_mod(item.owner_id.def_id, m);
1528             }
1529             hir::ItemKind::OpaqueTy(ref opaque) => {
1530                 self.encode_explicit_item_bounds(def_id);
1531                 if matches!(opaque.origin, hir::OpaqueTyOrigin::TyAlias) {
1532                     self.tables.is_type_alias_impl_trait.set_nullable(def_id.index, true);
1533                 }
1534             }
1535             hir::ItemKind::Enum(..) => {
1536                 let adt_def = self.tcx.adt_def(def_id);
1537                 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1538             }
1539             hir::ItemKind::Struct(..) => {
1540                 let adt_def = self.tcx.adt_def(def_id);
1541                 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1542                 self.tables.constness.set(def_id.index, hir::Constness::Const);
1543
1544                 let variant = adt_def.non_enum_variant();
1545                 record!(self.tables.variant_data[def_id] <- VariantData {
1546                     discr: variant.discr,
1547                     ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)),
1548                     is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1549                 });
1550             }
1551             hir::ItemKind::Union(..) => {
1552                 let adt_def = self.tcx.adt_def(def_id);
1553                 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1554
1555                 let variant = adt_def.non_enum_variant();
1556                 record!(self.tables.variant_data[def_id] <- VariantData {
1557                     discr: variant.discr,
1558                     ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)),
1559                     is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1560                 });
1561             }
1562             hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => {
1563                 self.tables.impl_defaultness.set(def_id.index, *defaultness);
1564                 self.tables.constness.set(def_id.index, *constness);
1565
1566                 let trait_ref = self.tcx.impl_trait_ref(def_id).map(ty::EarlyBinder::skip_binder);
1567                 if let Some(trait_ref) = trait_ref {
1568                     let trait_def = self.tcx.trait_def(trait_ref.def_id);
1569                     if let Ok(mut an) = trait_def.ancestors(self.tcx, def_id) {
1570                         if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) {
1571                             self.tables.impl_parent.set(def_id.index, parent.into());
1572                         }
1573                     }
1574
1575                     // if this is an impl of `CoerceUnsized`, create its
1576                     // "unsized info", else just store None
1577                     if Some(trait_ref.def_id) == self.tcx.lang_items().coerce_unsized_trait() {
1578                         let coerce_unsized_info =
1579                             self.tcx.at(item.span).coerce_unsized_info(def_id);
1580                         record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
1581                     }
1582                 }
1583
1584                 let polarity = self.tcx.impl_polarity(def_id);
1585                 self.tables.impl_polarity.set(def_id.index, polarity);
1586             }
1587             hir::ItemKind::Trait(..) => {
1588                 let trait_def = self.tcx.trait_def(def_id);
1589                 record!(self.tables.trait_def[def_id] <- trait_def);
1590             }
1591             hir::ItemKind::TraitAlias(..) => {
1592                 let trait_def = self.tcx.trait_def(def_id);
1593                 record!(self.tables.trait_def[def_id] <- trait_def);
1594             }
1595             hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {
1596                 bug!("cannot encode info for item {:?}", item)
1597             }
1598             hir::ItemKind::Static(..)
1599             | hir::ItemKind::Const(..)
1600             | hir::ItemKind::ForeignMod { .. }
1601             | hir::ItemKind::GlobalAsm(..)
1602             | hir::ItemKind::TyAlias(..) => {}
1603         };
1604         // FIXME(eddyb) there should be a nicer way to do this.
1605         match item.kind {
1606             hir::ItemKind::Enum(..) => {
1607                 record_array!(self.tables.children[def_id] <- iter::from_generator(||
1608                     for variant in tcx.adt_def(def_id).variants() {
1609                         yield variant.def_id.index;
1610                         // Encode constructors which take a separate slot in value namespace.
1611                         if let Some(ctor_def_id) = variant.ctor_def_id() {
1612                             yield ctor_def_id.index;
1613                         }
1614                     }
1615                 ))
1616             }
1617             hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => {
1618                 record_array!(self.tables.children[def_id] <-
1619                     self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| {
1620                         assert!(f.did.is_local());
1621                         f.did.index
1622                     })
1623                 )
1624             }
1625             hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => {
1626                 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1627                 record_array!(self.tables.children[def_id] <-
1628                     associated_item_def_ids.iter().map(|&def_id| {
1629                         assert!(def_id.is_local());
1630                         def_id.index
1631                     })
1632                 );
1633             }
1634             _ => {}
1635         }
1636         if let hir::ItemKind::Fn(..) = item.kind {
1637             record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1638             if tcx.is_intrinsic(def_id) {
1639                 self.tables.is_intrinsic.set_nullable(def_id.index, true);
1640             }
1641         }
1642         if let hir::ItemKind::Impl { .. } = item.kind {
1643             if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) {
1644                 record!(self.tables.impl_trait_ref[def_id] <- trait_ref);
1645             }
1646         }
1647         // In some cases, along with the item itself, we also
1648         // encode some sub-items. Usually we want some info from the item
1649         // so it's easier to do that here then to wait until we would encounter
1650         // normally in the visitor walk.
1651         match item.kind {
1652             hir::ItemKind::Enum(..) => {
1653                 let def = self.tcx.adt_def(item.owner_id.to_def_id());
1654                 for (i, _) in def.variants().iter_enumerated() {
1655                     self.encode_enum_variant_info(def, i);
1656                     self.encode_enum_variant_ctor(def, i);
1657                 }
1658             }
1659             hir::ItemKind::Struct(..) => {
1660                 let def = self.tcx.adt_def(item.owner_id.to_def_id());
1661                 self.encode_struct_ctor(def);
1662             }
1663             hir::ItemKind::Impl { .. } => {
1664                 for &trait_item_def_id in
1665                     self.tcx.associated_item_def_ids(item.owner_id.to_def_id()).iter()
1666                 {
1667                     self.encode_info_for_impl_item(trait_item_def_id);
1668                 }
1669             }
1670             hir::ItemKind::Trait(..) => {
1671                 for &item_def_id in
1672                     self.tcx.associated_item_def_ids(item.owner_id.to_def_id()).iter()
1673                 {
1674                     self.encode_info_for_trait_item(item_def_id);
1675                 }
1676             }
1677             _ => {}
1678         }
1679     }
1680
1681     #[instrument(level = "debug", skip(self))]
1682     fn encode_info_for_closure(&mut self, def_id: LocalDefId) {
1683         // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic,
1684         // including on the signature, which is inferred in `typeck.
1685         let typeck_result: &'tcx ty::TypeckResults<'tcx> = self.tcx.typeck(def_id);
1686         let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
1687         let ty = typeck_result.node_type(hir_id);
1688         match ty.kind() {
1689             ty::Generator(..) => {
1690                 let data = self.tcx.generator_kind(def_id).unwrap();
1691                 let generator_diagnostic_data = typeck_result.get_generator_diagnostic_data();
1692                 record!(self.tables.generator_kind[def_id.to_def_id()] <- data);
1693                 record!(self.tables.generator_diagnostic_data[def_id.to_def_id()]  <- generator_diagnostic_data);
1694             }
1695
1696             ty::Closure(_, substs) => {
1697                 let constness = self.tcx.constness(def_id.to_def_id());
1698                 self.tables.constness.set(def_id.to_def_id().index, constness);
1699                 record!(self.tables.fn_sig[def_id.to_def_id()] <- substs.as_closure().sig());
1700             }
1701
1702             _ => bug!("closure that is neither generator nor closure"),
1703         }
1704     }
1705
1706     fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
1707         empty_proc_macro!(self);
1708         let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1709         self.lazy_array(used_libraries.iter())
1710     }
1711
1712     fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
1713         empty_proc_macro!(self);
1714         let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1715         self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
1716     }
1717
1718     fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1719         let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1720         let mut expn_data_table: TableBuilder<_, _> = Default::default();
1721         let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1722
1723         self.hygiene_ctxt.encode(
1724             &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1725             |(this, syntax_contexts, _, _), index, ctxt_data| {
1726                 syntax_contexts.set(index, this.lazy(ctxt_data));
1727             },
1728             |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1729                 if let Some(index) = index.as_local() {
1730                     expn_data_table.set(index.as_raw(), this.lazy(expn_data));
1731                     expn_hash_table.set(index.as_raw(), this.lazy(hash));
1732                 }
1733             },
1734         );
1735
1736         (
1737             syntax_contexts.encode(&mut self.opaque),
1738             expn_data_table.encode(&mut self.opaque),
1739             expn_hash_table.encode(&mut self.opaque),
1740         )
1741     }
1742
1743     fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1744         let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro);
1745         if is_proc_macro {
1746             let tcx = self.tcx;
1747             let hir = tcx.hir();
1748
1749             let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1750             let stability = tcx.lookup_stability(CRATE_DEF_ID);
1751             let macros =
1752                 self.lazy_array(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1753             let spans = self.tcx.sess.parse_sess.proc_macro_quoted_spans();
1754             for (i, span) in spans.into_iter().enumerate() {
1755                 let span = self.lazy(span);
1756                 self.tables.proc_macro_quoted_spans.set(i, span);
1757             }
1758
1759             self.tables.opt_def_kind.set(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
1760             record!(self.tables.def_span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1761             self.encode_attrs(LOCAL_CRATE.as_def_id().expect_local());
1762             let vis = tcx.local_visibility(CRATE_DEF_ID).map_id(|def_id| def_id.local_def_index);
1763             record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- vis);
1764             if let Some(stability) = stability {
1765                 record!(self.tables.lookup_stability[LOCAL_CRATE.as_def_id()] <- stability);
1766             }
1767             self.encode_deprecation(LOCAL_CRATE.as_def_id());
1768
1769             // Normally, this information is encoded when we walk the items
1770             // defined in this crate. However, we skip doing that for proc-macro crates,
1771             // so we manually encode just the information that we need
1772             for &proc_macro in &tcx.resolutions(()).proc_macros {
1773                 let id = proc_macro;
1774                 let proc_macro = hir.local_def_id_to_hir_id(proc_macro);
1775                 let mut name = hir.name(proc_macro);
1776                 let span = hir.span(proc_macro);
1777                 // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1778                 // so downstream crates need access to them.
1779                 let attrs = hir.attrs(proc_macro);
1780                 let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) {
1781                     MacroKind::Bang
1782                 } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) {
1783                     MacroKind::Attr
1784                 } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) {
1785                     // This unwrap chain should have been checked by the proc-macro harness.
1786                     name = attr.meta_item_list().unwrap()[0]
1787                         .meta_item()
1788                         .unwrap()
1789                         .ident()
1790                         .unwrap()
1791                         .name;
1792                     MacroKind::Derive
1793                 } else {
1794                     bug!("Unknown proc-macro type for item {:?}", id);
1795                 };
1796
1797                 let mut def_key = self.tcx.hir().def_key(id);
1798                 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1799
1800                 let def_id = id.to_def_id();
1801                 self.tables.opt_def_kind.set(def_id.index, DefKind::Macro(macro_kind));
1802                 self.tables.proc_macro.set(def_id.index, macro_kind);
1803                 self.encode_attrs(id);
1804                 record!(self.tables.def_keys[def_id] <- def_key);
1805                 record!(self.tables.def_ident_span[def_id] <- span);
1806                 record!(self.tables.def_span[def_id] <- span);
1807                 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1808                 if let Some(stability) = stability {
1809                     record!(self.tables.lookup_stability[def_id] <- stability);
1810                 }
1811             }
1812
1813             Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1814         } else {
1815             None
1816         }
1817     }
1818
1819     fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
1820         empty_proc_macro!(self);
1821         self.lazy_array(self.tcx.debugger_visualizers(LOCAL_CRATE).iter())
1822     }
1823
1824     fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
1825         empty_proc_macro!(self);
1826
1827         let deps = self
1828             .tcx
1829             .crates(())
1830             .iter()
1831             .map(|&cnum| {
1832                 let dep = CrateDep {
1833                     name: self.tcx.crate_name(cnum),
1834                     hash: self.tcx.crate_hash(cnum),
1835                     host_hash: self.tcx.crate_host_hash(cnum),
1836                     kind: self.tcx.dep_kind(cnum),
1837                     extra_filename: self.tcx.extra_filename(cnum).clone(),
1838                 };
1839                 (cnum, dep)
1840             })
1841             .collect::<Vec<_>>();
1842
1843         {
1844             // Sanity-check the crate numbers
1845             let mut expected_cnum = 1;
1846             for &(n, _) in &deps {
1847                 assert_eq!(n, CrateNum::new(expected_cnum));
1848                 expected_cnum += 1;
1849             }
1850         }
1851
1852         // We're just going to write a list of crate 'name-hash-version's, with
1853         // the assumption that they are numbered 1 to n.
1854         // FIXME (#2166): This is not nearly enough to support correct versioning
1855         // but is enough to get transitive crate dependencies working.
1856         self.lazy_array(deps.iter().map(|(_, dep)| dep))
1857     }
1858
1859     fn encode_lib_features(&mut self) -> LazyArray<(Symbol, Option<Symbol>)> {
1860         empty_proc_macro!(self);
1861         let tcx = self.tcx;
1862         let lib_features = tcx.lib_features(());
1863         self.lazy_array(lib_features.to_vec())
1864     }
1865
1866     fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
1867         empty_proc_macro!(self);
1868         let tcx = self.tcx;
1869         let implications = tcx.stability_implications(LOCAL_CRATE);
1870         self.lazy_array(implications.iter().map(|(k, v)| (*k, *v)))
1871     }
1872
1873     fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, DefIndex)> {
1874         empty_proc_macro!(self);
1875         let tcx = self.tcx;
1876         let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
1877         self.lazy_array(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
1878     }
1879
1880     fn encode_lang_items(&mut self) -> LazyArray<(DefIndex, LangItem)> {
1881         empty_proc_macro!(self);
1882         let lang_items = self.tcx.lang_items().iter();
1883         self.lazy_array(lang_items.filter_map(|(lang_item, def_id)| {
1884             def_id.as_local().map(|id| (id.local_def_index, lang_item))
1885         }))
1886     }
1887
1888     fn encode_lang_items_missing(&mut self) -> LazyArray<LangItem> {
1889         empty_proc_macro!(self);
1890         let tcx = self.tcx;
1891         self.lazy_array(&tcx.lang_items().missing)
1892     }
1893
1894     fn encode_traits(&mut self) -> LazyArray<DefIndex> {
1895         empty_proc_macro!(self);
1896         self.lazy_array(self.tcx.traits_in_crate(LOCAL_CRATE).iter().map(|def_id| def_id.index))
1897     }
1898
1899     /// Encodes an index, mapping each trait to its (local) implementations.
1900     fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
1901         debug!("EncodeContext::encode_traits_and_impls()");
1902         empty_proc_macro!(self);
1903         let tcx = self.tcx;
1904         let mut fx_hash_map: FxHashMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
1905             FxHashMap::default();
1906
1907         for id in tcx.hir().items() {
1908             if matches!(tcx.def_kind(id.owner_id), DefKind::Impl) {
1909                 if let Some(trait_ref) = tcx.impl_trait_ref(id.owner_id) {
1910                     let trait_ref = trait_ref.subst_identity();
1911
1912                     let simplified_self_ty = fast_reject::simplify_type(
1913                         self.tcx,
1914                         trait_ref.self_ty(),
1915                         TreatParams::AsInfer,
1916                     );
1917
1918                     fx_hash_map
1919                         .entry(trait_ref.def_id)
1920                         .or_default()
1921                         .push((id.owner_id.def_id.local_def_index, simplified_self_ty));
1922                 }
1923             }
1924         }
1925
1926         let mut all_impls: Vec<_> = fx_hash_map.into_iter().collect();
1927
1928         // Bring everything into deterministic order for hashing
1929         all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id));
1930
1931         let all_impls: Vec<_> = all_impls
1932             .into_iter()
1933             .map(|(trait_def_id, mut impls)| {
1934                 // Bring everything into deterministic order for hashing
1935                 impls.sort_by_cached_key(|&(index, _)| {
1936                     tcx.hir().def_path_hash(LocalDefId { local_def_index: index })
1937                 });
1938
1939                 TraitImpls {
1940                     trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
1941                     impls: self.lazy_array(&impls),
1942                 }
1943             })
1944             .collect();
1945
1946         self.lazy_array(&all_impls)
1947     }
1948
1949     fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
1950         debug!("EncodeContext::encode_traits_and_impls()");
1951         empty_proc_macro!(self);
1952         let tcx = self.tcx;
1953         let mut all_impls: Vec<_> = tcx.crate_inherent_impls(()).incoherent_impls.iter().collect();
1954         tcx.with_stable_hashing_context(|mut ctx| {
1955             all_impls.sort_by_cached_key(|&(&simp, _)| {
1956                 let mut hasher = StableHasher::new();
1957                 simp.hash_stable(&mut ctx, &mut hasher);
1958                 hasher.finish::<Fingerprint>()
1959             })
1960         });
1961         let all_impls: Vec<_> = all_impls
1962             .into_iter()
1963             .map(|(&simp, impls)| {
1964                 let mut impls: Vec<_> =
1965                     impls.into_iter().map(|def_id| def_id.local_def_index).collect();
1966                 impls.sort_by_cached_key(|&local_def_index| {
1967                     tcx.hir().def_path_hash(LocalDefId { local_def_index })
1968                 });
1969
1970                 IncoherentImpls { self_ty: simp, impls: self.lazy_array(impls) }
1971             })
1972             .collect();
1973
1974         self.lazy_array(&all_impls)
1975     }
1976
1977     // Encodes all symbols exported from this crate into the metadata.
1978     //
1979     // This pass is seeded off the reachability list calculated in the
1980     // middle::reachable module but filters out items that either don't have a
1981     // symbol associated with them (they weren't translated) or if they're an FFI
1982     // definition (as that's not defined in this crate).
1983     fn encode_exported_symbols(
1984         &mut self,
1985         exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
1986     ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
1987         empty_proc_macro!(self);
1988         // The metadata symbol name is special. It should not show up in
1989         // downstream crates.
1990         let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
1991
1992         self.lazy_array(
1993             exported_symbols
1994                 .iter()
1995                 .filter(|&(exported_symbol, _)| match *exported_symbol {
1996                     ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
1997                     _ => true,
1998                 })
1999                 .cloned(),
2000         )
2001     }
2002
2003     fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
2004         empty_proc_macro!(self);
2005         let formats = self.tcx.dependency_formats(());
2006         for (ty, arr) in formats.iter() {
2007             if *ty != CrateType::Dylib {
2008                 continue;
2009             }
2010             return self.lazy_array(arr.iter().map(|slot| match *slot {
2011                 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
2012
2013                 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
2014                 Linkage::Static => Some(LinkagePreference::RequireStatic),
2015             }));
2016         }
2017         LazyArray::empty()
2018     }
2019
2020     fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) {
2021         let tcx = self.tcx;
2022
2023         debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id);
2024
2025         match nitem.kind {
2026             hir::ForeignItemKind::Fn(_, ref names, _) => {
2027                 self.tables.asyncness.set(def_id.index, hir::IsAsync::NotAsync);
2028                 record_array!(self.tables.fn_arg_names[def_id] <- *names);
2029                 let constness = if self.tcx.is_const_fn_raw(def_id) {
2030                     hir::Constness::Const
2031                 } else {
2032                     hir::Constness::NotConst
2033                 };
2034                 self.tables.constness.set(def_id.index, constness);
2035                 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
2036             }
2037             hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => {}
2038         }
2039         if let hir::ForeignItemKind::Fn(..) = nitem.kind {
2040             if tcx.is_intrinsic(def_id) {
2041                 self.tables.is_intrinsic.set_nullable(def_id.index, true);
2042             }
2043         }
2044     }
2045 }
2046
2047 // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR.
2048 impl<'a, 'tcx> Visitor<'tcx> for EncodeContext<'a, 'tcx> {
2049     type NestedFilter = nested_filter::OnlyBodies;
2050
2051     fn nested_visit_map(&mut self) -> Self::Map {
2052         self.tcx.hir()
2053     }
2054     fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {
2055         intravisit::walk_expr(self, ex);
2056         self.encode_info_for_expr(ex);
2057     }
2058     fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
2059         intravisit::walk_item(self, item);
2060         match item.kind {
2061             hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these
2062             _ => self.encode_info_for_item(item.owner_id.to_def_id(), item),
2063         }
2064     }
2065     fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) {
2066         intravisit::walk_foreign_item(self, ni);
2067         self.encode_info_for_foreign_item(ni.owner_id.to_def_id(), ni);
2068     }
2069     fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) {
2070         intravisit::walk_generics(self, generics);
2071         self.encode_info_for_generics(generics);
2072     }
2073 }
2074
2075 impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
2076     fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) {
2077         for param in generics.params {
2078             match param.kind {
2079                 hir::GenericParamKind::Lifetime { .. } | hir::GenericParamKind::Type { .. } => {}
2080                 hir::GenericParamKind::Const { ref default, .. } => {
2081                     let def_id = param.def_id.to_def_id();
2082                     if default.is_some() {
2083                         record!(self.tables.const_param_default[def_id] <- self.tcx.const_param_default(def_id))
2084                     }
2085                 }
2086             }
2087         }
2088     }
2089
2090     fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) {
2091         if let hir::ExprKind::Closure(closure) = expr.kind {
2092             self.encode_info_for_closure(closure.def_id);
2093         }
2094     }
2095 }
2096
2097 /// Used to prefetch queries which will be needed later by metadata encoding.
2098 /// Only a subset of the queries are actually prefetched to keep this code smaller.
2099 fn prefetch_mir(tcx: TyCtxt<'_>) {
2100     if !tcx.sess.opts.output_types.should_codegen() {
2101         // We won't emit MIR, so don't prefetch it.
2102         return;
2103     }
2104
2105     par_iter(tcx.mir_keys(())).for_each(|&def_id| {
2106         let (encode_const, encode_opt) = should_encode_mir(tcx, def_id);
2107
2108         if encode_const {
2109             tcx.ensure().mir_for_ctfe(def_id);
2110         }
2111         if encode_opt {
2112             tcx.ensure().optimized_mir(def_id);
2113         }
2114         if encode_opt || encode_const {
2115             tcx.ensure().promoted_mir(def_id);
2116         }
2117     })
2118 }
2119
2120 // NOTE(eddyb) The following comment was preserved for posterity, even
2121 // though it's no longer relevant as EBML (which uses nested & tagged
2122 // "documents") was replaced with a scheme that can't go out of bounds.
2123 //
2124 // And here we run into yet another obscure archive bug: in which metadata
2125 // loaded from archives may have trailing garbage bytes. Awhile back one of
2126 // our tests was failing sporadically on the macOS 64-bit builders (both nopt
2127 // and opt) by having ebml generate an out-of-bounds panic when looking at
2128 // metadata.
2129 //
2130 // Upon investigation it turned out that the metadata file inside of an rlib
2131 // (and ar archive) was being corrupted. Some compilations would generate a
2132 // metadata file which would end in a few extra bytes, while other
2133 // compilations would not have these extra bytes appended to the end. These
2134 // extra bytes were interpreted by ebml as an extra tag, so they ended up
2135 // being interpreted causing the out-of-bounds.
2136 //
2137 // The root cause of why these extra bytes were appearing was never
2138 // discovered, and in the meantime the solution we're employing is to insert
2139 // the length of the metadata to the start of the metadata. Later on this
2140 // will allow us to slice the metadata to the precise length that we just
2141 // generated regardless of trailing bytes that end up in it.
2142
2143 pub struct EncodedMetadata {
2144     // The declaration order matters because `mmap` should be dropped before `_temp_dir`.
2145     mmap: Option<Mmap>,
2146     // We need to carry MaybeTempDir to avoid deleting the temporary
2147     // directory while accessing the Mmap.
2148     _temp_dir: Option<MaybeTempDir>,
2149 }
2150
2151 impl EncodedMetadata {
2152     #[inline]
2153     pub fn from_path(path: PathBuf, temp_dir: Option<MaybeTempDir>) -> std::io::Result<Self> {
2154         let file = std::fs::File::open(&path)?;
2155         let file_metadata = file.metadata()?;
2156         if file_metadata.len() == 0 {
2157             return Ok(Self { mmap: None, _temp_dir: None });
2158         }
2159         let mmap = unsafe { Some(Mmap::map(file)?) };
2160         Ok(Self { mmap, _temp_dir: temp_dir })
2161     }
2162
2163     #[inline]
2164     pub fn raw_data(&self) -> &[u8] {
2165         self.mmap.as_deref().unwrap_or_default()
2166     }
2167 }
2168
2169 impl<S: Encoder> Encodable<S> for EncodedMetadata {
2170     fn encode(&self, s: &mut S) {
2171         let slice = self.raw_data();
2172         slice.encode(s)
2173     }
2174 }
2175
2176 impl<D: Decoder> Decodable<D> for EncodedMetadata {
2177     fn decode(d: &mut D) -> Self {
2178         let len = d.read_usize();
2179         let mmap = if len > 0 {
2180             let mut mmap = MmapMut::map_anon(len).unwrap();
2181             for _ in 0..len {
2182                 (&mut mmap[..]).write(&[d.read_u8()]).unwrap();
2183             }
2184             mmap.flush().unwrap();
2185             Some(mmap.make_read_only().unwrap())
2186         } else {
2187             None
2188         };
2189
2190         Self { mmap, _temp_dir: None }
2191     }
2192 }
2193
2194 pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path) {
2195     let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2196
2197     // Since encoding metadata is not in a query, and nothing is cached,
2198     // there's no need to do dep-graph tracking for any of it.
2199     tcx.dep_graph.assert_ignored();
2200
2201     join(
2202         || encode_metadata_impl(tcx, path),
2203         || {
2204             if tcx.sess.threads() == 1 {
2205                 return;
2206             }
2207             // Prefetch some queries used by metadata encoding.
2208             // This is not necessary for correctness, but is only done for performance reasons.
2209             // It can be removed if it turns out to cause trouble or be detrimental to performance.
2210             join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2211         },
2212     );
2213 }
2214
2215 fn encode_metadata_impl(tcx: TyCtxt<'_>, path: &Path) {
2216     let mut encoder = opaque::FileEncoder::new(path)
2217         .unwrap_or_else(|err| tcx.sess.emit_fatal(FailCreateFileEncoder { err }));
2218     encoder.emit_raw_bytes(METADATA_HEADER);
2219
2220     // Will be filled with the root position after encoding everything.
2221     encoder.emit_raw_bytes(&[0, 0, 0, 0]);
2222
2223     let source_map_files = tcx.sess.source_map().files();
2224     let source_file_cache = (source_map_files[0].clone(), 0);
2225     let required_source_files = Some(FxIndexSet::default());
2226     drop(source_map_files);
2227
2228     let hygiene_ctxt = HygieneEncodeContext::default();
2229
2230     let mut ecx = EncodeContext {
2231         opaque: encoder,
2232         tcx,
2233         feat: tcx.features(),
2234         tables: Default::default(),
2235         lazy_state: LazyState::NoNode,
2236         type_shorthands: Default::default(),
2237         predicate_shorthands: Default::default(),
2238         source_file_cache,
2239         interpret_allocs: Default::default(),
2240         required_source_files,
2241         is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro),
2242         hygiene_ctxt: &hygiene_ctxt,
2243         symbol_table: Default::default(),
2244     };
2245
2246     // Encode the rustc version string in a predictable location.
2247     rustc_version().encode(&mut ecx);
2248
2249     // Encode all the entries and extra information in the crate,
2250     // culminating in the `CrateRoot` which points to all of it.
2251     let root = ecx.encode_crate_root();
2252
2253     ecx.opaque.flush();
2254
2255     let mut file = ecx.opaque.file();
2256     // We will return to this position after writing the root position.
2257     let pos_before_seek = file.stream_position().unwrap();
2258
2259     // Encode the root position.
2260     let header = METADATA_HEADER.len();
2261     file.seek(std::io::SeekFrom::Start(header as u64))
2262         .unwrap_or_else(|err| tcx.sess.emit_fatal(FailSeekFile { err }));
2263     let pos = root.position.get();
2264     file.write_all(&[(pos >> 24) as u8, (pos >> 16) as u8, (pos >> 8) as u8, (pos >> 0) as u8])
2265         .unwrap_or_else(|err| tcx.sess.emit_fatal(FailWriteFile { err }));
2266
2267     // Return to the position where we are before writing the root position.
2268     file.seek(std::io::SeekFrom::Start(pos_before_seek)).unwrap();
2269
2270     // Record metadata size for self-profiling
2271     tcx.prof.artifact_size(
2272         "crate_metadata",
2273         "crate_metadata",
2274         file.metadata().unwrap().len() as u64,
2275     );
2276 }
2277
2278 pub fn provide(providers: &mut Providers) {
2279     *providers = Providers {
2280         traits_in_crate: |tcx, cnum| {
2281             assert_eq!(cnum, LOCAL_CRATE);
2282
2283             let mut traits = Vec::new();
2284             for id in tcx.hir().items() {
2285                 if matches!(tcx.def_kind(id.owner_id), DefKind::Trait | DefKind::TraitAlias) {
2286                     traits.push(id.owner_id.to_def_id())
2287                 }
2288             }
2289
2290             // Bring everything into deterministic order.
2291             traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id));
2292             tcx.arena.alloc_slice(&traits)
2293         },
2294
2295         ..*providers
2296     }
2297 }