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