rustc_metadata/rmeta/
encoder.rs

1use std::borrow::Borrow;
2use std::collections::hash_map::Entry;
3use std::fs::File;
4use std::io::{Read, Seek, Write};
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7
8use rustc_ast::attr::AttributeExt;
9use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
10use rustc_data_structures::memmap::{Mmap, MmapMut};
11use rustc_data_structures::sync::{join, par_for_each_in};
12use rustc_data_structures::temp_dir::MaybeTempDir;
13use rustc_data_structures::thousands::format_with_underscores;
14use rustc_feature::Features;
15use rustc_hir as hir;
16use rustc_hir::def_id::{CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE, LocalDefId, LocalDefIdSet};
17use rustc_hir::definitions::DefPathData;
18use rustc_hir_pretty::id_to_string;
19use rustc_middle::middle::dependency_format::Linkage;
20use rustc_middle::middle::exported_symbols::metadata_symbol_name;
21use rustc_middle::mir::interpret;
22use rustc_middle::query::Providers;
23use rustc_middle::traits::specialization_graph;
24use rustc_middle::ty::codec::TyEncoder;
25use rustc_middle::ty::fast_reject::{self, TreatParams};
26use rustc_middle::ty::{AssocItemContainer, SymbolName};
27use rustc_middle::{bug, span_bug};
28use rustc_serialize::{Decodable, Decoder, Encodable, Encoder, opaque};
29use rustc_session::config::{CrateType, OptLevel, TargetModifier};
30use rustc_span::hygiene::HygieneEncodeContext;
31use rustc_span::{
32    ExternalSource, FileName, SourceFile, SpanData, SpanEncoder, StableSourceFileId, SyntaxContext,
33    sym,
34};
35use tracing::{debug, instrument, trace};
36
37use crate::errors::{FailCreateFileEncoder, FailWriteFile};
38use crate::rmeta::*;
39
40pub(super) struct EncodeContext<'a, 'tcx> {
41    opaque: opaque::FileEncoder,
42    tcx: TyCtxt<'tcx>,
43    feat: &'tcx rustc_feature::Features,
44    tables: TableBuilders,
45
46    lazy_state: LazyState,
47    span_shorthands: FxHashMap<Span, usize>,
48    type_shorthands: FxHashMap<Ty<'tcx>, usize>,
49    predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>,
50
51    interpret_allocs: FxIndexSet<interpret::AllocId>,
52
53    // This is used to speed up Span encoding.
54    // The `usize` is an index into the `MonotonicVec`
55    // that stores the `SourceFile`
56    source_file_cache: (Arc<SourceFile>, usize),
57    // The indices (into the `SourceMap`'s `MonotonicVec`)
58    // of all of the `SourceFiles` that we need to serialize.
59    // When we serialize a `Span`, we insert the index of its
60    // `SourceFile` into the `FxIndexSet`.
61    // The order inside the `FxIndexSet` is used as on-disk
62    // order of `SourceFiles`, and encoded inside `Span`s.
63    required_source_files: Option<FxIndexSet<usize>>,
64    is_proc_macro: bool,
65    hygiene_ctxt: &'a HygieneEncodeContext,
66    symbol_table: FxHashMap<Symbol, usize>,
67}
68
69/// If the current crate is a proc-macro, returns early with `LazyArray::default()`.
70/// This is useful for skipping the encoding of things that aren't needed
71/// for proc-macro crates.
72macro_rules! empty_proc_macro {
73    ($self:ident) => {
74        if $self.is_proc_macro {
75            return LazyArray::default();
76        }
77    };
78}
79
80macro_rules! encoder_methods {
81    ($($name:ident($ty:ty);)*) => {
82        $(fn $name(&mut self, value: $ty) {
83            self.opaque.$name(value)
84        })*
85    }
86}
87
88impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
89    encoder_methods! {
90        emit_usize(usize);
91        emit_u128(u128);
92        emit_u64(u64);
93        emit_u32(u32);
94        emit_u16(u16);
95        emit_u8(u8);
96
97        emit_isize(isize);
98        emit_i128(i128);
99        emit_i64(i64);
100        emit_i32(i32);
101        emit_i16(i16);
102
103        emit_raw_bytes(&[u8]);
104    }
105}
106
107impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyValue<T> {
108    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
109        e.emit_lazy_distance(self.position);
110    }
111}
112
113impl<'a, 'tcx, T> Encodable<EncodeContext<'a, 'tcx>> for LazyArray<T> {
114    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
115        e.emit_usize(self.num_elems);
116        if self.num_elems > 0 {
117            e.emit_lazy_distance(self.position)
118        }
119    }
120}
121
122impl<'a, 'tcx, I, T> Encodable<EncodeContext<'a, 'tcx>> for LazyTable<I, T> {
123    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
124        e.emit_usize(self.width);
125        e.emit_usize(self.len);
126        e.emit_lazy_distance(self.position);
127    }
128}
129
130impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex {
131    fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
132        s.emit_u32(self.as_u32());
133    }
134}
135
136impl<'a, 'tcx> SpanEncoder for EncodeContext<'a, 'tcx> {
137    fn encode_crate_num(&mut self, crate_num: CrateNum) {
138        if crate_num != LOCAL_CRATE && self.is_proc_macro {
139            panic!("Attempted to encode non-local CrateNum {crate_num:?} for proc-macro crate");
140        }
141        self.emit_u32(crate_num.as_u32());
142    }
143
144    fn encode_def_index(&mut self, def_index: DefIndex) {
145        self.emit_u32(def_index.as_u32());
146    }
147
148    fn encode_def_id(&mut self, def_id: DefId) {
149        def_id.krate.encode(self);
150        def_id.index.encode(self);
151    }
152
153    fn encode_syntax_context(&mut self, syntax_context: SyntaxContext) {
154        rustc_span::hygiene::raw_encode_syntax_context(syntax_context, self.hygiene_ctxt, self);
155    }
156
157    fn encode_expn_id(&mut self, expn_id: ExpnId) {
158        if expn_id.krate == LOCAL_CRATE {
159            // We will only write details for local expansions. Non-local expansions will fetch
160            // data from the corresponding crate's metadata.
161            // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external
162            // metadata from proc-macro crates.
163            self.hygiene_ctxt.schedule_expn_data_for_encoding(expn_id);
164        }
165        expn_id.krate.encode(self);
166        expn_id.local_id.encode(self);
167    }
168
169    fn encode_span(&mut self, span: Span) {
170        match self.span_shorthands.entry(span) {
171            Entry::Occupied(o) => {
172                // If an offset is smaller than the absolute position, we encode with the offset.
173                // This saves space since smaller numbers encode in less bits.
174                let last_location = *o.get();
175                // This cannot underflow. Metadata is written with increasing position(), so any
176                // previously saved offset must be smaller than the current position.
177                let offset = self.opaque.position() - last_location;
178                if offset < last_location {
179                    let needed = bytes_needed(offset);
180                    SpanTag::indirect(true, needed as u8).encode(self);
181                    self.opaque.write_with(|dest| {
182                        *dest = offset.to_le_bytes();
183                        needed
184                    });
185                } else {
186                    let needed = bytes_needed(last_location);
187                    SpanTag::indirect(false, needed as u8).encode(self);
188                    self.opaque.write_with(|dest| {
189                        *dest = last_location.to_le_bytes();
190                        needed
191                    });
192                }
193            }
194            Entry::Vacant(v) => {
195                let position = self.opaque.position();
196                v.insert(position);
197                // Data is encoded with a SpanTag prefix (see below).
198                span.data().encode(self);
199            }
200        }
201    }
202
203    fn encode_symbol(&mut self, symbol: Symbol) {
204        // if symbol predefined, emit tag and symbol index
205        if symbol.is_predefined() {
206            self.opaque.emit_u8(SYMBOL_PREDEFINED);
207            self.opaque.emit_u32(symbol.as_u32());
208        } else {
209            // otherwise write it as string or as offset to it
210            match self.symbol_table.entry(symbol) {
211                Entry::Vacant(o) => {
212                    self.opaque.emit_u8(SYMBOL_STR);
213                    let pos = self.opaque.position();
214                    o.insert(pos);
215                    self.emit_str(symbol.as_str());
216                }
217                Entry::Occupied(o) => {
218                    let x = *o.get();
219                    self.emit_u8(SYMBOL_OFFSET);
220                    self.emit_usize(x);
221                }
222            }
223        }
224    }
225}
226
227fn bytes_needed(n: usize) -> usize {
228    (usize::BITS - n.leading_zeros()).div_ceil(u8::BITS) as usize
229}
230
231impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SpanData {
232    fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) {
233        // Don't serialize any `SyntaxContext`s from a proc-macro crate,
234        // since we don't load proc-macro dependencies during serialization.
235        // This means that any hygiene information from macros used *within*
236        // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro
237        // definition) will be lost.
238        //
239        // This can show up in two ways:
240        //
241        // 1. Any hygiene information associated with identifier of
242        // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost.
243        // Since proc-macros can only be invoked from a different crate,
244        // real code should never need to care about this.
245        //
246        // 2. Using `Span::def_site` or `Span::mixed_site` will not
247        // include any hygiene information associated with the definition
248        // site. This means that a proc-macro cannot emit a `$crate`
249        // identifier which resolves to one of its dependencies,
250        // which also should never come up in practice.
251        //
252        // Additionally, this affects `Span::parent`, and any other
253        // span inspection APIs that would otherwise allow traversing
254        // the `SyntaxContexts` associated with a span.
255        //
256        // None of these user-visible effects should result in any
257        // cross-crate inconsistencies (getting one behavior in the same
258        // crate, and a different behavior in another crate) due to the
259        // limited surface that proc-macros can expose.
260        //
261        // IMPORTANT: If this is ever changed, be sure to update
262        // `rustc_span::hygiene::raw_encode_expn_id` to handle
263        // encoding `ExpnData` for proc-macro crates.
264        let ctxt = if s.is_proc_macro { SyntaxContext::root() } else { self.ctxt };
265
266        if self.is_dummy() {
267            let tag = SpanTag::new(SpanKind::Partial, ctxt, 0);
268            tag.encode(s);
269            if tag.context().is_none() {
270                ctxt.encode(s);
271            }
272            return;
273        }
274
275        // The Span infrastructure should make sure that this invariant holds:
276        debug_assert!(self.lo <= self.hi);
277
278        if !s.source_file_cache.0.contains(self.lo) {
279            let source_map = s.tcx.sess.source_map();
280            let source_file_index = source_map.lookup_source_file_idx(self.lo);
281            s.source_file_cache =
282                (Arc::clone(&source_map.files()[source_file_index]), source_file_index);
283        }
284        let (ref source_file, source_file_index) = s.source_file_cache;
285        debug_assert!(source_file.contains(self.lo));
286
287        if !source_file.contains(self.hi) {
288            // Unfortunately, macro expansion still sometimes generates Spans
289            // that malformed in this way.
290            let tag = SpanTag::new(SpanKind::Partial, ctxt, 0);
291            tag.encode(s);
292            if tag.context().is_none() {
293                ctxt.encode(s);
294            }
295            return;
296        }
297
298        // There are two possible cases here:
299        // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
300        // crate we are writing metadata for. When the metadata for *this* crate gets
301        // deserialized, the deserializer will need to know which crate it originally came
302        // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
303        // be deserialized after the rest of the span data, which tells the deserializer
304        // which crate contains the source map information.
305        // 2. This span comes from our own crate. No special handling is needed - we just
306        // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
307        // our own source map information.
308        //
309        // If we're a proc-macro crate, we always treat this as a local `Span`.
310        // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata
311        // if we're a proc-macro crate.
312        // This allows us to avoid loading the dependencies of proc-macro crates: all of
313        // the information we need to decode `Span`s is stored in the proc-macro crate.
314        let (kind, metadata_index) = if source_file.is_imported() && !s.is_proc_macro {
315            // To simplify deserialization, we 'rebase' this span onto the crate it originally came
316            // from (the crate that 'owns' the file it references. These rebased 'lo' and 'hi'
317            // values are relative to the source map information for the 'foreign' crate whose
318            // CrateNum we write into the metadata. This allows `imported_source_files` to binary
319            // search through the 'foreign' crate's source map information, using the
320            // deserialized 'lo' and 'hi' values directly.
321            //
322            // All of this logic ensures that the final result of deserialization is a 'normal'
323            // Span that can be used without any additional trouble.
324            let metadata_index = {
325                // Introduce a new scope so that we drop the 'read()' temporary
326                match &*source_file.external_src.read() {
327                    ExternalSource::Foreign { metadata_index, .. } => *metadata_index,
328                    src => panic!("Unexpected external source {src:?}"),
329                }
330            };
331
332            (SpanKind::Foreign, metadata_index)
333        } else {
334            // Record the fact that we need to encode the data for this `SourceFile`
335            let source_files =
336                s.required_source_files.as_mut().expect("Already encoded SourceMap!");
337            let (metadata_index, _) = source_files.insert_full(source_file_index);
338            let metadata_index: u32 =
339                metadata_index.try_into().expect("cannot export more than U32_MAX files");
340
341            (SpanKind::Local, metadata_index)
342        };
343
344        // Encode the start position relative to the file start, so we profit more from the
345        // variable-length integer encoding.
346        let lo = self.lo - source_file.start_pos;
347
348        // Encode length which is usually less than span.hi and profits more
349        // from the variable-length integer encoding that we use.
350        let len = self.hi - self.lo;
351
352        let tag = SpanTag::new(kind, ctxt, len.0 as usize);
353        tag.encode(s);
354        if tag.context().is_none() {
355            ctxt.encode(s);
356        }
357        lo.encode(s);
358        if tag.length().is_none() {
359            len.encode(s);
360        }
361
362        // Encode the index of the `SourceFile` for the span, in order to make decoding faster.
363        metadata_index.encode(s);
364
365        if kind == SpanKind::Foreign {
366            // This needs to be two lines to avoid holding the `s.source_file_cache`
367            // while calling `cnum.encode(s)`
368            let cnum = s.source_file_cache.0.cnum;
369            cnum.encode(s);
370        }
371    }
372}
373
374impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for [u8] {
375    fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) {
376        Encoder::emit_usize(e, self.len());
377        e.emit_raw_bytes(self);
378    }
379}
380
381impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> {
382    const CLEAR_CROSS_CRATE: bool = true;
383
384    fn position(&self) -> usize {
385        self.opaque.position()
386    }
387
388    fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
389        &mut self.type_shorthands
390    }
391
392    fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
393        &mut self.predicate_shorthands
394    }
395
396    fn encode_alloc_id(&mut self, alloc_id: &rustc_middle::mir::interpret::AllocId) {
397        let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
398
399        index.encode(self);
400    }
401}
402
403// Shorthand for `$self.$tables.$table.set_some($def_id.index, $self.lazy($value))`, which would
404// normally need extra variables to avoid errors about multiple mutable borrows.
405macro_rules! record {
406    ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
407        {
408            let value = $value;
409            let lazy = $self.lazy(value);
410            $self.$tables.$table.set_some($def_id.index, lazy);
411        }
412    }};
413}
414
415// Shorthand for `$self.$tables.$table.set_some($def_id.index, $self.lazy_array($value))`, which would
416// normally need extra variables to avoid errors about multiple mutable borrows.
417macro_rules! record_array {
418    ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
419        {
420            let value = $value;
421            let lazy = $self.lazy_array(value);
422            $self.$tables.$table.set_some($def_id.index, lazy);
423        }
424    }};
425}
426
427macro_rules! record_defaulted_array {
428    ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
429        {
430            let value = $value;
431            let lazy = $self.lazy_array(value);
432            $self.$tables.$table.set($def_id.index, lazy);
433        }
434    }};
435}
436
437impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
438    fn emit_lazy_distance(&mut self, position: NonZero<usize>) {
439        let pos = position.get();
440        let distance = match self.lazy_state {
441            LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
442            LazyState::NodeStart(start) => {
443                let start = start.get();
444                assert!(pos <= start);
445                start - pos
446            }
447            LazyState::Previous(last_pos) => {
448                assert!(
449                    last_pos <= position,
450                    "make sure that the calls to `lazy*` \
451                     are in the same order as the metadata fields",
452                );
453                position.get() - last_pos.get()
454            }
455        };
456        self.lazy_state = LazyState::Previous(NonZero::new(pos).unwrap());
457        self.emit_usize(distance);
458    }
459
460    fn lazy<T: ParameterizedOverTcx, B: Borrow<T::Value<'tcx>>>(&mut self, value: B) -> LazyValue<T>
461    where
462        T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
463    {
464        let pos = NonZero::new(self.position()).unwrap();
465
466        assert_eq!(self.lazy_state, LazyState::NoNode);
467        self.lazy_state = LazyState::NodeStart(pos);
468        value.borrow().encode(self);
469        self.lazy_state = LazyState::NoNode;
470
471        assert!(pos.get() <= self.position());
472
473        LazyValue::from_position(pos)
474    }
475
476    fn lazy_array<T: ParameterizedOverTcx, I: IntoIterator<Item = B>, B: Borrow<T::Value<'tcx>>>(
477        &mut self,
478        values: I,
479    ) -> LazyArray<T>
480    where
481        T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
482    {
483        let pos = NonZero::new(self.position()).unwrap();
484
485        assert_eq!(self.lazy_state, LazyState::NoNode);
486        self.lazy_state = LazyState::NodeStart(pos);
487        let len = values.into_iter().map(|value| value.borrow().encode(self)).count();
488        self.lazy_state = LazyState::NoNode;
489
490        assert!(pos.get() <= self.position());
491
492        LazyArray::from_position_and_num_elems(pos, len)
493    }
494
495    fn encode_def_path_table(&mut self) {
496        let table = self.tcx.def_path_table();
497        if self.is_proc_macro {
498            for def_index in std::iter::once(CRATE_DEF_INDEX)
499                .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index))
500            {
501                let def_key = self.lazy(table.def_key(def_index));
502                let def_path_hash = table.def_path_hash(def_index);
503                self.tables.def_keys.set_some(def_index, def_key);
504                self.tables.def_path_hashes.set(def_index, def_path_hash.local_hash().as_u64());
505            }
506        } else {
507            for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
508                let def_key = self.lazy(def_key);
509                self.tables.def_keys.set_some(def_index, def_key);
510                self.tables.def_path_hashes.set(def_index, def_path_hash.local_hash().as_u64());
511            }
512        }
513    }
514
515    fn encode_def_path_hash_map(&mut self) -> LazyValue<DefPathHashMapRef<'static>> {
516        self.lazy(DefPathHashMapRef::BorrowedFromTcx(self.tcx.def_path_hash_to_def_index_map()))
517    }
518
519    fn encode_source_map(&mut self) -> LazyTable<u32, Option<LazyValue<rustc_span::SourceFile>>> {
520        let source_map = self.tcx.sess.source_map();
521        let all_source_files = source_map.files();
522
523        // By replacing the `Option` with `None`, we ensure that we can't
524        // accidentally serialize any more `Span`s after the source map encoding
525        // is done.
526        let required_source_files = self.required_source_files.take().unwrap();
527
528        let working_directory = &self.tcx.sess.opts.working_dir;
529
530        let mut adapted = TableBuilder::default();
531
532        let local_crate_stable_id = self.tcx.stable_crate_id(LOCAL_CRATE);
533
534        // Only serialize `SourceFile`s that were used during the encoding of a `Span`.
535        //
536        // The order in which we encode source files is important here: the on-disk format for
537        // `Span` contains the index of the corresponding `SourceFile`.
538        for (on_disk_index, &source_file_index) in required_source_files.iter().enumerate() {
539            let source_file = &all_source_files[source_file_index];
540            // Don't serialize imported `SourceFile`s, unless we're in a proc-macro crate.
541            assert!(!source_file.is_imported() || self.is_proc_macro);
542
543            // At export time we expand all source file paths to absolute paths because
544            // downstream compilation sessions can have a different compiler working
545            // directory, so relative paths from this or any other upstream crate
546            // won't be valid anymore.
547            //
548            // At this point we also erase the actual on-disk path and only keep
549            // the remapped version -- as is necessary for reproducible builds.
550            let mut adapted_source_file = (**source_file).clone();
551
552            match source_file.name {
553                FileName::Real(ref original_file_name) => {
554                    let adapted_file_name = source_map
555                        .path_mapping()
556                        .to_embeddable_absolute_path(original_file_name.clone(), working_directory);
557
558                    adapted_source_file.name = FileName::Real(adapted_file_name);
559                }
560                _ => {
561                    // expanded code, not from a file
562                }
563            };
564
565            // We're serializing this `SourceFile` into our crate metadata,
566            // so mark it as coming from this crate.
567            // This also ensures that we don't try to deserialize the
568            // `CrateNum` for a proc-macro dependency - since proc macro
569            // dependencies aren't loaded when we deserialize a proc-macro,
570            // trying to remap the `CrateNum` would fail.
571            if self.is_proc_macro {
572                adapted_source_file.cnum = LOCAL_CRATE;
573            }
574
575            // Update the `StableSourceFileId` to make sure it incorporates the
576            // id of the current crate. This way it will be unique within the
577            // crate graph during downstream compilation sessions.
578            adapted_source_file.stable_id = StableSourceFileId::from_filename_for_export(
579                &adapted_source_file.name,
580                local_crate_stable_id,
581            );
582
583            let on_disk_index: u32 =
584                on_disk_index.try_into().expect("cannot export more than U32_MAX files");
585            adapted.set_some(on_disk_index, self.lazy(adapted_source_file));
586        }
587
588        adapted.encode(&mut self.opaque)
589    }
590
591    fn encode_crate_root(&mut self) -> LazyValue<CrateRoot> {
592        let tcx = self.tcx;
593        let mut stats: Vec<(&'static str, usize)> = Vec::with_capacity(32);
594
595        macro_rules! stat {
596            ($label:literal, $f:expr) => {{
597                let orig_pos = self.position();
598                let res = $f();
599                stats.push(($label, self.position() - orig_pos));
600                res
601            }};
602        }
603
604        // We have already encoded some things. Get their combined size from the current position.
605        stats.push(("preamble", self.position()));
606
607        let (crate_deps, dylib_dependency_formats) =
608            stat!("dep", || (self.encode_crate_deps(), self.encode_dylib_dependency_formats()));
609
610        let lib_features = stat!("lib-features", || self.encode_lib_features());
611
612        let stability_implications =
613            stat!("stability-implications", || self.encode_stability_implications());
614
615        let (lang_items, lang_items_missing) = stat!("lang-items", || {
616            (self.encode_lang_items(), self.encode_lang_items_missing())
617        });
618
619        let stripped_cfg_items = stat!("stripped-cfg-items", || self.encode_stripped_cfg_items());
620
621        let diagnostic_items = stat!("diagnostic-items", || self.encode_diagnostic_items());
622
623        let native_libraries = stat!("native-libs", || self.encode_native_libraries());
624
625        let foreign_modules = stat!("foreign-modules", || self.encode_foreign_modules());
626
627        _ = stat!("def-path-table", || self.encode_def_path_table());
628
629        // Encode the def IDs of traits, for rustdoc and diagnostics.
630        let traits = stat!("traits", || self.encode_traits());
631
632        // Encode the def IDs of impls, for coherence checking.
633        let impls = stat!("impls", || self.encode_impls());
634
635        let incoherent_impls = stat!("incoherent-impls", || self.encode_incoherent_impls());
636
637        _ = stat!("mir", || self.encode_mir());
638
639        _ = stat!("def-ids", || self.encode_def_ids());
640
641        let interpret_alloc_index = stat!("interpret-alloc-index", || {
642            let mut interpret_alloc_index = Vec::new();
643            let mut n = 0;
644            trace!("beginning to encode alloc ids");
645            loop {
646                let new_n = self.interpret_allocs.len();
647                // if we have found new ids, serialize those, too
648                if n == new_n {
649                    // otherwise, abort
650                    break;
651                }
652                trace!("encoding {} further alloc ids", new_n - n);
653                for idx in n..new_n {
654                    let id = self.interpret_allocs[idx];
655                    let pos = self.position() as u64;
656                    interpret_alloc_index.push(pos);
657                    interpret::specialized_encode_alloc_id(self, tcx, id);
658                }
659                n = new_n;
660            }
661            self.lazy_array(interpret_alloc_index)
662        });
663
664        // Encode the proc macro data. This affects `tables`, so we need to do this before we
665        // encode the tables. This overwrites def_keys, so it must happen after
666        // encode_def_path_table.
667        let proc_macro_data = stat!("proc-macro-data", || self.encode_proc_macros());
668
669        let tables = stat!("tables", || self.tables.encode(&mut self.opaque));
670
671        let debugger_visualizers =
672            stat!("debugger-visualizers", || self.encode_debugger_visualizers());
673
674        let exportable_items = stat!("exportable-items", || self.encode_exportable_items());
675
676        let stable_order_of_exportable_impls =
677            stat!("exportable-items", || self.encode_stable_order_of_exportable_impls());
678
679        // Encode exported symbols info. This is prefetched in `encode_metadata`.
680        let exported_symbols = stat!("exported-symbols", || {
681            self.encode_exported_symbols(tcx.exported_symbols(LOCAL_CRATE))
682        });
683
684        // Encode the hygiene data.
685        // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The
686        // process of encoding other items (e.g. `optimized_mir`) may cause us to load data from
687        // the incremental cache. If this causes us to deserialize a `Span`, then we may load
688        // additional `SyntaxContext`s into the global `HygieneData`. Therefore, we need to encode
689        // the hygiene data last to ensure that we encode any `SyntaxContext`s that might be used.
690        let (syntax_contexts, expn_data, expn_hashes) = stat!("hygiene", || self.encode_hygiene());
691
692        let def_path_hash_map = stat!("def-path-hash-map", || self.encode_def_path_hash_map());
693
694        // Encode source_map. This needs to be done last, because encoding `Span`s tells us which
695        // `SourceFiles` we actually need to encode.
696        let source_map = stat!("source-map", || self.encode_source_map());
697        let target_modifiers = stat!("target-modifiers", || self.encode_target_modifiers());
698
699        let root = stat!("final", || {
700            let attrs = tcx.hir_krate_attrs();
701            self.lazy(CrateRoot {
702                header: CrateHeader {
703                    name: tcx.crate_name(LOCAL_CRATE),
704                    triple: tcx.sess.opts.target_triple.clone(),
705                    hash: tcx.crate_hash(LOCAL_CRATE),
706                    is_proc_macro_crate: proc_macro_data.is_some(),
707                    is_stub: false,
708                },
709                extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
710                stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(),
711                required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
712                panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
713                edition: tcx.sess.edition(),
714                has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
715                has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
716                has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
717                has_default_lib_allocator: ast::attr::contains_name(
718                    attrs,
719                    sym::default_lib_allocator,
720                ),
721                proc_macro_data,
722                debugger_visualizers,
723                compiler_builtins: ast::attr::contains_name(attrs, sym::compiler_builtins),
724                needs_allocator: ast::attr::contains_name(attrs, sym::needs_allocator),
725                needs_panic_runtime: ast::attr::contains_name(attrs, sym::needs_panic_runtime),
726                no_builtins: ast::attr::contains_name(attrs, sym::no_builtins),
727                panic_runtime: ast::attr::contains_name(attrs, sym::panic_runtime),
728                profiler_runtime: ast::attr::contains_name(attrs, sym::profiler_runtime),
729                symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
730
731                crate_deps,
732                dylib_dependency_formats,
733                lib_features,
734                stability_implications,
735                lang_items,
736                diagnostic_items,
737                lang_items_missing,
738                stripped_cfg_items,
739                native_libraries,
740                foreign_modules,
741                source_map,
742                target_modifiers,
743                traits,
744                impls,
745                incoherent_impls,
746                exportable_items,
747                stable_order_of_exportable_impls,
748                exported_symbols,
749                interpret_alloc_index,
750                tables,
751                syntax_contexts,
752                expn_data,
753                expn_hashes,
754                def_path_hash_map,
755                specialization_enabled_in: tcx.specialization_enabled_in(LOCAL_CRATE),
756            })
757        });
758
759        let total_bytes = self.position();
760
761        let computed_total_bytes: usize = stats.iter().map(|(_, size)| size).sum();
762        assert_eq!(total_bytes, computed_total_bytes);
763
764        if tcx.sess.opts.unstable_opts.meta_stats {
765            self.opaque.flush();
766
767            // Rewind and re-read all the metadata to count the zero bytes we wrote.
768            let pos_before_rewind = self.opaque.file().stream_position().unwrap();
769            let mut zero_bytes = 0;
770            self.opaque.file().rewind().unwrap();
771            let file = std::io::BufReader::new(self.opaque.file());
772            for e in file.bytes() {
773                if e.unwrap() == 0 {
774                    zero_bytes += 1;
775                }
776            }
777            assert_eq!(self.opaque.file().stream_position().unwrap(), pos_before_rewind);
778
779            stats.sort_by_key(|&(_, usize)| usize);
780
781            let prefix = "meta-stats";
782            let perc = |bytes| (bytes * 100) as f64 / total_bytes as f64;
783
784            eprintln!("{prefix} METADATA STATS");
785            eprintln!("{} {:<23}{:>10}", prefix, "Section", "Size");
786            eprintln!("{prefix} ----------------------------------------------------------------");
787            for (label, size) in stats {
788                eprintln!(
789                    "{} {:<23}{:>10} ({:4.1}%)",
790                    prefix,
791                    label,
792                    format_with_underscores(size),
793                    perc(size)
794                );
795            }
796            eprintln!("{prefix} ----------------------------------------------------------------");
797            eprintln!(
798                "{} {:<23}{:>10} (of which {:.1}% are zero bytes)",
799                prefix,
800                "Total",
801                format_with_underscores(total_bytes),
802                perc(zero_bytes)
803            );
804            eprintln!("{prefix}");
805        }
806
807        root
808    }
809}
810
811struct AnalyzeAttrState<'a> {
812    is_exported: bool,
813    is_doc_hidden: bool,
814    features: &'a Features,
815}
816
817/// Returns whether an attribute needs to be recorded in metadata, that is, if it's usable and
818/// useful in downstream crates. Local-only attributes are an obvious example, but some
819/// rustdoc-specific attributes can equally be of use while documenting the current crate only.
820///
821/// Removing these superfluous attributes speeds up compilation by making the metadata smaller.
822///
823/// Note: the `is_exported` parameter is used to cache whether the given `DefId` has a public
824/// visibility: this is a piece of data that can be computed once per defid, and not once per
825/// attribute. Some attributes would only be usable downstream if they are public.
826#[inline]
827fn analyze_attr(attr: &impl AttributeExt, state: &mut AnalyzeAttrState<'_>) -> bool {
828    let mut should_encode = false;
829    if let Some(name) = attr.name()
830        && !rustc_feature::encode_cross_crate(name)
831    {
832        // Attributes not marked encode-cross-crate don't need to be encoded for downstream crates.
833    } else if attr.doc_str().is_some() {
834        // We keep all doc comments reachable to rustdoc because they might be "imported" into
835        // downstream crates if they use `#[doc(inline)]` to copy an item's documentation into
836        // their own.
837        if state.is_exported {
838            should_encode = true;
839        }
840    } else if attr.has_name(sym::doc) {
841        // If this is a `doc` attribute that doesn't have anything except maybe `inline` (as in
842        // `#[doc(inline)]`), then we can remove it. It won't be inlinable in downstream crates.
843        if let Some(item_list) = attr.meta_item_list() {
844            for item in item_list {
845                if !item.has_name(sym::inline) {
846                    should_encode = true;
847                    if item.has_name(sym::hidden) {
848                        state.is_doc_hidden = true;
849                        break;
850                    }
851                }
852            }
853        }
854    } else if let &[sym::diagnostic, seg] = &*attr.path() {
855        should_encode = rustc_feature::is_stable_diagnostic_attribute(seg, state.features);
856    } else {
857        should_encode = true;
858    }
859    should_encode
860}
861
862fn should_encode_span(def_kind: DefKind) -> bool {
863    match def_kind {
864        DefKind::Mod
865        | DefKind::Struct
866        | DefKind::Union
867        | DefKind::Enum
868        | DefKind::Variant
869        | DefKind::Trait
870        | DefKind::TyAlias
871        | DefKind::ForeignTy
872        | DefKind::TraitAlias
873        | DefKind::AssocTy
874        | DefKind::TyParam
875        | DefKind::ConstParam
876        | DefKind::LifetimeParam
877        | DefKind::Fn
878        | DefKind::Const
879        | DefKind::Static { .. }
880        | DefKind::Ctor(..)
881        | DefKind::AssocFn
882        | DefKind::AssocConst
883        | DefKind::Macro(_)
884        | DefKind::ExternCrate
885        | DefKind::Use
886        | DefKind::AnonConst
887        | DefKind::InlineConst
888        | DefKind::OpaqueTy
889        | DefKind::Field
890        | DefKind::Impl { .. }
891        | DefKind::Closure
892        | DefKind::SyntheticCoroutineBody => true,
893        DefKind::ForeignMod | DefKind::GlobalAsm => false,
894    }
895}
896
897fn should_encode_attrs(def_kind: DefKind) -> bool {
898    match def_kind {
899        DefKind::Mod
900        | DefKind::Struct
901        | DefKind::Union
902        | DefKind::Enum
903        | DefKind::Variant
904        | DefKind::Trait
905        | DefKind::TyAlias
906        | DefKind::ForeignTy
907        | DefKind::TraitAlias
908        | DefKind::AssocTy
909        | DefKind::Fn
910        | DefKind::Const
911        | DefKind::Static { nested: false, .. }
912        | DefKind::AssocFn
913        | DefKind::AssocConst
914        | DefKind::Macro(_)
915        | DefKind::Field
916        | DefKind::Impl { .. } => true,
917        // Tools may want to be able to detect their tool lints on
918        // closures from upstream crates, too. This is used by
919        // https://github.com/model-checking/kani and is not a performance
920        // or maintenance issue for us.
921        DefKind::Closure => true,
922        DefKind::SyntheticCoroutineBody => false,
923        DefKind::TyParam
924        | DefKind::ConstParam
925        | DefKind::Ctor(..)
926        | DefKind::ExternCrate
927        | DefKind::Use
928        | DefKind::ForeignMod
929        | DefKind::AnonConst
930        | DefKind::InlineConst
931        | DefKind::OpaqueTy
932        | DefKind::LifetimeParam
933        | DefKind::Static { nested: true, .. }
934        | DefKind::GlobalAsm => false,
935    }
936}
937
938fn should_encode_expn_that_defined(def_kind: DefKind) -> bool {
939    match def_kind {
940        DefKind::Mod
941        | DefKind::Struct
942        | DefKind::Union
943        | DefKind::Enum
944        | DefKind::Variant
945        | DefKind::Trait
946        | DefKind::Impl { .. } => true,
947        DefKind::TyAlias
948        | DefKind::ForeignTy
949        | DefKind::TraitAlias
950        | DefKind::AssocTy
951        | DefKind::TyParam
952        | DefKind::Fn
953        | DefKind::Const
954        | DefKind::ConstParam
955        | DefKind::Static { .. }
956        | DefKind::Ctor(..)
957        | DefKind::AssocFn
958        | DefKind::AssocConst
959        | DefKind::Macro(_)
960        | DefKind::ExternCrate
961        | DefKind::Use
962        | DefKind::ForeignMod
963        | DefKind::AnonConst
964        | DefKind::InlineConst
965        | DefKind::OpaqueTy
966        | DefKind::Field
967        | DefKind::LifetimeParam
968        | DefKind::GlobalAsm
969        | DefKind::Closure
970        | DefKind::SyntheticCoroutineBody => false,
971    }
972}
973
974fn should_encode_visibility(def_kind: DefKind) -> bool {
975    match def_kind {
976        DefKind::Mod
977        | DefKind::Struct
978        | DefKind::Union
979        | DefKind::Enum
980        | DefKind::Variant
981        | DefKind::Trait
982        | DefKind::TyAlias
983        | DefKind::ForeignTy
984        | DefKind::TraitAlias
985        | DefKind::AssocTy
986        | DefKind::Fn
987        | DefKind::Const
988        | DefKind::Static { nested: false, .. }
989        | DefKind::Ctor(..)
990        | DefKind::AssocFn
991        | DefKind::AssocConst
992        | DefKind::Macro(..)
993        | DefKind::Field => true,
994        DefKind::Use
995        | DefKind::ForeignMod
996        | DefKind::TyParam
997        | DefKind::ConstParam
998        | DefKind::LifetimeParam
999        | DefKind::AnonConst
1000        | DefKind::InlineConst
1001        | DefKind::Static { nested: true, .. }
1002        | DefKind::OpaqueTy
1003        | DefKind::GlobalAsm
1004        | DefKind::Impl { .. }
1005        | DefKind::Closure
1006        | DefKind::ExternCrate
1007        | DefKind::SyntheticCoroutineBody => false,
1008    }
1009}
1010
1011fn should_encode_stability(def_kind: DefKind) -> bool {
1012    match def_kind {
1013        DefKind::Mod
1014        | DefKind::Ctor(..)
1015        | DefKind::Variant
1016        | DefKind::Field
1017        | DefKind::Struct
1018        | DefKind::AssocTy
1019        | DefKind::AssocFn
1020        | DefKind::AssocConst
1021        | DefKind::TyParam
1022        | DefKind::ConstParam
1023        | DefKind::Static { .. }
1024        | DefKind::Const
1025        | DefKind::Fn
1026        | DefKind::ForeignMod
1027        | DefKind::TyAlias
1028        | DefKind::OpaqueTy
1029        | DefKind::Enum
1030        | DefKind::Union
1031        | DefKind::Impl { .. }
1032        | DefKind::Trait
1033        | DefKind::TraitAlias
1034        | DefKind::Macro(..)
1035        | DefKind::ForeignTy => true,
1036        DefKind::Use
1037        | DefKind::LifetimeParam
1038        | DefKind::AnonConst
1039        | DefKind::InlineConst
1040        | DefKind::GlobalAsm
1041        | DefKind::Closure
1042        | DefKind::ExternCrate
1043        | DefKind::SyntheticCoroutineBody => false,
1044    }
1045}
1046
1047/// Whether we should encode MIR. Return a pair, resp. for CTFE and for LLVM.
1048///
1049/// Computing, optimizing and encoding the MIR is a relatively expensive operation.
1050/// We want to avoid this work when not required. Therefore:
1051/// - we only compute `mir_for_ctfe` on items with const-eval semantics;
1052/// - we skip `optimized_mir` for check runs.
1053/// - we only encode `optimized_mir` that could be generated in other crates, that is, a code that
1054///   is either generic or has inline hint, and is reachable from the other crates (contained
1055///   in reachable set).
1056///
1057/// Note: Reachable set describes definitions that might be generated or referenced from other
1058/// crates and it can be used to limit optimized MIR that needs to be encoded. On the other hand,
1059/// the reachable set doesn't have much to say about which definitions might be evaluated at compile
1060/// time in other crates, so it cannot be used to omit CTFE MIR. For example, `f` below is
1061/// unreachable and yet it can be evaluated in other crates:
1062///
1063/// ```
1064/// const fn f() -> usize { 0 }
1065/// pub struct S { pub a: [usize; f()] }
1066/// ```
1067fn should_encode_mir(
1068    tcx: TyCtxt<'_>,
1069    reachable_set: &LocalDefIdSet,
1070    def_id: LocalDefId,
1071) -> (bool, bool) {
1072    match tcx.def_kind(def_id) {
1073        // Constructors
1074        DefKind::Ctor(_, _) => {
1075            let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
1076                || tcx.sess.opts.unstable_opts.always_encode_mir;
1077            (true, mir_opt_base)
1078        }
1079        // Constants
1080        DefKind::AnonConst | DefKind::InlineConst | DefKind::AssocConst | DefKind::Const => {
1081            (true, false)
1082        }
1083        // Coroutines require optimized MIR to compute layout.
1084        DefKind::Closure if tcx.is_coroutine(def_id.to_def_id()) => (false, true),
1085        DefKind::SyntheticCoroutineBody => (false, true),
1086        // Full-fledged functions + closures
1087        DefKind::AssocFn | DefKind::Fn | DefKind::Closure => {
1088            let generics = tcx.generics_of(def_id);
1089            let opt = tcx.sess.opts.unstable_opts.always_encode_mir
1090                || (tcx.sess.opts.output_types.should_codegen()
1091                    && reachable_set.contains(&def_id)
1092                    && (generics.requires_monomorphization(tcx)
1093                        || tcx.cross_crate_inlinable(def_id)));
1094            // The function has a `const` modifier or is in a `#[const_trait]`.
1095            let is_const_fn = tcx.is_const_fn(def_id.to_def_id())
1096                || tcx.is_const_default_method(def_id.to_def_id());
1097            (is_const_fn, opt)
1098        }
1099        // The others don't have MIR.
1100        _ => (false, false),
1101    }
1102}
1103
1104fn should_encode_variances<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: DefKind) -> bool {
1105    match def_kind {
1106        DefKind::Struct
1107        | DefKind::Union
1108        | DefKind::Enum
1109        | DefKind::OpaqueTy
1110        | DefKind::Fn
1111        | DefKind::Ctor(..)
1112        | DefKind::AssocFn => true,
1113        DefKind::AssocTy => {
1114            // Only encode variances for RPITITs (for traits)
1115            matches!(tcx.opt_rpitit_info(def_id), Some(ty::ImplTraitInTraitData::Trait { .. }))
1116        }
1117        DefKind::Mod
1118        | DefKind::Variant
1119        | DefKind::Field
1120        | DefKind::AssocConst
1121        | DefKind::TyParam
1122        | DefKind::ConstParam
1123        | DefKind::Static { .. }
1124        | DefKind::Const
1125        | DefKind::ForeignMod
1126        | DefKind::Impl { .. }
1127        | DefKind::Trait
1128        | DefKind::TraitAlias
1129        | DefKind::Macro(..)
1130        | DefKind::ForeignTy
1131        | DefKind::Use
1132        | DefKind::LifetimeParam
1133        | DefKind::AnonConst
1134        | DefKind::InlineConst
1135        | DefKind::GlobalAsm
1136        | DefKind::Closure
1137        | DefKind::ExternCrate
1138        | DefKind::SyntheticCoroutineBody => false,
1139        DefKind::TyAlias => tcx.type_alias_is_lazy(def_id),
1140    }
1141}
1142
1143fn should_encode_generics(def_kind: DefKind) -> bool {
1144    match def_kind {
1145        DefKind::Struct
1146        | DefKind::Union
1147        | DefKind::Enum
1148        | DefKind::Variant
1149        | DefKind::Trait
1150        | DefKind::TyAlias
1151        | DefKind::ForeignTy
1152        | DefKind::TraitAlias
1153        | DefKind::AssocTy
1154        | DefKind::Fn
1155        | DefKind::Const
1156        | DefKind::Static { .. }
1157        | DefKind::Ctor(..)
1158        | DefKind::AssocFn
1159        | DefKind::AssocConst
1160        | DefKind::AnonConst
1161        | DefKind::InlineConst
1162        | DefKind::OpaqueTy
1163        | DefKind::Impl { .. }
1164        | DefKind::Field
1165        | DefKind::TyParam
1166        | DefKind::Closure
1167        | DefKind::SyntheticCoroutineBody => true,
1168        DefKind::Mod
1169        | DefKind::ForeignMod
1170        | DefKind::ConstParam
1171        | DefKind::Macro(..)
1172        | DefKind::Use
1173        | DefKind::LifetimeParam
1174        | DefKind::GlobalAsm
1175        | DefKind::ExternCrate => false,
1176    }
1177}
1178
1179fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> bool {
1180    match def_kind {
1181        DefKind::Struct
1182        | DefKind::Union
1183        | DefKind::Enum
1184        | DefKind::Variant
1185        | DefKind::Ctor(..)
1186        | DefKind::Field
1187        | DefKind::Fn
1188        | DefKind::Const
1189        | DefKind::Static { nested: false, .. }
1190        | DefKind::TyAlias
1191        | DefKind::ForeignTy
1192        | DefKind::Impl { .. }
1193        | DefKind::AssocFn
1194        | DefKind::AssocConst
1195        | DefKind::Closure
1196        | DefKind::ConstParam
1197        | DefKind::AnonConst
1198        | DefKind::InlineConst
1199        | DefKind::SyntheticCoroutineBody => true,
1200
1201        DefKind::OpaqueTy => {
1202            let origin = tcx.local_opaque_ty_origin(def_id);
1203            if let hir::OpaqueTyOrigin::FnReturn { parent, .. }
1204            | hir::OpaqueTyOrigin::AsyncFn { parent, .. } = origin
1205                && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(parent)
1206                && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
1207            {
1208                false
1209            } else {
1210                true
1211            }
1212        }
1213
1214        DefKind::AssocTy => {
1215            let assoc_item = tcx.associated_item(def_id);
1216            match assoc_item.container {
1217                ty::AssocItemContainer::Impl => true,
1218                ty::AssocItemContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1219            }
1220        }
1221        DefKind::TyParam => {
1222            let hir::Node::GenericParam(param) = tcx.hir_node_by_def_id(def_id) else { bug!() };
1223            let hir::GenericParamKind::Type { default, .. } = param.kind else { bug!() };
1224            default.is_some()
1225        }
1226
1227        DefKind::Trait
1228        | DefKind::TraitAlias
1229        | DefKind::Mod
1230        | DefKind::ForeignMod
1231        | DefKind::Macro(..)
1232        | DefKind::Static { nested: true, .. }
1233        | DefKind::Use
1234        | DefKind::LifetimeParam
1235        | DefKind::GlobalAsm
1236        | DefKind::ExternCrate => false,
1237    }
1238}
1239
1240fn should_encode_fn_sig(def_kind: DefKind) -> bool {
1241    match def_kind {
1242        DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) => true,
1243
1244        DefKind::Struct
1245        | DefKind::Union
1246        | DefKind::Enum
1247        | DefKind::Variant
1248        | DefKind::Field
1249        | DefKind::Const
1250        | DefKind::Static { .. }
1251        | DefKind::Ctor(..)
1252        | DefKind::TyAlias
1253        | DefKind::OpaqueTy
1254        | DefKind::ForeignTy
1255        | DefKind::Impl { .. }
1256        | DefKind::AssocConst
1257        | DefKind::Closure
1258        | DefKind::ConstParam
1259        | DefKind::AnonConst
1260        | DefKind::InlineConst
1261        | DefKind::AssocTy
1262        | DefKind::TyParam
1263        | DefKind::Trait
1264        | DefKind::TraitAlias
1265        | DefKind::Mod
1266        | DefKind::ForeignMod
1267        | DefKind::Macro(..)
1268        | DefKind::Use
1269        | DefKind::LifetimeParam
1270        | DefKind::GlobalAsm
1271        | DefKind::ExternCrate
1272        | DefKind::SyntheticCoroutineBody => false,
1273    }
1274}
1275
1276fn should_encode_constness(def_kind: DefKind) -> bool {
1277    match def_kind {
1278        DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::Ctor(_, CtorKind::Fn) => true,
1279
1280        DefKind::Struct
1281        | DefKind::Union
1282        | DefKind::Enum
1283        | DefKind::Field
1284        | DefKind::Const
1285        | DefKind::AssocConst
1286        | DefKind::AnonConst
1287        | DefKind::Static { .. }
1288        | DefKind::TyAlias
1289        | DefKind::OpaqueTy
1290        | DefKind::Impl { .. }
1291        | DefKind::ForeignTy
1292        | DefKind::ConstParam
1293        | DefKind::InlineConst
1294        | DefKind::AssocTy
1295        | DefKind::TyParam
1296        | DefKind::Trait
1297        | DefKind::TraitAlias
1298        | DefKind::Mod
1299        | DefKind::ForeignMod
1300        | DefKind::Macro(..)
1301        | DefKind::Use
1302        | DefKind::LifetimeParam
1303        | DefKind::GlobalAsm
1304        | DefKind::ExternCrate
1305        | DefKind::Ctor(_, CtorKind::Const)
1306        | DefKind::Variant
1307        | DefKind::SyntheticCoroutineBody => false,
1308    }
1309}
1310
1311fn should_encode_const(def_kind: DefKind) -> bool {
1312    match def_kind {
1313        DefKind::Const | DefKind::AssocConst | DefKind::AnonConst | DefKind::InlineConst => true,
1314
1315        DefKind::Struct
1316        | DefKind::Union
1317        | DefKind::Enum
1318        | DefKind::Variant
1319        | DefKind::Ctor(..)
1320        | DefKind::Field
1321        | DefKind::Fn
1322        | DefKind::Static { .. }
1323        | DefKind::TyAlias
1324        | DefKind::OpaqueTy
1325        | DefKind::ForeignTy
1326        | DefKind::Impl { .. }
1327        | DefKind::AssocFn
1328        | DefKind::Closure
1329        | DefKind::ConstParam
1330        | DefKind::AssocTy
1331        | DefKind::TyParam
1332        | DefKind::Trait
1333        | DefKind::TraitAlias
1334        | DefKind::Mod
1335        | DefKind::ForeignMod
1336        | DefKind::Macro(..)
1337        | DefKind::Use
1338        | DefKind::LifetimeParam
1339        | DefKind::GlobalAsm
1340        | DefKind::ExternCrate
1341        | DefKind::SyntheticCoroutineBody => false,
1342    }
1343}
1344
1345fn should_encode_fn_impl_trait_in_trait<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
1346    if let Some(assoc_item) = tcx.opt_associated_item(def_id)
1347        && assoc_item.container == ty::AssocItemContainer::Trait
1348        && assoc_item.is_fn()
1349    {
1350        true
1351    } else {
1352        false
1353    }
1354}
1355
1356impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1357    fn encode_attrs(&mut self, def_id: LocalDefId) {
1358        let tcx = self.tcx;
1359        let mut state = AnalyzeAttrState {
1360            is_exported: tcx.effective_visibilities(()).is_exported(def_id),
1361            is_doc_hidden: false,
1362            features: &tcx.features(),
1363        };
1364        let attr_iter = tcx
1365            .hir_attrs(tcx.local_def_id_to_hir_id(def_id))
1366            .iter()
1367            .filter(|attr| analyze_attr(*attr, &mut state));
1368
1369        record_array!(self.tables.attributes[def_id.to_def_id()] <- attr_iter);
1370
1371        let mut attr_flags = AttrFlags::empty();
1372        if state.is_doc_hidden {
1373            attr_flags |= AttrFlags::IS_DOC_HIDDEN;
1374        }
1375        self.tables.attr_flags.set(def_id.local_def_index, attr_flags);
1376    }
1377
1378    fn encode_def_ids(&mut self) {
1379        self.encode_info_for_mod(CRATE_DEF_ID);
1380
1381        // Proc-macro crates only export proc-macro items, which are looked
1382        // up using `proc_macro_data`
1383        if self.is_proc_macro {
1384            return;
1385        }
1386
1387        let tcx = self.tcx;
1388
1389        for local_id in tcx.iter_local_def_id() {
1390            let def_id = local_id.to_def_id();
1391            let def_kind = tcx.def_kind(local_id);
1392            self.tables.def_kind.set_some(def_id.index, def_kind);
1393
1394            // The `DefCollector` will sometimes create unnecessary `DefId`s
1395            // for trivial const arguments which are directly lowered to
1396            // `ConstArgKind::Path`. We never actually access this `DefId`
1397            // anywhere so we don't need to encode it for other crates.
1398            if def_kind == DefKind::AnonConst
1399                && match tcx.hir_node_by_def_id(local_id) {
1400                    hir::Node::ConstArg(hir::ConstArg { kind, .. }) => match kind {
1401                        // Skip encoding defs for these as they should not have had a `DefId` created
1402                        hir::ConstArgKind::Path(..) | hir::ConstArgKind::Infer(..) => true,
1403                        hir::ConstArgKind::Anon(..) => false,
1404                    },
1405                    _ => false,
1406                }
1407            {
1408                continue;
1409            }
1410
1411            if def_kind == DefKind::Field
1412                && let hir::Node::Field(field) = tcx.hir_node_by_def_id(local_id)
1413                && let Some(anon) = field.default
1414            {
1415                record!(self.tables.default_fields[def_id] <- anon.def_id.to_def_id());
1416            }
1417
1418            if should_encode_span(def_kind) {
1419                let def_span = tcx.def_span(local_id);
1420                record!(self.tables.def_span[def_id] <- def_span);
1421            }
1422            if should_encode_attrs(def_kind) {
1423                self.encode_attrs(local_id);
1424            }
1425            if should_encode_expn_that_defined(def_kind) {
1426                record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
1427            }
1428            if should_encode_span(def_kind)
1429                && let Some(ident_span) = tcx.def_ident_span(def_id)
1430            {
1431                record!(self.tables.def_ident_span[def_id] <- ident_span);
1432            }
1433            if def_kind.has_codegen_attrs() {
1434                record!(self.tables.codegen_fn_attrs[def_id] <- self.tcx.codegen_fn_attrs(def_id));
1435            }
1436            if should_encode_visibility(def_kind) {
1437                let vis =
1438                    self.tcx.local_visibility(local_id).map_id(|def_id| def_id.local_def_index);
1439                record!(self.tables.visibility[def_id] <- vis);
1440            }
1441            if should_encode_stability(def_kind) {
1442                self.encode_stability(def_id);
1443                self.encode_const_stability(def_id);
1444                self.encode_default_body_stability(def_id);
1445                self.encode_deprecation(def_id);
1446            }
1447            if should_encode_variances(tcx, def_id, def_kind) {
1448                let v = self.tcx.variances_of(def_id);
1449                record_array!(self.tables.variances_of[def_id] <- v);
1450            }
1451            if should_encode_fn_sig(def_kind) {
1452                record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1453            }
1454            if should_encode_generics(def_kind) {
1455                let g = tcx.generics_of(def_id);
1456                record!(self.tables.generics_of[def_id] <- g);
1457                record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id));
1458                let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1459                record_defaulted_array!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives);
1460
1461                for param in &g.own_params {
1462                    if let ty::GenericParamDefKind::Const { has_default: true, .. } = param.kind {
1463                        let default = self.tcx.const_param_default(param.def_id);
1464                        record!(self.tables.const_param_default[param.def_id] <- default);
1465                    }
1466                }
1467            }
1468            if tcx.is_conditionally_const(def_id) {
1469                record!(self.tables.const_conditions[def_id] <- self.tcx.const_conditions(def_id));
1470            }
1471            if should_encode_type(tcx, local_id, def_kind) {
1472                record!(self.tables.type_of[def_id] <- self.tcx.type_of(def_id));
1473            }
1474            if should_encode_constness(def_kind) {
1475                self.tables.constness.set_some(def_id.index, self.tcx.constness(def_id));
1476            }
1477            if let DefKind::Fn | DefKind::AssocFn = def_kind {
1478                self.tables.asyncness.set_some(def_id.index, tcx.asyncness(def_id));
1479                record_array!(self.tables.fn_arg_idents[def_id] <- tcx.fn_arg_idents(def_id));
1480            }
1481            if let Some(name) = tcx.intrinsic(def_id) {
1482                record!(self.tables.intrinsic[def_id] <- name);
1483            }
1484            if let DefKind::TyParam = def_kind {
1485                let default = self.tcx.object_lifetime_default(def_id);
1486                record!(self.tables.object_lifetime_default[def_id] <- default);
1487            }
1488            if let DefKind::Trait = def_kind {
1489                record!(self.tables.trait_def[def_id] <- self.tcx.trait_def(def_id));
1490                record_defaulted_array!(self.tables.explicit_super_predicates_of[def_id] <-
1491                    self.tcx.explicit_super_predicates_of(def_id).skip_binder());
1492                record_defaulted_array!(self.tables.explicit_implied_predicates_of[def_id] <-
1493                    self.tcx.explicit_implied_predicates_of(def_id).skip_binder());
1494                let module_children = self.tcx.module_children_local(local_id);
1495                record_array!(self.tables.module_children_non_reexports[def_id] <-
1496                    module_children.iter().map(|child| child.res.def_id().index));
1497                if self.tcx.is_const_trait(def_id) {
1498                    record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1499                        <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1500                }
1501            }
1502            if let DefKind::TraitAlias = def_kind {
1503                record!(self.tables.trait_def[def_id] <- self.tcx.trait_def(def_id));
1504                record_defaulted_array!(self.tables.explicit_super_predicates_of[def_id] <-
1505                    self.tcx.explicit_super_predicates_of(def_id).skip_binder());
1506                record_defaulted_array!(self.tables.explicit_implied_predicates_of[def_id] <-
1507                    self.tcx.explicit_implied_predicates_of(def_id).skip_binder());
1508            }
1509            if let DefKind::Trait | DefKind::Impl { .. } = def_kind {
1510                let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1511                record_array!(self.tables.associated_item_or_field_def_ids[def_id] <-
1512                    associated_item_def_ids.iter().map(|&def_id| {
1513                        assert!(def_id.is_local());
1514                        def_id.index
1515                    })
1516                );
1517                for &def_id in associated_item_def_ids {
1518                    self.encode_info_for_assoc_item(def_id);
1519                }
1520            }
1521            if let DefKind::Closure | DefKind::SyntheticCoroutineBody = def_kind
1522                && let Some(coroutine_kind) = self.tcx.coroutine_kind(def_id)
1523            {
1524                self.tables.coroutine_kind.set(def_id.index, Some(coroutine_kind))
1525            }
1526            if def_kind == DefKind::Closure
1527                && tcx.type_of(def_id).skip_binder().is_coroutine_closure()
1528            {
1529                let coroutine_for_closure = self.tcx.coroutine_for_closure(def_id);
1530                self.tables
1531                    .coroutine_for_closure
1532                    .set_some(def_id.index, coroutine_for_closure.into());
1533
1534                // If this async closure has a by-move body, record it too.
1535                if tcx.needs_coroutine_by_move_body_def_id(coroutine_for_closure) {
1536                    self.tables.coroutine_by_move_body_def_id.set_some(
1537                        coroutine_for_closure.index,
1538                        self.tcx.coroutine_by_move_body_def_id(coroutine_for_closure).into(),
1539                    );
1540                }
1541            }
1542            if let DefKind::Static { .. } = def_kind {
1543                if !self.tcx.is_foreign_item(def_id) {
1544                    let data = self.tcx.eval_static_initializer(def_id).unwrap();
1545                    record!(self.tables.eval_static_initializer[def_id] <- data);
1546                }
1547            }
1548            if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind {
1549                self.encode_info_for_adt(local_id);
1550            }
1551            if let DefKind::Mod = def_kind {
1552                self.encode_info_for_mod(local_id);
1553            }
1554            if let DefKind::Macro(_) = def_kind {
1555                self.encode_info_for_macro(local_id);
1556            }
1557            if let DefKind::TyAlias = def_kind {
1558                self.tables
1559                    .type_alias_is_lazy
1560                    .set(def_id.index, self.tcx.type_alias_is_lazy(def_id));
1561            }
1562            if let DefKind::OpaqueTy = def_kind {
1563                self.encode_explicit_item_bounds(def_id);
1564                self.encode_explicit_item_self_bounds(def_id);
1565                record!(self.tables.opaque_ty_origin[def_id] <- self.tcx.opaque_ty_origin(def_id));
1566                self.encode_precise_capturing_args(def_id);
1567                if tcx.is_conditionally_const(def_id) {
1568                    record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1569                        <- tcx.explicit_implied_const_bounds(def_id).skip_binder());
1570                }
1571            }
1572            if tcx.impl_method_has_trait_impl_trait_tys(def_id)
1573                && let Ok(table) = self.tcx.collect_return_position_impl_trait_in_trait_tys(def_id)
1574            {
1575                record!(self.tables.trait_impl_trait_tys[def_id] <- table);
1576            }
1577            if should_encode_fn_impl_trait_in_trait(tcx, def_id) {
1578                let table = tcx.associated_types_for_impl_traits_in_associated_fn(def_id);
1579                record_defaulted_array!(self.tables.associated_types_for_impl_traits_in_associated_fn[def_id] <- table);
1580            }
1581        }
1582
1583        for (def_id, impls) in &tcx.crate_inherent_impls(()).0.inherent_impls {
1584            record_defaulted_array!(self.tables.inherent_impls[def_id.to_def_id()] <- impls.iter().map(|def_id| {
1585                assert!(def_id.is_local());
1586                def_id.index
1587            }));
1588        }
1589
1590        for (def_id, res_map) in &tcx.resolutions(()).doc_link_resolutions {
1591            record!(self.tables.doc_link_resolutions[def_id.to_def_id()] <- res_map);
1592        }
1593
1594        for (def_id, traits) in &tcx.resolutions(()).doc_link_traits_in_scope {
1595            record_array!(self.tables.doc_link_traits_in_scope[def_id.to_def_id()] <- traits);
1596        }
1597    }
1598
1599    #[instrument(level = "trace", skip(self))]
1600    fn encode_info_for_adt(&mut self, local_def_id: LocalDefId) {
1601        let def_id = local_def_id.to_def_id();
1602        let tcx = self.tcx;
1603        let adt_def = tcx.adt_def(def_id);
1604        record!(self.tables.repr_options[def_id] <- adt_def.repr());
1605
1606        let params_in_repr = self.tcx.params_in_repr(def_id);
1607        record!(self.tables.params_in_repr[def_id] <- params_in_repr);
1608
1609        if adt_def.is_enum() {
1610            let module_children = tcx.module_children_local(local_def_id);
1611            record_array!(self.tables.module_children_non_reexports[def_id] <-
1612                module_children.iter().map(|child| child.res.def_id().index));
1613        } else {
1614            // For non-enum, there is only one variant, and its def_id is the adt's.
1615            debug_assert_eq!(adt_def.variants().len(), 1);
1616            debug_assert_eq!(adt_def.non_enum_variant().def_id, def_id);
1617            // Therefore, the loop over variants will encode its fields as the adt's children.
1618        }
1619
1620        for (idx, variant) in adt_def.variants().iter_enumerated() {
1621            let data = VariantData {
1622                discr: variant.discr,
1623                idx,
1624                ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)),
1625                is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1626            };
1627            record!(self.tables.variant_data[variant.def_id] <- data);
1628
1629            record_array!(self.tables.associated_item_or_field_def_ids[variant.def_id] <- variant.fields.iter().map(|f| {
1630                assert!(f.did.is_local());
1631                f.did.index
1632            }));
1633
1634            for field in &variant.fields {
1635                self.tables.safety.set_some(field.did.index, field.safety);
1636            }
1637
1638            if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
1639                let fn_sig = tcx.fn_sig(ctor_def_id);
1640                // FIXME only encode signature for ctor_def_id
1641                record!(self.tables.fn_sig[variant.def_id] <- fn_sig);
1642            }
1643        }
1644
1645        if let Some(destructor) = tcx.adt_destructor(local_def_id) {
1646            record!(self.tables.adt_destructor[def_id] <- destructor);
1647        }
1648
1649        if let Some(destructor) = tcx.adt_async_destructor(local_def_id) {
1650            record!(self.tables.adt_async_destructor[def_id] <- destructor);
1651        }
1652    }
1653
1654    #[instrument(level = "debug", skip(self))]
1655    fn encode_info_for_mod(&mut self, local_def_id: LocalDefId) {
1656        let tcx = self.tcx;
1657        let def_id = local_def_id.to_def_id();
1658
1659        // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1660        // only ever get called for the crate root. We still want to encode
1661        // the crate root for consistency with other crates (some of the resolver
1662        // code uses it). However, we skip encoding anything relating to child
1663        // items - we encode information about proc-macros later on.
1664        if self.is_proc_macro {
1665            // Encode this here because we don't do it in encode_def_ids.
1666            record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1667        } else {
1668            let module_children = tcx.module_children_local(local_def_id);
1669
1670            record_array!(self.tables.module_children_non_reexports[def_id] <-
1671                module_children.iter().filter(|child| child.reexport_chain.is_empty())
1672                    .map(|child| child.res.def_id().index));
1673
1674            record_defaulted_array!(self.tables.module_children_reexports[def_id] <-
1675                module_children.iter().filter(|child| !child.reexport_chain.is_empty()));
1676        }
1677    }
1678
1679    fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1680        debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1681        let bounds = self.tcx.explicit_item_bounds(def_id).skip_binder();
1682        record_defaulted_array!(self.tables.explicit_item_bounds[def_id] <- bounds);
1683    }
1684
1685    fn encode_explicit_item_self_bounds(&mut self, def_id: DefId) {
1686        debug!("EncodeContext::encode_explicit_item_self_bounds({:?})", def_id);
1687        let bounds = self.tcx.explicit_item_self_bounds(def_id).skip_binder();
1688        record_defaulted_array!(self.tables.explicit_item_self_bounds[def_id] <- bounds);
1689    }
1690
1691    #[instrument(level = "debug", skip(self))]
1692    fn encode_info_for_assoc_item(&mut self, def_id: DefId) {
1693        let tcx = self.tcx;
1694        let item = tcx.associated_item(def_id);
1695
1696        self.tables.defaultness.set_some(def_id.index, item.defaultness(tcx));
1697        self.tables.assoc_container.set_some(def_id.index, item.container);
1698
1699        match item.container {
1700            AssocItemContainer::Trait => {
1701                if item.is_type() {
1702                    self.encode_explicit_item_bounds(def_id);
1703                    self.encode_explicit_item_self_bounds(def_id);
1704                    if tcx.is_conditionally_const(def_id) {
1705                        record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1706                            <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1707                    }
1708                }
1709            }
1710            AssocItemContainer::Impl => {
1711                if let Some(trait_item_def_id) = item.trait_item_def_id {
1712                    self.tables.trait_item_def_id.set_some(def_id.index, trait_item_def_id.into());
1713                }
1714            }
1715        }
1716        if let ty::AssocKind::Type { data: ty::AssocTypeData::Rpitit(rpitit_info) } = item.kind {
1717            record!(self.tables.opt_rpitit_info[def_id] <- rpitit_info);
1718            if matches!(rpitit_info, ty::ImplTraitInTraitData::Trait { .. }) {
1719                record_array!(
1720                    self.tables.assumed_wf_types_for_rpitit[def_id]
1721                        <- self.tcx.assumed_wf_types_for_rpitit(def_id)
1722                );
1723                self.encode_precise_capturing_args(def_id);
1724            }
1725        }
1726    }
1727
1728    fn encode_precise_capturing_args(&mut self, def_id: DefId) {
1729        let Some(precise_capturing_args) = self.tcx.rendered_precise_capturing_args(def_id) else {
1730            return;
1731        };
1732
1733        record_array!(self.tables.rendered_precise_capturing_args[def_id] <- precise_capturing_args);
1734    }
1735
1736    fn encode_mir(&mut self) {
1737        if self.is_proc_macro {
1738            return;
1739        }
1740
1741        let tcx = self.tcx;
1742        let reachable_set = tcx.reachable_set(());
1743
1744        let keys_and_jobs = tcx.mir_keys(()).iter().filter_map(|&def_id| {
1745            let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
1746            if encode_const || encode_opt { Some((def_id, encode_const, encode_opt)) } else { None }
1747        });
1748        for (def_id, encode_const, encode_opt) in keys_and_jobs {
1749            debug_assert!(encode_const || encode_opt);
1750
1751            debug!("EntryBuilder::encode_mir({:?})", def_id);
1752            if encode_opt {
1753                record!(self.tables.optimized_mir[def_id.to_def_id()] <- tcx.optimized_mir(def_id));
1754                self.tables
1755                    .cross_crate_inlinable
1756                    .set(def_id.to_def_id().index, self.tcx.cross_crate_inlinable(def_id));
1757                record!(self.tables.closure_saved_names_of_captured_variables[def_id.to_def_id()]
1758                    <- tcx.closure_saved_names_of_captured_variables(def_id));
1759
1760                if self.tcx.is_coroutine(def_id.to_def_id())
1761                    && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1762                {
1763                    record!(self.tables.mir_coroutine_witnesses[def_id.to_def_id()] <- witnesses);
1764                }
1765            }
1766            if encode_const {
1767                record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- tcx.mir_for_ctfe(def_id));
1768
1769                // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1770                let abstract_const = tcx.thir_abstract_const(def_id);
1771                if let Ok(Some(abstract_const)) = abstract_const {
1772                    record!(self.tables.thir_abstract_const[def_id.to_def_id()] <- abstract_const);
1773                }
1774
1775                if should_encode_const(tcx.def_kind(def_id)) {
1776                    let qualifs = tcx.mir_const_qualif(def_id);
1777                    record!(self.tables.mir_const_qualif[def_id.to_def_id()] <- qualifs);
1778                    let body = tcx.hir_maybe_body_owned_by(def_id);
1779                    if let Some(body) = body {
1780                        let const_data = rendered_const(self.tcx, &body, def_id);
1781                        record!(self.tables.rendered_const[def_id.to_def_id()] <- const_data);
1782                    }
1783                }
1784            }
1785            record!(self.tables.promoted_mir[def_id.to_def_id()] <- tcx.promoted_mir(def_id));
1786
1787            if self.tcx.is_coroutine(def_id.to_def_id())
1788                && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1789            {
1790                record!(self.tables.mir_coroutine_witnesses[def_id.to_def_id()] <- witnesses);
1791            }
1792        }
1793
1794        // Encode all the deduced parameter attributes for everything that has MIR, even for items
1795        // that can't be inlined. But don't if we aren't optimizing in non-incremental mode, to
1796        // save the query traffic.
1797        if tcx.sess.opts.output_types.should_codegen()
1798            && tcx.sess.opts.optimize != OptLevel::No
1799            && tcx.sess.opts.incremental.is_none()
1800        {
1801            for &local_def_id in tcx.mir_keys(()) {
1802                if let DefKind::AssocFn | DefKind::Fn = tcx.def_kind(local_def_id) {
1803                    record_array!(self.tables.deduced_param_attrs[local_def_id.to_def_id()] <-
1804                        self.tcx.deduced_param_attrs(local_def_id.to_def_id()));
1805                }
1806            }
1807        }
1808    }
1809
1810    #[instrument(level = "debug", skip(self))]
1811    fn encode_stability(&mut self, def_id: DefId) {
1812        // The query lookup can take a measurable amount of time in crates with many items. Check if
1813        // the stability attributes are even enabled before using their queries.
1814        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1815            if let Some(stab) = self.tcx.lookup_stability(def_id) {
1816                record!(self.tables.lookup_stability[def_id] <- stab)
1817            }
1818        }
1819    }
1820
1821    #[instrument(level = "debug", skip(self))]
1822    fn encode_const_stability(&mut self, def_id: DefId) {
1823        // The query lookup can take a measurable amount of time in crates with many items. Check if
1824        // the stability attributes are even enabled before using their queries.
1825        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1826            if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1827                record!(self.tables.lookup_const_stability[def_id] <- stab)
1828            }
1829        }
1830    }
1831
1832    #[instrument(level = "debug", skip(self))]
1833    fn encode_default_body_stability(&mut self, def_id: DefId) {
1834        // The query lookup can take a measurable amount of time in crates with many items. Check if
1835        // the stability attributes are even enabled before using their queries.
1836        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1837            if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
1838                record!(self.tables.lookup_default_body_stability[def_id] <- stab)
1839            }
1840        }
1841    }
1842
1843    #[instrument(level = "debug", skip(self))]
1844    fn encode_deprecation(&mut self, def_id: DefId) {
1845        if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1846            record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1847        }
1848    }
1849
1850    #[instrument(level = "debug", skip(self))]
1851    fn encode_info_for_macro(&mut self, def_id: LocalDefId) {
1852        let tcx = self.tcx;
1853
1854        let (_, macro_def, _) = tcx.hir_expect_item(def_id).expect_macro();
1855        self.tables.is_macro_rules.set(def_id.local_def_index, macro_def.macro_rules);
1856        record!(self.tables.macro_definition[def_id.to_def_id()] <- &*macro_def.body);
1857    }
1858
1859    fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
1860        empty_proc_macro!(self);
1861        let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1862        self.lazy_array(used_libraries.iter())
1863    }
1864
1865    fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
1866        empty_proc_macro!(self);
1867        let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1868        self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
1869    }
1870
1871    fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1872        let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1873        let mut expn_data_table: TableBuilder<_, _> = Default::default();
1874        let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1875
1876        self.hygiene_ctxt.encode(
1877            &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1878            |(this, syntax_contexts, _, _), index, ctxt_data| {
1879                syntax_contexts.set_some(index, this.lazy(ctxt_data));
1880            },
1881            |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1882                if let Some(index) = index.as_local() {
1883                    expn_data_table.set_some(index.as_raw(), this.lazy(expn_data));
1884                    expn_hash_table.set_some(index.as_raw(), this.lazy(hash));
1885                }
1886            },
1887        );
1888
1889        (
1890            syntax_contexts.encode(&mut self.opaque),
1891            expn_data_table.encode(&mut self.opaque),
1892            expn_hash_table.encode(&mut self.opaque),
1893        )
1894    }
1895
1896    fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1897        let is_proc_macro = self.tcx.crate_types().contains(&CrateType::ProcMacro);
1898        if is_proc_macro {
1899            let tcx = self.tcx;
1900            let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1901            let stability = tcx.lookup_stability(CRATE_DEF_ID);
1902            let macros =
1903                self.lazy_array(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1904            for (i, span) in self.tcx.sess.psess.proc_macro_quoted_spans() {
1905                let span = self.lazy(span);
1906                self.tables.proc_macro_quoted_spans.set_some(i, span);
1907            }
1908
1909            self.tables.def_kind.set_some(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
1910            record!(self.tables.def_span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1911            self.encode_attrs(LOCAL_CRATE.as_def_id().expect_local());
1912            let vis = tcx.local_visibility(CRATE_DEF_ID).map_id(|def_id| def_id.local_def_index);
1913            record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- vis);
1914            if let Some(stability) = stability {
1915                record!(self.tables.lookup_stability[LOCAL_CRATE.as_def_id()] <- stability);
1916            }
1917            self.encode_deprecation(LOCAL_CRATE.as_def_id());
1918            if let Some(res_map) = tcx.resolutions(()).doc_link_resolutions.get(&CRATE_DEF_ID) {
1919                record!(self.tables.doc_link_resolutions[LOCAL_CRATE.as_def_id()] <- res_map);
1920            }
1921            if let Some(traits) = tcx.resolutions(()).doc_link_traits_in_scope.get(&CRATE_DEF_ID) {
1922                record_array!(self.tables.doc_link_traits_in_scope[LOCAL_CRATE.as_def_id()] <- traits);
1923            }
1924
1925            // Normally, this information is encoded when we walk the items
1926            // defined in this crate. However, we skip doing that for proc-macro crates,
1927            // so we manually encode just the information that we need
1928            for &proc_macro in &tcx.resolutions(()).proc_macros {
1929                let id = proc_macro;
1930                let proc_macro = tcx.local_def_id_to_hir_id(proc_macro);
1931                let mut name = tcx.hir_name(proc_macro);
1932                let span = tcx.hir_span(proc_macro);
1933                // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1934                // so downstream crates need access to them.
1935                let attrs = tcx.hir_attrs(proc_macro);
1936                let macro_kind = if ast::attr::contains_name(attrs, sym::proc_macro) {
1937                    MacroKind::Bang
1938                } else if ast::attr::contains_name(attrs, sym::proc_macro_attribute) {
1939                    MacroKind::Attr
1940                } else if let Some(attr) = ast::attr::find_by_name(attrs, sym::proc_macro_derive) {
1941                    // This unwrap chain should have been checked by the proc-macro harness.
1942                    name = attr.meta_item_list().unwrap()[0]
1943                        .meta_item()
1944                        .unwrap()
1945                        .ident()
1946                        .unwrap()
1947                        .name;
1948                    MacroKind::Derive
1949                } else {
1950                    bug!("Unknown proc-macro type for item {:?}", id);
1951                };
1952
1953                let mut def_key = self.tcx.hir_def_key(id);
1954                def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1955
1956                let def_id = id.to_def_id();
1957                self.tables.def_kind.set_some(def_id.index, DefKind::Macro(macro_kind));
1958                self.tables.proc_macro.set_some(def_id.index, macro_kind);
1959                self.encode_attrs(id);
1960                record!(self.tables.def_keys[def_id] <- def_key);
1961                record!(self.tables.def_ident_span[def_id] <- span);
1962                record!(self.tables.def_span[def_id] <- span);
1963                record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1964                if let Some(stability) = stability {
1965                    record!(self.tables.lookup_stability[def_id] <- stability);
1966                }
1967            }
1968
1969            Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1970        } else {
1971            None
1972        }
1973    }
1974
1975    fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
1976        empty_proc_macro!(self);
1977        self.lazy_array(
1978            self.tcx
1979                .debugger_visualizers(LOCAL_CRATE)
1980                .iter()
1981                // Erase the path since it may contain privacy sensitive data
1982                // that we don't want to end up in crate metadata.
1983                // The path is only needed for the local crate because of
1984                // `--emit dep-info`.
1985                .map(DebuggerVisualizerFile::path_erased),
1986        )
1987    }
1988
1989    fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
1990        empty_proc_macro!(self);
1991
1992        let deps = self
1993            .tcx
1994            .crates(())
1995            .iter()
1996            .map(|&cnum| {
1997                let dep = CrateDep {
1998                    name: self.tcx.crate_name(cnum),
1999                    hash: self.tcx.crate_hash(cnum),
2000                    host_hash: self.tcx.crate_host_hash(cnum),
2001                    kind: self.tcx.dep_kind(cnum),
2002                    extra_filename: self.tcx.extra_filename(cnum).clone(),
2003                    is_private: self.tcx.is_private_dep(cnum),
2004                };
2005                (cnum, dep)
2006            })
2007            .collect::<Vec<_>>();
2008
2009        {
2010            // Sanity-check the crate numbers
2011            let mut expected_cnum = 1;
2012            for &(n, _) in &deps {
2013                assert_eq!(n, CrateNum::new(expected_cnum));
2014                expected_cnum += 1;
2015            }
2016        }
2017
2018        // We're just going to write a list of crate 'name-hash-version's, with
2019        // the assumption that they are numbered 1 to n.
2020        // FIXME (#2166): This is not nearly enough to support correct versioning
2021        // but is enough to get transitive crate dependencies working.
2022        self.lazy_array(deps.iter().map(|(_, dep)| dep))
2023    }
2024
2025    fn encode_target_modifiers(&mut self) -> LazyArray<TargetModifier> {
2026        empty_proc_macro!(self);
2027        let tcx = self.tcx;
2028        self.lazy_array(tcx.sess.opts.gather_target_modifiers())
2029    }
2030
2031    fn encode_lib_features(&mut self) -> LazyArray<(Symbol, FeatureStability)> {
2032        empty_proc_macro!(self);
2033        let tcx = self.tcx;
2034        let lib_features = tcx.lib_features(LOCAL_CRATE);
2035        self.lazy_array(lib_features.to_sorted_vec())
2036    }
2037
2038    fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
2039        empty_proc_macro!(self);
2040        let tcx = self.tcx;
2041        let implications = tcx.stability_implications(LOCAL_CRATE);
2042        let sorted = implications.to_sorted_stable_ord();
2043        self.lazy_array(sorted.into_iter().map(|(k, v)| (*k, *v)))
2044    }
2045
2046    fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, DefIndex)> {
2047        empty_proc_macro!(self);
2048        let tcx = self.tcx;
2049        let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
2050        self.lazy_array(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
2051    }
2052
2053    fn encode_lang_items(&mut self) -> LazyArray<(DefIndex, LangItem)> {
2054        empty_proc_macro!(self);
2055        let lang_items = self.tcx.lang_items().iter();
2056        self.lazy_array(lang_items.filter_map(|(lang_item, def_id)| {
2057            def_id.as_local().map(|id| (id.local_def_index, lang_item))
2058        }))
2059    }
2060
2061    fn encode_lang_items_missing(&mut self) -> LazyArray<LangItem> {
2062        empty_proc_macro!(self);
2063        let tcx = self.tcx;
2064        self.lazy_array(&tcx.lang_items().missing)
2065    }
2066
2067    fn encode_stripped_cfg_items(&mut self) -> LazyArray<StrippedCfgItem<DefIndex>> {
2068        self.lazy_array(
2069            self.tcx
2070                .stripped_cfg_items(LOCAL_CRATE)
2071                .into_iter()
2072                .map(|item| item.clone().map_mod_id(|def_id| def_id.index)),
2073        )
2074    }
2075
2076    fn encode_traits(&mut self) -> LazyArray<DefIndex> {
2077        empty_proc_macro!(self);
2078        self.lazy_array(self.tcx.traits(LOCAL_CRATE).iter().map(|def_id| def_id.index))
2079    }
2080
2081    /// Encodes an index, mapping each trait to its (local) implementations.
2082    #[instrument(level = "debug", skip(self))]
2083    fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
2084        empty_proc_macro!(self);
2085        let tcx = self.tcx;
2086        let mut trait_impls: FxIndexMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
2087            FxIndexMap::default();
2088
2089        for id in tcx.hir_free_items() {
2090            let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else {
2091                continue;
2092            };
2093            let def_id = id.owner_id.to_def_id();
2094
2095            self.tables.defaultness.set_some(def_id.index, tcx.defaultness(def_id));
2096
2097            if of_trait && let Some(header) = tcx.impl_trait_header(def_id) {
2098                record!(self.tables.impl_trait_header[def_id] <- header);
2099
2100                let trait_ref = header.trait_ref.instantiate_identity();
2101                let simplified_self_ty = fast_reject::simplify_type(
2102                    self.tcx,
2103                    trait_ref.self_ty(),
2104                    TreatParams::InstantiateWithInfer,
2105                );
2106                trait_impls
2107                    .entry(trait_ref.def_id)
2108                    .or_default()
2109                    .push((id.owner_id.def_id.local_def_index, simplified_self_ty));
2110
2111                let trait_def = tcx.trait_def(trait_ref.def_id);
2112                if let Ok(mut an) = trait_def.ancestors(tcx, def_id) {
2113                    if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) {
2114                        self.tables.impl_parent.set_some(def_id.index, parent.into());
2115                    }
2116                }
2117
2118                // if this is an impl of `CoerceUnsized`, create its
2119                // "unsized info", else just store None
2120                if tcx.is_lang_item(trait_ref.def_id, LangItem::CoerceUnsized) {
2121                    let coerce_unsized_info = tcx.coerce_unsized_info(def_id).unwrap();
2122                    record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
2123                }
2124            }
2125        }
2126
2127        let trait_impls: Vec<_> = trait_impls
2128            .into_iter()
2129            .map(|(trait_def_id, impls)| TraitImpls {
2130                trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
2131                impls: self.lazy_array(&impls),
2132            })
2133            .collect();
2134
2135        self.lazy_array(&trait_impls)
2136    }
2137
2138    #[instrument(level = "debug", skip(self))]
2139    fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
2140        empty_proc_macro!(self);
2141        let tcx = self.tcx;
2142
2143        let all_impls: Vec<_> = tcx
2144            .crate_inherent_impls(())
2145            .0
2146            .incoherent_impls
2147            .iter()
2148            .map(|(&simp, impls)| IncoherentImpls {
2149                self_ty: simp,
2150                impls: self.lazy_array(impls.iter().map(|def_id| def_id.local_def_index)),
2151            })
2152            .collect();
2153
2154        self.lazy_array(&all_impls)
2155    }
2156
2157    fn encode_exportable_items(&mut self) -> LazyArray<DefIndex> {
2158        empty_proc_macro!(self);
2159        self.lazy_array(self.tcx.exportable_items(LOCAL_CRATE).iter().map(|def_id| def_id.index))
2160    }
2161
2162    fn encode_stable_order_of_exportable_impls(&mut self) -> LazyArray<(DefIndex, usize)> {
2163        empty_proc_macro!(self);
2164        let stable_order_of_exportable_impls =
2165            self.tcx.stable_order_of_exportable_impls(LOCAL_CRATE);
2166        self.lazy_array(
2167            stable_order_of_exportable_impls.iter().map(|(def_id, idx)| (def_id.index, *idx)),
2168        )
2169    }
2170
2171    // Encodes all symbols exported from this crate into the metadata.
2172    //
2173    // This pass is seeded off the reachability list calculated in the
2174    // middle::reachable module but filters out items that either don't have a
2175    // symbol associated with them (they weren't translated) or if they're an FFI
2176    // definition (as that's not defined in this crate).
2177    fn encode_exported_symbols(
2178        &mut self,
2179        exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
2180    ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
2181        empty_proc_macro!(self);
2182        // The metadata symbol name is special. It should not show up in
2183        // downstream crates.
2184        let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
2185
2186        self.lazy_array(
2187            exported_symbols
2188                .iter()
2189                .filter(|&(exported_symbol, _)| match *exported_symbol {
2190                    ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
2191                    _ => true,
2192                })
2193                .cloned(),
2194        )
2195    }
2196
2197    fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
2198        empty_proc_macro!(self);
2199        let formats = self.tcx.dependency_formats(());
2200        if let Some(arr) = formats.get(&CrateType::Dylib) {
2201            return self.lazy_array(arr.iter().skip(1 /* skip LOCAL_CRATE */).map(
2202                |slot| match *slot {
2203                    Linkage::NotLinked | Linkage::IncludedFromDylib => None,
2204
2205                    Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
2206                    Linkage::Static => Some(LinkagePreference::RequireStatic),
2207                },
2208            ));
2209        }
2210        LazyArray::default()
2211    }
2212}
2213
2214/// Used to prefetch queries which will be needed later by metadata encoding.
2215/// Only a subset of the queries are actually prefetched to keep this code smaller.
2216fn prefetch_mir(tcx: TyCtxt<'_>) {
2217    if !tcx.sess.opts.output_types.should_codegen() {
2218        // We won't emit MIR, so don't prefetch it.
2219        return;
2220    }
2221
2222    let reachable_set = tcx.reachable_set(());
2223    par_for_each_in(tcx.mir_keys(()), |&&def_id| {
2224        let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
2225
2226        if encode_const {
2227            tcx.ensure_done().mir_for_ctfe(def_id);
2228        }
2229        if encode_opt {
2230            tcx.ensure_done().optimized_mir(def_id);
2231        }
2232        if encode_opt || encode_const {
2233            tcx.ensure_done().promoted_mir(def_id);
2234        }
2235    })
2236}
2237
2238// NOTE(eddyb) The following comment was preserved for posterity, even
2239// though it's no longer relevant as EBML (which uses nested & tagged
2240// "documents") was replaced with a scheme that can't go out of bounds.
2241//
2242// And here we run into yet another obscure archive bug: in which metadata
2243// loaded from archives may have trailing garbage bytes. Awhile back one of
2244// our tests was failing sporadically on the macOS 64-bit builders (both nopt
2245// and opt) by having ebml generate an out-of-bounds panic when looking at
2246// metadata.
2247//
2248// Upon investigation it turned out that the metadata file inside of an rlib
2249// (and ar archive) was being corrupted. Some compilations would generate a
2250// metadata file which would end in a few extra bytes, while other
2251// compilations would not have these extra bytes appended to the end. These
2252// extra bytes were interpreted by ebml as an extra tag, so they ended up
2253// being interpreted causing the out-of-bounds.
2254//
2255// The root cause of why these extra bytes were appearing was never
2256// discovered, and in the meantime the solution we're employing is to insert
2257// the length of the metadata to the start of the metadata. Later on this
2258// will allow us to slice the metadata to the precise length that we just
2259// generated regardless of trailing bytes that end up in it.
2260
2261pub struct EncodedMetadata {
2262    // The declaration order matters because `full_metadata` should be dropped
2263    // before `_temp_dir`.
2264    full_metadata: Option<Mmap>,
2265    // This is an optional stub metadata containing only the crate header.
2266    // The header should be very small, so we load it directly into memory.
2267    stub_metadata: Option<Vec<u8>>,
2268    // We need to carry MaybeTempDir to avoid deleting the temporary
2269    // directory while accessing the Mmap.
2270    _temp_dir: Option<MaybeTempDir>,
2271}
2272
2273impl EncodedMetadata {
2274    #[inline]
2275    pub fn from_path(
2276        path: PathBuf,
2277        stub_path: Option<PathBuf>,
2278        temp_dir: Option<MaybeTempDir>,
2279    ) -> std::io::Result<Self> {
2280        let file = std::fs::File::open(&path)?;
2281        let file_metadata = file.metadata()?;
2282        if file_metadata.len() == 0 {
2283            return Ok(Self { full_metadata: None, stub_metadata: None, _temp_dir: None });
2284        }
2285        let full_mmap = unsafe { Some(Mmap::map(file)?) };
2286
2287        let stub =
2288            if let Some(stub_path) = stub_path { Some(std::fs::read(stub_path)?) } else { None };
2289
2290        Ok(Self { full_metadata: full_mmap, stub_metadata: stub, _temp_dir: temp_dir })
2291    }
2292
2293    #[inline]
2294    pub fn full(&self) -> &[u8] {
2295        &self.full_metadata.as_deref().unwrap_or_default()
2296    }
2297
2298    #[inline]
2299    pub fn stub_or_full(&self) -> &[u8] {
2300        self.stub_metadata.as_deref().unwrap_or(self.full())
2301    }
2302}
2303
2304impl<S: Encoder> Encodable<S> for EncodedMetadata {
2305    fn encode(&self, s: &mut S) {
2306        self.stub_metadata.encode(s);
2307
2308        let slice = self.full();
2309        slice.encode(s)
2310    }
2311}
2312
2313impl<D: Decoder> Decodable<D> for EncodedMetadata {
2314    fn decode(d: &mut D) -> Self {
2315        let stub = <Option<Vec<u8>>>::decode(d);
2316
2317        let len = d.read_usize();
2318        let full_metadata = if len > 0 {
2319            let mut mmap = MmapMut::map_anon(len).unwrap();
2320            mmap.copy_from_slice(d.read_raw_bytes(len));
2321            Some(mmap.make_read_only().unwrap())
2322        } else {
2323            None
2324        };
2325
2326        Self { full_metadata, stub_metadata: stub, _temp_dir: None }
2327    }
2328}
2329
2330pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path, ref_path: Option<&Path>) {
2331    let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2332
2333    // Since encoding metadata is not in a query, and nothing is cached,
2334    // there's no need to do dep-graph tracking for any of it.
2335    tcx.dep_graph.assert_ignored();
2336
2337    if tcx.sess.threads() != 1 {
2338        // Prefetch some queries used by metadata encoding.
2339        // This is not necessary for correctness, but is only done for performance reasons.
2340        // It can be removed if it turns out to cause trouble or be detrimental to performance.
2341        join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2342    }
2343
2344    with_encode_metadata_header(tcx, path, |ecx| {
2345        // Encode all the entries and extra information in the crate,
2346        // culminating in the `CrateRoot` which points to all of it.
2347        let root = ecx.encode_crate_root();
2348
2349        // Flush buffer to ensure backing file has the correct size.
2350        ecx.opaque.flush();
2351        // Record metadata size for self-profiling
2352        tcx.prof.artifact_size(
2353            "crate_metadata",
2354            "crate_metadata",
2355            ecx.opaque.file().metadata().unwrap().len(),
2356        );
2357
2358        root.position.get()
2359    });
2360
2361    if let Some(ref_path) = ref_path {
2362        with_encode_metadata_header(tcx, ref_path, |ecx| {
2363            let header: LazyValue<CrateHeader> = ecx.lazy(CrateHeader {
2364                name: tcx.crate_name(LOCAL_CRATE),
2365                triple: tcx.sess.opts.target_triple.clone(),
2366                hash: tcx.crate_hash(LOCAL_CRATE),
2367                is_proc_macro_crate: false,
2368                is_stub: true,
2369            });
2370            header.position.get()
2371        });
2372    }
2373}
2374
2375fn with_encode_metadata_header(
2376    tcx: TyCtxt<'_>,
2377    path: &Path,
2378    f: impl FnOnce(&mut EncodeContext<'_, '_>) -> usize,
2379) {
2380    let mut encoder = opaque::FileEncoder::new(path)
2381        .unwrap_or_else(|err| tcx.dcx().emit_fatal(FailCreateFileEncoder { err }));
2382    encoder.emit_raw_bytes(METADATA_HEADER);
2383
2384    // Will be filled with the root position after encoding everything.
2385    encoder.emit_raw_bytes(&0u64.to_le_bytes());
2386
2387    let source_map_files = tcx.sess.source_map().files();
2388    let source_file_cache = (Arc::clone(&source_map_files[0]), 0);
2389    let required_source_files = Some(FxIndexSet::default());
2390    drop(source_map_files);
2391
2392    let hygiene_ctxt = HygieneEncodeContext::default();
2393
2394    let mut ecx = EncodeContext {
2395        opaque: encoder,
2396        tcx,
2397        feat: tcx.features(),
2398        tables: Default::default(),
2399        lazy_state: LazyState::NoNode,
2400        span_shorthands: Default::default(),
2401        type_shorthands: Default::default(),
2402        predicate_shorthands: Default::default(),
2403        source_file_cache,
2404        interpret_allocs: Default::default(),
2405        required_source_files,
2406        is_proc_macro: tcx.crate_types().contains(&CrateType::ProcMacro),
2407        hygiene_ctxt: &hygiene_ctxt,
2408        symbol_table: Default::default(),
2409    };
2410
2411    // Encode the rustc version string in a predictable location.
2412    rustc_version(tcx.sess.cfg_version).encode(&mut ecx);
2413
2414    let root_position = f(&mut ecx);
2415
2416    // Make sure we report any errors from writing to the file.
2417    // If we forget this, compilation can succeed with an incomplete rmeta file,
2418    // causing an ICE when the rmeta file is read by another compilation.
2419    if let Err((path, err)) = ecx.opaque.finish() {
2420        tcx.dcx().emit_fatal(FailWriteFile { path: &path, err });
2421    }
2422
2423    let file = ecx.opaque.file();
2424    if let Err(err) = encode_root_position(file, root_position) {
2425        tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2426    }
2427}
2428
2429fn encode_root_position(mut file: &File, pos: usize) -> Result<(), std::io::Error> {
2430    // We will return to this position after writing the root position.
2431    let pos_before_seek = file.stream_position().unwrap();
2432
2433    // Encode the root position.
2434    let header = METADATA_HEADER.len();
2435    file.seek(std::io::SeekFrom::Start(header as u64))?;
2436    file.write_all(&pos.to_le_bytes())?;
2437
2438    // Return to the position where we are before writing the root position.
2439    file.seek(std::io::SeekFrom::Start(pos_before_seek))?;
2440    Ok(())
2441}
2442
2443pub(crate) fn provide(providers: &mut Providers) {
2444    *providers = Providers {
2445        doc_link_resolutions: |tcx, def_id| {
2446            tcx.resolutions(())
2447                .doc_link_resolutions
2448                .get(&def_id)
2449                .unwrap_or_else(|| span_bug!(tcx.def_span(def_id), "no resolutions for a doc link"))
2450        },
2451        doc_link_traits_in_scope: |tcx, def_id| {
2452            tcx.resolutions(()).doc_link_traits_in_scope.get(&def_id).unwrap_or_else(|| {
2453                span_bug!(tcx.def_span(def_id), "no traits in scope for a doc link")
2454            })
2455        },
2456
2457        ..*providers
2458    }
2459}
2460
2461/// Build a textual representation of an unevaluated constant expression.
2462///
2463/// If the const expression is too complex, an underscore `_` is returned.
2464/// For const arguments, it's `{ _ }` to be precise.
2465/// This means that the output is not necessarily valid Rust code.
2466///
2467/// Currently, only
2468///
2469/// * literals (optionally with a leading `-`)
2470/// * unit `()`
2471/// * blocks (`{ … }`) around simple expressions and
2472/// * paths without arguments
2473///
2474/// are considered simple enough. Simple blocks are included since they are
2475/// necessary to disambiguate unit from the unit type.
2476/// This list might get extended in the future.
2477///
2478/// Without this censoring, in a lot of cases the output would get too large
2479/// and verbose. Consider `match` expressions, blocks and deeply nested ADTs.
2480/// Further, private and `doc(hidden)` fields of structs would get leaked
2481/// since HIR datatypes like the `body` parameter do not contain enough
2482/// semantic information for this function to be able to hide them –
2483/// at least not without significant performance overhead.
2484///
2485/// Whenever possible, prefer to evaluate the constant first and try to
2486/// use a different method for pretty-printing. Ideally this function
2487/// should only ever be used as a fallback.
2488pub fn rendered_const<'tcx>(tcx: TyCtxt<'tcx>, body: &hir::Body<'_>, def_id: LocalDefId) -> String {
2489    let value = body.value;
2490
2491    #[derive(PartialEq, Eq)]
2492    enum Classification {
2493        Literal,
2494        Simple,
2495        Complex,
2496    }
2497
2498    use Classification::*;
2499
2500    fn classify(expr: &hir::Expr<'_>) -> Classification {
2501        match &expr.kind {
2502            hir::ExprKind::Unary(hir::UnOp::Neg, expr) => {
2503                if matches!(expr.kind, hir::ExprKind::Lit(_)) { Literal } else { Complex }
2504            }
2505            hir::ExprKind::Lit(_) => Literal,
2506            hir::ExprKind::Tup([]) => Simple,
2507            hir::ExprKind::Block(hir::Block { stmts: [], expr: Some(expr), .. }, _) => {
2508                if classify(expr) == Complex { Complex } else { Simple }
2509            }
2510            // Paths with a self-type or arguments are too “complex” following our measure since
2511            // they may leak private fields of structs (with feature `adt_const_params`).
2512            // Consider: `<Self as Trait<{ Struct { private: () } }>>::CONSTANT`.
2513            // Paths without arguments are definitely harmless though.
2514            hir::ExprKind::Path(hir::QPath::Resolved(_, hir::Path { segments, .. })) => {
2515                if segments.iter().all(|segment| segment.args.is_none()) { Simple } else { Complex }
2516            }
2517            // FIXME: Claiming that those kinds of QPaths are simple is probably not true if the Ty
2518            //        contains const arguments. Is there a *concise* way to check for this?
2519            hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => Simple,
2520            // FIXME: Can they contain const arguments and thus leak private struct fields?
2521            hir::ExprKind::Path(hir::QPath::LangItem(..)) => Simple,
2522            _ => Complex,
2523        }
2524    }
2525
2526    match classify(value) {
2527        // For non-macro literals, we avoid invoking the pretty-printer and use the source snippet
2528        // instead to preserve certain stylistic choices the user likely made for the sake of
2529        // legibility, like:
2530        //
2531        // * hexadecimal notation
2532        // * underscores
2533        // * character escapes
2534        //
2535        // FIXME: This passes through `-/*spacer*/0` verbatim.
2536        Literal
2537            if !value.span.from_expansion()
2538                && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(value.span) =>
2539        {
2540            snippet
2541        }
2542
2543        // Otherwise we prefer pretty-printing to get rid of extraneous whitespace, comments and
2544        // other formatting artifacts.
2545        Literal | Simple => id_to_string(&tcx, body.id().hir_id),
2546
2547        // FIXME: Omit the curly braces if the enclosing expression is an array literal
2548        //        with a repeated element (an `ExprKind::Repeat`) as in such case it
2549        //        would not actually need any disambiguation.
2550        Complex => {
2551            if tcx.def_kind(def_id) == DefKind::AnonConst {
2552                "{ _ }".to_owned()
2553            } else {
2554                "_".to_owned()
2555            }
2556        }
2557    }
2558}