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