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