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 preinterned, emit tag and symbol index
205        if symbol.is_preinterned() {
206            self.opaque.emit_u8(SYMBOL_PREINTERNED);
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                    // FIXME: This should probably to conditionally remapped under
555                    // a RemapPathScopeComponents but which one?
556                    let adapted_file_name = source_map
557                        .path_mapping()
558                        .to_embeddable_absolute_path(original_file_name.clone(), working_directory);
559
560                    adapted_source_file.name = FileName::Real(adapted_file_name);
561                }
562                _ => {
563                    // expanded code, not from a file
564                }
565            };
566
567            // We're serializing this `SourceFile` into our crate metadata,
568            // so mark it as coming from this crate.
569            // This also ensures that we don't try to deserialize the
570            // `CrateNum` for a proc-macro dependency - since proc macro
571            // dependencies aren't loaded when we deserialize a proc-macro,
572            // trying to remap the `CrateNum` would fail.
573            if self.is_proc_macro {
574                adapted_source_file.cnum = LOCAL_CRATE;
575            }
576
577            // Update the `StableSourceFileId` to make sure it incorporates the
578            // id of the current crate. This way it will be unique within the
579            // crate graph during downstream compilation sessions.
580            adapted_source_file.stable_id = StableSourceFileId::from_filename_for_export(
581                &adapted_source_file.name,
582                local_crate_stable_id,
583            );
584
585            let on_disk_index: u32 =
586                on_disk_index.try_into().expect("cannot export more than U32_MAX files");
587            adapted.set_some(on_disk_index, self.lazy(adapted_source_file));
588        }
589
590        adapted.encode(&mut self.opaque)
591    }
592
593    fn encode_crate_root(&mut self) -> LazyValue<CrateRoot> {
594        let tcx = self.tcx;
595        let mut stats: Vec<(&'static str, usize)> = Vec::with_capacity(32);
596
597        macro_rules! stat {
598            ($label:literal, $f:expr) => {{
599                let orig_pos = self.position();
600                let res = $f();
601                stats.push(($label, self.position() - orig_pos));
602                res
603            }};
604        }
605
606        // We have already encoded some things. Get their combined size from the current position.
607        stats.push(("preamble", self.position()));
608
609        let (crate_deps, dylib_dependency_formats) =
610            stat!("dep", || (self.encode_crate_deps(), self.encode_dylib_dependency_formats()));
611
612        let lib_features = stat!("lib-features", || self.encode_lib_features());
613
614        let stability_implications =
615            stat!("stability-implications", || self.encode_stability_implications());
616
617        let (lang_items, lang_items_missing) = stat!("lang-items", || {
618            (self.encode_lang_items(), self.encode_lang_items_missing())
619        });
620
621        let stripped_cfg_items = stat!("stripped-cfg-items", || self.encode_stripped_cfg_items());
622
623        let diagnostic_items = stat!("diagnostic-items", || self.encode_diagnostic_items());
624
625        let native_libraries = stat!("native-libs", || self.encode_native_libraries());
626
627        let foreign_modules = stat!("foreign-modules", || self.encode_foreign_modules());
628
629        _ = stat!("def-path-table", || self.encode_def_path_table());
630
631        // Encode the def IDs of traits, for rustdoc and diagnostics.
632        let traits = stat!("traits", || self.encode_traits());
633
634        // Encode the def IDs of impls, for coherence checking.
635        let impls = stat!("impls", || self.encode_impls());
636
637        let incoherent_impls = stat!("incoherent-impls", || self.encode_incoherent_impls());
638
639        _ = stat!("mir", || self.encode_mir());
640
641        _ = stat!("def-ids", || self.encode_def_ids());
642
643        let interpret_alloc_index = stat!("interpret-alloc-index", || {
644            let mut interpret_alloc_index = Vec::new();
645            let mut n = 0;
646            trace!("beginning to encode alloc ids");
647            loop {
648                let new_n = self.interpret_allocs.len();
649                // if we have found new ids, serialize those, too
650                if n == new_n {
651                    // otherwise, abort
652                    break;
653                }
654                trace!("encoding {} further alloc ids", new_n - n);
655                for idx in n..new_n {
656                    let id = self.interpret_allocs[idx];
657                    let pos = self.position() as u64;
658                    interpret_alloc_index.push(pos);
659                    interpret::specialized_encode_alloc_id(self, tcx, id);
660                }
661                n = new_n;
662            }
663            self.lazy_array(interpret_alloc_index)
664        });
665
666        // Encode the proc macro data. This affects `tables`, so we need to do this before we
667        // encode the tables. This overwrites def_keys, so it must happen after
668        // encode_def_path_table.
669        let proc_macro_data = stat!("proc-macro-data", || self.encode_proc_macros());
670
671        let tables = stat!("tables", || self.tables.encode(&mut self.opaque));
672
673        let debugger_visualizers =
674            stat!("debugger-visualizers", || self.encode_debugger_visualizers());
675
676        // Encode exported symbols info. This is prefetched in `encode_metadata`.
677        let exported_symbols = stat!("exported-symbols", || {
678            self.encode_exported_symbols(tcx.exported_symbols(LOCAL_CRATE))
679        });
680
681        // Encode the hygiene data.
682        // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The
683        // process of encoding other items (e.g. `optimized_mir`) may cause us to load data from
684        // the incremental cache. If this causes us to deserialize a `Span`, then we may load
685        // additional `SyntaxContext`s into the global `HygieneData`. Therefore, we need to encode
686        // the hygiene data last to ensure that we encode any `SyntaxContext`s that might be used.
687        let (syntax_contexts, expn_data, expn_hashes) = stat!("hygiene", || self.encode_hygiene());
688
689        let def_path_hash_map = stat!("def-path-hash-map", || self.encode_def_path_hash_map());
690
691        // Encode source_map. This needs to be done last, because encoding `Span`s tells us which
692        // `SourceFiles` we actually need to encode.
693        let source_map = stat!("source-map", || self.encode_source_map());
694        let target_modifiers = stat!("target-modifiers", || self.encode_target_modifiers());
695
696        let root = stat!("final", || {
697            let attrs = tcx.hir_krate_attrs();
698            self.lazy(CrateRoot {
699                header: CrateHeader {
700                    name: tcx.crate_name(LOCAL_CRATE),
701                    triple: tcx.sess.opts.target_triple.clone(),
702                    hash: tcx.crate_hash(LOCAL_CRATE),
703                    is_proc_macro_crate: proc_macro_data.is_some(),
704                },
705                extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
706                stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(),
707                required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
708                panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
709                edition: tcx.sess.edition(),
710                has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
711                has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
712                has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
713                has_default_lib_allocator: ast::attr::contains_name(
714                    attrs,
715                    sym::default_lib_allocator,
716                ),
717                proc_macro_data,
718                debugger_visualizers,
719                compiler_builtins: ast::attr::contains_name(attrs, sym::compiler_builtins),
720                needs_allocator: ast::attr::contains_name(attrs, sym::needs_allocator),
721                needs_panic_runtime: ast::attr::contains_name(attrs, sym::needs_panic_runtime),
722                no_builtins: ast::attr::contains_name(attrs, sym::no_builtins),
723                panic_runtime: ast::attr::contains_name(attrs, sym::panic_runtime),
724                profiler_runtime: ast::attr::contains_name(attrs, sym::profiler_runtime),
725                symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
726
727                crate_deps,
728                dylib_dependency_formats,
729                lib_features,
730                stability_implications,
731                lang_items,
732                diagnostic_items,
733                lang_items_missing,
734                stripped_cfg_items,
735                native_libraries,
736                foreign_modules,
737                source_map,
738                target_modifiers,
739                traits,
740                impls,
741                incoherent_impls,
742                exported_symbols,
743                interpret_alloc_index,
744                tables,
745                syntax_contexts,
746                expn_data,
747                expn_hashes,
748                def_path_hash_map,
749                specialization_enabled_in: tcx.specialization_enabled_in(LOCAL_CRATE),
750            })
751        });
752
753        let total_bytes = self.position();
754
755        let computed_total_bytes: usize = stats.iter().map(|(_, size)| size).sum();
756        assert_eq!(total_bytes, computed_total_bytes);
757
758        if tcx.sess.opts.unstable_opts.meta_stats {
759            self.opaque.flush();
760
761            // Rewind and re-read all the metadata to count the zero bytes we wrote.
762            let pos_before_rewind = self.opaque.file().stream_position().unwrap();
763            let mut zero_bytes = 0;
764            self.opaque.file().rewind().unwrap();
765            let file = std::io::BufReader::new(self.opaque.file());
766            for e in file.bytes() {
767                if e.unwrap() == 0 {
768                    zero_bytes += 1;
769                }
770            }
771            assert_eq!(self.opaque.file().stream_position().unwrap(), pos_before_rewind);
772
773            stats.sort_by_key(|&(_, usize)| usize);
774
775            let prefix = "meta-stats";
776            let perc = |bytes| (bytes * 100) as f64 / total_bytes as f64;
777
778            eprintln!("{prefix} METADATA STATS");
779            eprintln!("{} {:<23}{:>10}", prefix, "Section", "Size");
780            eprintln!("{prefix} ----------------------------------------------------------------");
781            for (label, size) in stats {
782                eprintln!(
783                    "{} {:<23}{:>10} ({:4.1}%)",
784                    prefix,
785                    label,
786                    format_with_underscores(size),
787                    perc(size)
788                );
789            }
790            eprintln!("{prefix} ----------------------------------------------------------------");
791            eprintln!(
792                "{} {:<23}{:>10} (of which {:.1}% are zero bytes)",
793                prefix,
794                "Total",
795                format_with_underscores(total_bytes),
796                perc(zero_bytes)
797            );
798            eprintln!("{prefix}");
799        }
800
801        root
802    }
803}
804
805struct AnalyzeAttrState<'a> {
806    is_exported: bool,
807    is_doc_hidden: bool,
808    features: &'a Features,
809}
810
811/// Returns whether an attribute needs to be recorded in metadata, that is, if it's usable and
812/// useful in downstream crates. Local-only attributes are an obvious example, but some
813/// rustdoc-specific attributes can equally be of use while documenting the current crate only.
814///
815/// Removing these superfluous attributes speeds up compilation by making the metadata smaller.
816///
817/// Note: the `is_exported` parameter is used to cache whether the given `DefId` has a public
818/// visibility: this is a piece of data that can be computed once per defid, and not once per
819/// attribute. Some attributes would only be usable downstream if they are public.
820#[inline]
821fn analyze_attr(attr: &impl AttributeExt, state: &mut AnalyzeAttrState<'_>) -> bool {
822    let mut should_encode = false;
823    if !rustc_feature::encode_cross_crate(attr.name_or_empty()) {
824        // Attributes not marked encode-cross-crate don't need to be encoded for downstream crates.
825    } else if attr.doc_str().is_some() {
826        // We keep all doc comments reachable to rustdoc because they might be "imported" into
827        // downstream crates if they use `#[doc(inline)]` to copy an item's documentation into
828        // their own.
829        if state.is_exported {
830            should_encode = true;
831        }
832    } else if attr.has_name(sym::doc) {
833        // If this is a `doc` attribute that doesn't have anything except maybe `inline` (as in
834        // `#[doc(inline)]`), then we can remove it. It won't be inlinable in downstream crates.
835        if let Some(item_list) = attr.meta_item_list() {
836            for item in item_list {
837                if !item.has_name(sym::inline) {
838                    should_encode = true;
839                    if item.has_name(sym::hidden) {
840                        state.is_doc_hidden = true;
841                        break;
842                    }
843                }
844            }
845        }
846    } else if attr.path().starts_with(&[sym::diagnostic]) && attr.path().len() == 2 {
847        should_encode =
848            rustc_feature::is_stable_diagnostic_attribute(attr.path()[1], state.features);
849    } else {
850        should_encode = true;
851    }
852    should_encode
853}
854
855fn should_encode_span(def_kind: DefKind) -> bool {
856    match def_kind {
857        DefKind::Mod
858        | DefKind::Struct
859        | DefKind::Union
860        | DefKind::Enum
861        | DefKind::Variant
862        | DefKind::Trait
863        | DefKind::TyAlias
864        | DefKind::ForeignTy
865        | DefKind::TraitAlias
866        | DefKind::AssocTy
867        | DefKind::TyParam
868        | DefKind::ConstParam
869        | DefKind::LifetimeParam
870        | DefKind::Fn
871        | DefKind::Const
872        | DefKind::Static { .. }
873        | DefKind::Ctor(..)
874        | DefKind::AssocFn
875        | DefKind::AssocConst
876        | DefKind::Macro(_)
877        | DefKind::ExternCrate
878        | DefKind::Use
879        | DefKind::AnonConst
880        | DefKind::InlineConst
881        | DefKind::OpaqueTy
882        | DefKind::Field
883        | DefKind::Impl { .. }
884        | DefKind::Closure
885        | DefKind::SyntheticCoroutineBody => true,
886        DefKind::ForeignMod | DefKind::GlobalAsm => false,
887    }
888}
889
890fn should_encode_attrs(def_kind: DefKind) -> bool {
891    match def_kind {
892        DefKind::Mod
893        | DefKind::Struct
894        | DefKind::Union
895        | DefKind::Enum
896        | DefKind::Variant
897        | DefKind::Trait
898        | DefKind::TyAlias
899        | DefKind::ForeignTy
900        | DefKind::TraitAlias
901        | DefKind::AssocTy
902        | DefKind::Fn
903        | DefKind::Const
904        | DefKind::Static { nested: false, .. }
905        | DefKind::AssocFn
906        | DefKind::AssocConst
907        | DefKind::Macro(_)
908        | DefKind::Field
909        | DefKind::Impl { .. } => true,
910        // Tools may want to be able to detect their tool lints on
911        // closures from upstream crates, too. This is used by
912        // https://github.com/model-checking/kani and is not a performance
913        // or maintenance issue for us.
914        DefKind::Closure => true,
915        DefKind::SyntheticCoroutineBody => false,
916        DefKind::TyParam
917        | DefKind::ConstParam
918        | DefKind::Ctor(..)
919        | DefKind::ExternCrate
920        | DefKind::Use
921        | DefKind::ForeignMod
922        | DefKind::AnonConst
923        | DefKind::InlineConst
924        | DefKind::OpaqueTy
925        | DefKind::LifetimeParam
926        | DefKind::Static { nested: true, .. }
927        | DefKind::GlobalAsm => false,
928    }
929}
930
931fn should_encode_expn_that_defined(def_kind: DefKind) -> bool {
932    match def_kind {
933        DefKind::Mod
934        | DefKind::Struct
935        | DefKind::Union
936        | DefKind::Enum
937        | DefKind::Variant
938        | DefKind::Trait
939        | DefKind::Impl { .. } => true,
940        DefKind::TyAlias
941        | DefKind::ForeignTy
942        | DefKind::TraitAlias
943        | DefKind::AssocTy
944        | DefKind::TyParam
945        | DefKind::Fn
946        | DefKind::Const
947        | DefKind::ConstParam
948        | DefKind::Static { .. }
949        | DefKind::Ctor(..)
950        | DefKind::AssocFn
951        | DefKind::AssocConst
952        | DefKind::Macro(_)
953        | DefKind::ExternCrate
954        | DefKind::Use
955        | DefKind::ForeignMod
956        | DefKind::AnonConst
957        | DefKind::InlineConst
958        | DefKind::OpaqueTy
959        | DefKind::Field
960        | DefKind::LifetimeParam
961        | DefKind::GlobalAsm
962        | DefKind::Closure
963        | DefKind::SyntheticCoroutineBody => false,
964    }
965}
966
967fn should_encode_visibility(def_kind: DefKind) -> bool {
968    match def_kind {
969        DefKind::Mod
970        | DefKind::Struct
971        | DefKind::Union
972        | DefKind::Enum
973        | DefKind::Variant
974        | DefKind::Trait
975        | DefKind::TyAlias
976        | DefKind::ForeignTy
977        | DefKind::TraitAlias
978        | DefKind::AssocTy
979        | DefKind::Fn
980        | DefKind::Const
981        | DefKind::Static { nested: false, .. }
982        | DefKind::Ctor(..)
983        | DefKind::AssocFn
984        | DefKind::AssocConst
985        | DefKind::Macro(..)
986        | DefKind::Field => true,
987        DefKind::Use
988        | DefKind::ForeignMod
989        | DefKind::TyParam
990        | DefKind::ConstParam
991        | DefKind::LifetimeParam
992        | DefKind::AnonConst
993        | DefKind::InlineConst
994        | DefKind::Static { nested: true, .. }
995        | DefKind::OpaqueTy
996        | DefKind::GlobalAsm
997        | DefKind::Impl { .. }
998        | DefKind::Closure
999        | DefKind::ExternCrate
1000        | DefKind::SyntheticCoroutineBody => false,
1001    }
1002}
1003
1004fn should_encode_stability(def_kind: DefKind) -> bool {
1005    match def_kind {
1006        DefKind::Mod
1007        | DefKind::Ctor(..)
1008        | DefKind::Variant
1009        | DefKind::Field
1010        | DefKind::Struct
1011        | DefKind::AssocTy
1012        | DefKind::AssocFn
1013        | DefKind::AssocConst
1014        | DefKind::TyParam
1015        | DefKind::ConstParam
1016        | DefKind::Static { .. }
1017        | DefKind::Const
1018        | DefKind::Fn
1019        | DefKind::ForeignMod
1020        | DefKind::TyAlias
1021        | DefKind::OpaqueTy
1022        | DefKind::Enum
1023        | DefKind::Union
1024        | DefKind::Impl { .. }
1025        | DefKind::Trait
1026        | DefKind::TraitAlias
1027        | DefKind::Macro(..)
1028        | DefKind::ForeignTy => true,
1029        DefKind::Use
1030        | DefKind::LifetimeParam
1031        | DefKind::AnonConst
1032        | DefKind::InlineConst
1033        | DefKind::GlobalAsm
1034        | DefKind::Closure
1035        | DefKind::ExternCrate
1036        | DefKind::SyntheticCoroutineBody => false,
1037    }
1038}
1039
1040/// Whether we should encode MIR. Return a pair, resp. for CTFE and for LLVM.
1041///
1042/// Computing, optimizing and encoding the MIR is a relatively expensive operation.
1043/// We want to avoid this work when not required. Therefore:
1044/// - we only compute `mir_for_ctfe` on items with const-eval semantics;
1045/// - we skip `optimized_mir` for check runs.
1046/// - we only encode `optimized_mir` that could be generated in other crates, that is, a code that
1047///   is either generic or has inline hint, and is reachable from the other crates (contained
1048///   in reachable set).
1049///
1050/// Note: Reachable set describes definitions that might be generated or referenced from other
1051/// crates and it can be used to limit optimized MIR that needs to be encoded. On the other hand,
1052/// the reachable set doesn't have much to say about which definitions might be evaluated at compile
1053/// time in other crates, so it cannot be used to omit CTFE MIR. For example, `f` below is
1054/// unreachable and yet it can be evaluated in other crates:
1055///
1056/// ```
1057/// const fn f() -> usize { 0 }
1058/// pub struct S { pub a: [usize; f()] }
1059/// ```
1060fn should_encode_mir(
1061    tcx: TyCtxt<'_>,
1062    reachable_set: &LocalDefIdSet,
1063    def_id: LocalDefId,
1064) -> (bool, bool) {
1065    match tcx.def_kind(def_id) {
1066        // Constructors
1067        DefKind::Ctor(_, _) => {
1068            let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
1069                || tcx.sess.opts.unstable_opts.always_encode_mir;
1070            (true, mir_opt_base)
1071        }
1072        // Constants
1073        DefKind::AnonConst | DefKind::InlineConst | DefKind::AssocConst | DefKind::Const => {
1074            (true, false)
1075        }
1076        // Coroutines require optimized MIR to compute layout.
1077        DefKind::Closure if tcx.is_coroutine(def_id.to_def_id()) => (false, true),
1078        DefKind::SyntheticCoroutineBody => (false, true),
1079        // Full-fledged functions + closures
1080        DefKind::AssocFn | DefKind::Fn | DefKind::Closure => {
1081            let generics = tcx.generics_of(def_id);
1082            let opt = tcx.sess.opts.unstable_opts.always_encode_mir
1083                || (tcx.sess.opts.output_types.should_codegen()
1084                    && reachable_set.contains(&def_id)
1085                    && (generics.requires_monomorphization(tcx)
1086                        || tcx.cross_crate_inlinable(def_id)));
1087            // The function has a `const` modifier or is in a `#[const_trait]`.
1088            let is_const_fn = tcx.is_const_fn(def_id.to_def_id())
1089                || tcx.is_const_default_method(def_id.to_def_id());
1090            (is_const_fn, opt)
1091        }
1092        // The others don't have MIR.
1093        _ => (false, false),
1094    }
1095}
1096
1097fn should_encode_variances<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: DefKind) -> bool {
1098    match def_kind {
1099        DefKind::Struct
1100        | DefKind::Union
1101        | DefKind::Enum
1102        | DefKind::Variant
1103        | DefKind::OpaqueTy
1104        | DefKind::Fn
1105        | DefKind::Ctor(..)
1106        | DefKind::AssocFn => true,
1107        DefKind::AssocTy => {
1108            // Only encode variances for RPITITs (for traits)
1109            matches!(tcx.opt_rpitit_info(def_id), Some(ty::ImplTraitInTraitData::Trait { .. }))
1110        }
1111        DefKind::Mod
1112        | DefKind::Field
1113        | DefKind::AssocConst
1114        | DefKind::TyParam
1115        | DefKind::ConstParam
1116        | DefKind::Static { .. }
1117        | DefKind::Const
1118        | DefKind::ForeignMod
1119        | DefKind::Impl { .. }
1120        | DefKind::Trait
1121        | DefKind::TraitAlias
1122        | DefKind::Macro(..)
1123        | DefKind::ForeignTy
1124        | DefKind::Use
1125        | DefKind::LifetimeParam
1126        | DefKind::AnonConst
1127        | DefKind::InlineConst
1128        | DefKind::GlobalAsm
1129        | DefKind::Closure
1130        | DefKind::ExternCrate
1131        | DefKind::SyntheticCoroutineBody => false,
1132        DefKind::TyAlias => tcx.type_alias_is_lazy(def_id),
1133    }
1134}
1135
1136fn should_encode_generics(def_kind: DefKind) -> bool {
1137    match def_kind {
1138        DefKind::Struct
1139        | DefKind::Union
1140        | DefKind::Enum
1141        | DefKind::Variant
1142        | DefKind::Trait
1143        | DefKind::TyAlias
1144        | DefKind::ForeignTy
1145        | DefKind::TraitAlias
1146        | DefKind::AssocTy
1147        | DefKind::Fn
1148        | DefKind::Const
1149        | DefKind::Static { .. }
1150        | DefKind::Ctor(..)
1151        | DefKind::AssocFn
1152        | DefKind::AssocConst
1153        | DefKind::AnonConst
1154        | DefKind::InlineConst
1155        | DefKind::OpaqueTy
1156        | DefKind::Impl { .. }
1157        | DefKind::Field
1158        | DefKind::TyParam
1159        | DefKind::Closure
1160        | DefKind::SyntheticCoroutineBody => true,
1161        DefKind::Mod
1162        | DefKind::ForeignMod
1163        | DefKind::ConstParam
1164        | DefKind::Macro(..)
1165        | DefKind::Use
1166        | DefKind::LifetimeParam
1167        | DefKind::GlobalAsm
1168        | DefKind::ExternCrate => false,
1169    }
1170}
1171
1172fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> bool {
1173    match def_kind {
1174        DefKind::Struct
1175        | DefKind::Union
1176        | DefKind::Enum
1177        | DefKind::Variant
1178        | DefKind::Ctor(..)
1179        | DefKind::Field
1180        | DefKind::Fn
1181        | DefKind::Const
1182        | DefKind::Static { nested: false, .. }
1183        | DefKind::TyAlias
1184        | DefKind::ForeignTy
1185        | DefKind::Impl { .. }
1186        | DefKind::AssocFn
1187        | DefKind::AssocConst
1188        | DefKind::Closure
1189        | DefKind::ConstParam
1190        | DefKind::AnonConst
1191        | DefKind::InlineConst
1192        | DefKind::SyntheticCoroutineBody => true,
1193
1194        DefKind::OpaqueTy => {
1195            let origin = tcx.local_opaque_ty_origin(def_id);
1196            if let hir::OpaqueTyOrigin::FnReturn { parent, .. }
1197            | hir::OpaqueTyOrigin::AsyncFn { parent, .. } = origin
1198                && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(parent)
1199                && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
1200            {
1201                false
1202            } else {
1203                true
1204            }
1205        }
1206
1207        DefKind::AssocTy => {
1208            let assoc_item = tcx.associated_item(def_id);
1209            match assoc_item.container {
1210                ty::AssocItemContainer::Impl => true,
1211                ty::AssocItemContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1212            }
1213        }
1214        DefKind::TyParam => {
1215            let hir::Node::GenericParam(param) = tcx.hir_node_by_def_id(def_id) else { bug!() };
1216            let hir::GenericParamKind::Type { default, .. } = param.kind else { bug!() };
1217            default.is_some()
1218        }
1219
1220        DefKind::Trait
1221        | DefKind::TraitAlias
1222        | DefKind::Mod
1223        | DefKind::ForeignMod
1224        | DefKind::Macro(..)
1225        | DefKind::Static { nested: true, .. }
1226        | DefKind::Use
1227        | DefKind::LifetimeParam
1228        | DefKind::GlobalAsm
1229        | DefKind::ExternCrate => false,
1230    }
1231}
1232
1233fn should_encode_fn_sig(def_kind: DefKind) -> bool {
1234    match def_kind {
1235        DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) => true,
1236
1237        DefKind::Struct
1238        | DefKind::Union
1239        | DefKind::Enum
1240        | DefKind::Variant
1241        | DefKind::Field
1242        | DefKind::Const
1243        | DefKind::Static { .. }
1244        | DefKind::Ctor(..)
1245        | DefKind::TyAlias
1246        | DefKind::OpaqueTy
1247        | DefKind::ForeignTy
1248        | DefKind::Impl { .. }
1249        | DefKind::AssocConst
1250        | DefKind::Closure
1251        | DefKind::ConstParam
1252        | DefKind::AnonConst
1253        | DefKind::InlineConst
1254        | DefKind::AssocTy
1255        | DefKind::TyParam
1256        | DefKind::Trait
1257        | DefKind::TraitAlias
1258        | DefKind::Mod
1259        | DefKind::ForeignMod
1260        | DefKind::Macro(..)
1261        | DefKind::Use
1262        | DefKind::LifetimeParam
1263        | DefKind::GlobalAsm
1264        | DefKind::ExternCrate
1265        | DefKind::SyntheticCoroutineBody => false,
1266    }
1267}
1268
1269fn should_encode_constness(def_kind: DefKind) -> bool {
1270    match def_kind {
1271        DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::Ctor(_, CtorKind::Fn) => true,
1272
1273        DefKind::Struct
1274        | DefKind::Union
1275        | DefKind::Enum
1276        | DefKind::Field
1277        | DefKind::Const
1278        | DefKind::AssocConst
1279        | DefKind::AnonConst
1280        | DefKind::Static { .. }
1281        | DefKind::TyAlias
1282        | DefKind::OpaqueTy
1283        | DefKind::Impl { .. }
1284        | DefKind::ForeignTy
1285        | DefKind::ConstParam
1286        | DefKind::InlineConst
1287        | DefKind::AssocTy
1288        | DefKind::TyParam
1289        | DefKind::Trait
1290        | DefKind::TraitAlias
1291        | DefKind::Mod
1292        | DefKind::ForeignMod
1293        | DefKind::Macro(..)
1294        | DefKind::Use
1295        | DefKind::LifetimeParam
1296        | DefKind::GlobalAsm
1297        | DefKind::ExternCrate
1298        | DefKind::Ctor(_, CtorKind::Const)
1299        | DefKind::Variant
1300        | DefKind::SyntheticCoroutineBody => false,
1301    }
1302}
1303
1304fn should_encode_const(def_kind: DefKind) -> bool {
1305    match def_kind {
1306        DefKind::Const | DefKind::AssocConst | DefKind::AnonConst | DefKind::InlineConst => true,
1307
1308        DefKind::Struct
1309        | DefKind::Union
1310        | DefKind::Enum
1311        | DefKind::Variant
1312        | DefKind::Ctor(..)
1313        | DefKind::Field
1314        | DefKind::Fn
1315        | DefKind::Static { .. }
1316        | DefKind::TyAlias
1317        | DefKind::OpaqueTy
1318        | DefKind::ForeignTy
1319        | DefKind::Impl { .. }
1320        | DefKind::AssocFn
1321        | DefKind::Closure
1322        | DefKind::ConstParam
1323        | DefKind::AssocTy
1324        | DefKind::TyParam
1325        | DefKind::Trait
1326        | DefKind::TraitAlias
1327        | DefKind::Mod
1328        | DefKind::ForeignMod
1329        | DefKind::Macro(..)
1330        | DefKind::Use
1331        | DefKind::LifetimeParam
1332        | DefKind::GlobalAsm
1333        | DefKind::ExternCrate
1334        | DefKind::SyntheticCoroutineBody => false,
1335    }
1336}
1337
1338fn should_encode_fn_impl_trait_in_trait<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
1339    if let Some(assoc_item) = tcx.opt_associated_item(def_id)
1340        && assoc_item.container == ty::AssocItemContainer::Trait
1341        && assoc_item.kind == ty::AssocKind::Fn
1342    {
1343        true
1344    } else {
1345        false
1346    }
1347}
1348
1349impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1350    fn encode_attrs(&mut self, def_id: LocalDefId) {
1351        let tcx = self.tcx;
1352        let mut state = AnalyzeAttrState {
1353            is_exported: tcx.effective_visibilities(()).is_exported(def_id),
1354            is_doc_hidden: false,
1355            features: &tcx.features(),
1356        };
1357        let attr_iter = tcx
1358            .hir_attrs(tcx.local_def_id_to_hir_id(def_id))
1359            .iter()
1360            .filter(|attr| analyze_attr(*attr, &mut state));
1361
1362        record_array!(self.tables.attributes[def_id.to_def_id()] <- attr_iter);
1363
1364        let mut attr_flags = AttrFlags::empty();
1365        if state.is_doc_hidden {
1366            attr_flags |= AttrFlags::IS_DOC_HIDDEN;
1367        }
1368        self.tables.attr_flags.set(def_id.local_def_index, attr_flags);
1369    }
1370
1371    fn encode_def_ids(&mut self) {
1372        self.encode_info_for_mod(CRATE_DEF_ID);
1373
1374        // Proc-macro crates only export proc-macro items, which are looked
1375        // up using `proc_macro_data`
1376        if self.is_proc_macro {
1377            return;
1378        }
1379
1380        let tcx = self.tcx;
1381
1382        for local_id in tcx.iter_local_def_id() {
1383            let def_id = local_id.to_def_id();
1384            let def_kind = tcx.def_kind(local_id);
1385            self.tables.def_kind.set_some(def_id.index, def_kind);
1386
1387            // The `DefCollector` will sometimes create unnecessary `DefId`s
1388            // for trivial const arguments which are directly lowered to
1389            // `ConstArgKind::Path`. We never actually access this `DefId`
1390            // anywhere so we don't need to encode it for other crates.
1391            if def_kind == DefKind::AnonConst
1392                && match tcx.hir_node_by_def_id(local_id) {
1393                    hir::Node::ConstArg(hir::ConstArg { kind, .. }) => match kind {
1394                        // Skip encoding defs for these as they should not have had a `DefId` created
1395                        hir::ConstArgKind::Path(..) | hir::ConstArgKind::Infer(..) => true,
1396                        hir::ConstArgKind::Anon(..) => false,
1397                    },
1398                    _ => false,
1399                }
1400            {
1401                continue;
1402            }
1403
1404            if def_kind == DefKind::Field
1405                && let hir::Node::Field(field) = tcx.hir_node_by_def_id(local_id)
1406                && let Some(anon) = field.default
1407            {
1408                record!(self.tables.default_fields[def_id] <- anon.def_id.to_def_id());
1409            }
1410
1411            if should_encode_span(def_kind) {
1412                let def_span = tcx.def_span(local_id);
1413                record!(self.tables.def_span[def_id] <- def_span);
1414            }
1415            if should_encode_attrs(def_kind) {
1416                self.encode_attrs(local_id);
1417            }
1418            if should_encode_expn_that_defined(def_kind) {
1419                record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
1420            }
1421            if should_encode_span(def_kind)
1422                && let Some(ident_span) = tcx.def_ident_span(def_id)
1423            {
1424                record!(self.tables.def_ident_span[def_id] <- ident_span);
1425            }
1426            if def_kind.has_codegen_attrs() {
1427                record!(self.tables.codegen_fn_attrs[def_id] <- self.tcx.codegen_fn_attrs(def_id));
1428            }
1429            if should_encode_visibility(def_kind) {
1430                let vis =
1431                    self.tcx.local_visibility(local_id).map_id(|def_id| def_id.local_def_index);
1432                record!(self.tables.visibility[def_id] <- vis);
1433            }
1434            if should_encode_stability(def_kind) {
1435                self.encode_stability(def_id);
1436                self.encode_const_stability(def_id);
1437                self.encode_default_body_stability(def_id);
1438                self.encode_deprecation(def_id);
1439            }
1440            if should_encode_variances(tcx, def_id, def_kind) {
1441                let v = self.tcx.variances_of(def_id);
1442                record_array!(self.tables.variances_of[def_id] <- v);
1443            }
1444            if should_encode_fn_sig(def_kind) {
1445                record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1446            }
1447            if should_encode_generics(def_kind) {
1448                let g = tcx.generics_of(def_id);
1449                record!(self.tables.generics_of[def_id] <- g);
1450                record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id));
1451                let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1452                record_defaulted_array!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives);
1453
1454                for param in &g.own_params {
1455                    if let ty::GenericParamDefKind::Const { has_default: true, .. } = param.kind {
1456                        let default = self.tcx.const_param_default(param.def_id);
1457                        record!(self.tables.const_param_default[param.def_id] <- default);
1458                    }
1459                }
1460            }
1461            if tcx.is_conditionally_const(def_id) {
1462                record!(self.tables.const_conditions[def_id] <- self.tcx.const_conditions(def_id));
1463            }
1464            if should_encode_type(tcx, local_id, def_kind) {
1465                record!(self.tables.type_of[def_id] <- self.tcx.type_of(def_id));
1466            }
1467            if should_encode_constness(def_kind) {
1468                self.tables.constness.set_some(def_id.index, self.tcx.constness(def_id));
1469            }
1470            if let DefKind::Fn | DefKind::AssocFn = def_kind {
1471                self.tables.asyncness.set_some(def_id.index, tcx.asyncness(def_id));
1472                record_array!(self.tables.fn_arg_names[def_id] <- tcx.fn_arg_names(def_id));
1473            }
1474            if let Some(name) = tcx.intrinsic(def_id) {
1475                record!(self.tables.intrinsic[def_id] <- name);
1476            }
1477            if let DefKind::TyParam = def_kind {
1478                let default = self.tcx.object_lifetime_default(def_id);
1479                record!(self.tables.object_lifetime_default[def_id] <- default);
1480            }
1481            if let DefKind::Trait = def_kind {
1482                record!(self.tables.trait_def[def_id] <- self.tcx.trait_def(def_id));
1483                record_defaulted_array!(self.tables.explicit_super_predicates_of[def_id] <-
1484                    self.tcx.explicit_super_predicates_of(def_id).skip_binder());
1485                record_defaulted_array!(self.tables.explicit_implied_predicates_of[def_id] <-
1486                    self.tcx.explicit_implied_predicates_of(def_id).skip_binder());
1487                let module_children = self.tcx.module_children_local(local_id);
1488                record_array!(self.tables.module_children_non_reexports[def_id] <-
1489                    module_children.iter().map(|child| child.res.def_id().index));
1490                if self.tcx.is_const_trait(def_id) {
1491                    record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1492                        <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1493                }
1494            }
1495            if let DefKind::TraitAlias = def_kind {
1496                record!(self.tables.trait_def[def_id] <- self.tcx.trait_def(def_id));
1497                record_defaulted_array!(self.tables.explicit_super_predicates_of[def_id] <-
1498                    self.tcx.explicit_super_predicates_of(def_id).skip_binder());
1499                record_defaulted_array!(self.tables.explicit_implied_predicates_of[def_id] <-
1500                    self.tcx.explicit_implied_predicates_of(def_id).skip_binder());
1501            }
1502            if let DefKind::Trait | DefKind::Impl { .. } = def_kind {
1503                let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1504                record_array!(self.tables.associated_item_or_field_def_ids[def_id] <-
1505                    associated_item_def_ids.iter().map(|&def_id| {
1506                        assert!(def_id.is_local());
1507                        def_id.index
1508                    })
1509                );
1510                for &def_id in associated_item_def_ids {
1511                    self.encode_info_for_assoc_item(def_id);
1512                }
1513            }
1514            if let DefKind::Closure | DefKind::SyntheticCoroutineBody = def_kind
1515                && let Some(coroutine_kind) = self.tcx.coroutine_kind(def_id)
1516            {
1517                self.tables.coroutine_kind.set(def_id.index, Some(coroutine_kind))
1518            }
1519            if def_kind == DefKind::Closure
1520                && tcx.type_of(def_id).skip_binder().is_coroutine_closure()
1521            {
1522                let coroutine_for_closure = self.tcx.coroutine_for_closure(def_id);
1523                self.tables
1524                    .coroutine_for_closure
1525                    .set_some(def_id.index, coroutine_for_closure.into());
1526
1527                // If this async closure has a by-move body, record it too.
1528                if tcx.needs_coroutine_by_move_body_def_id(coroutine_for_closure) {
1529                    self.tables.coroutine_by_move_body_def_id.set_some(
1530                        coroutine_for_closure.index,
1531                        self.tcx.coroutine_by_move_body_def_id(coroutine_for_closure).into(),
1532                    );
1533                }
1534            }
1535            if let DefKind::Static { .. } = def_kind {
1536                if !self.tcx.is_foreign_item(def_id) {
1537                    let data = self.tcx.eval_static_initializer(def_id).unwrap();
1538                    record!(self.tables.eval_static_initializer[def_id] <- data);
1539                }
1540            }
1541            if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind {
1542                self.encode_info_for_adt(local_id);
1543            }
1544            if let DefKind::Mod = def_kind {
1545                self.encode_info_for_mod(local_id);
1546            }
1547            if let DefKind::Macro(_) = def_kind {
1548                self.encode_info_for_macro(local_id);
1549            }
1550            if let DefKind::TyAlias = def_kind {
1551                self.tables
1552                    .type_alias_is_lazy
1553                    .set(def_id.index, self.tcx.type_alias_is_lazy(def_id));
1554            }
1555            if let DefKind::OpaqueTy = def_kind {
1556                self.encode_explicit_item_bounds(def_id);
1557                self.encode_explicit_item_self_bounds(def_id);
1558                record!(self.tables.opaque_ty_origin[def_id] <- self.tcx.opaque_ty_origin(def_id));
1559                self.encode_precise_capturing_args(def_id);
1560                if tcx.is_conditionally_const(def_id) {
1561                    record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1562                        <- tcx.explicit_implied_const_bounds(def_id).skip_binder());
1563                }
1564            }
1565            if tcx.impl_method_has_trait_impl_trait_tys(def_id)
1566                && let Ok(table) = self.tcx.collect_return_position_impl_trait_in_trait_tys(def_id)
1567            {
1568                record!(self.tables.trait_impl_trait_tys[def_id] <- table);
1569            }
1570            if should_encode_fn_impl_trait_in_trait(tcx, def_id) {
1571                let table = tcx.associated_types_for_impl_traits_in_associated_fn(def_id);
1572                record_defaulted_array!(self.tables.associated_types_for_impl_traits_in_associated_fn[def_id] <- table);
1573            }
1574        }
1575
1576        for (def_id, impls) in &tcx.crate_inherent_impls(()).0.inherent_impls {
1577            record_defaulted_array!(self.tables.inherent_impls[def_id.to_def_id()] <- impls.iter().map(|def_id| {
1578                assert!(def_id.is_local());
1579                def_id.index
1580            }));
1581        }
1582
1583        for (def_id, res_map) in &tcx.resolutions(()).doc_link_resolutions {
1584            record!(self.tables.doc_link_resolutions[def_id.to_def_id()] <- res_map);
1585        }
1586
1587        for (def_id, traits) in &tcx.resolutions(()).doc_link_traits_in_scope {
1588            record_array!(self.tables.doc_link_traits_in_scope[def_id.to_def_id()] <- traits);
1589        }
1590    }
1591
1592    #[instrument(level = "trace", skip(self))]
1593    fn encode_info_for_adt(&mut self, local_def_id: LocalDefId) {
1594        let def_id = local_def_id.to_def_id();
1595        let tcx = self.tcx;
1596        let adt_def = tcx.adt_def(def_id);
1597        record!(self.tables.repr_options[def_id] <- adt_def.repr());
1598
1599        let params_in_repr = self.tcx.params_in_repr(def_id);
1600        record!(self.tables.params_in_repr[def_id] <- params_in_repr);
1601
1602        if adt_def.is_enum() {
1603            let module_children = tcx.module_children_local(local_def_id);
1604            record_array!(self.tables.module_children_non_reexports[def_id] <-
1605                module_children.iter().map(|child| child.res.def_id().index));
1606        } else {
1607            // For non-enum, there is only one variant, and its def_id is the adt's.
1608            debug_assert_eq!(adt_def.variants().len(), 1);
1609            debug_assert_eq!(adt_def.non_enum_variant().def_id, def_id);
1610            // Therefore, the loop over variants will encode its fields as the adt's children.
1611        }
1612
1613        for (idx, variant) in adt_def.variants().iter_enumerated() {
1614            let data = VariantData {
1615                discr: variant.discr,
1616                idx,
1617                ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)),
1618                is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1619            };
1620            record!(self.tables.variant_data[variant.def_id] <- data);
1621
1622            record_array!(self.tables.associated_item_or_field_def_ids[variant.def_id] <- variant.fields.iter().map(|f| {
1623                assert!(f.did.is_local());
1624                f.did.index
1625            }));
1626
1627            for field in &variant.fields {
1628                self.tables.safety.set_some(field.did.index, field.safety);
1629            }
1630
1631            if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
1632                let fn_sig = tcx.fn_sig(ctor_def_id);
1633                // FIXME only encode signature for ctor_def_id
1634                record!(self.tables.fn_sig[variant.def_id] <- fn_sig);
1635            }
1636        }
1637    }
1638
1639    #[instrument(level = "debug", skip(self))]
1640    fn encode_info_for_mod(&mut self, local_def_id: LocalDefId) {
1641        let tcx = self.tcx;
1642        let def_id = local_def_id.to_def_id();
1643
1644        // If we are encoding a proc-macro crates, `encode_info_for_mod` will
1645        // only ever get called for the crate root. We still want to encode
1646        // the crate root for consistency with other crates (some of the resolver
1647        // code uses it). However, we skip encoding anything relating to child
1648        // items - we encode information about proc-macros later on.
1649        if self.is_proc_macro {
1650            // Encode this here because we don't do it in encode_def_ids.
1651            record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1652        } else {
1653            let module_children = tcx.module_children_local(local_def_id);
1654
1655            record_array!(self.tables.module_children_non_reexports[def_id] <-
1656                module_children.iter().filter(|child| child.reexport_chain.is_empty())
1657                    .map(|child| child.res.def_id().index));
1658
1659            record_defaulted_array!(self.tables.module_children_reexports[def_id] <-
1660                module_children.iter().filter(|child| !child.reexport_chain.is_empty()));
1661        }
1662    }
1663
1664    fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1665        debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1666        let bounds = self.tcx.explicit_item_bounds(def_id).skip_binder();
1667        record_defaulted_array!(self.tables.explicit_item_bounds[def_id] <- bounds);
1668    }
1669
1670    fn encode_explicit_item_self_bounds(&mut self, def_id: DefId) {
1671        debug!("EncodeContext::encode_explicit_item_self_bounds({:?})", def_id);
1672        let bounds = self.tcx.explicit_item_self_bounds(def_id).skip_binder();
1673        record_defaulted_array!(self.tables.explicit_item_self_bounds[def_id] <- bounds);
1674    }
1675
1676    #[instrument(level = "debug", skip(self))]
1677    fn encode_info_for_assoc_item(&mut self, def_id: DefId) {
1678        let tcx = self.tcx;
1679        let item = tcx.associated_item(def_id);
1680
1681        self.tables.defaultness.set_some(def_id.index, item.defaultness(tcx));
1682        self.tables.assoc_container.set_some(def_id.index, item.container);
1683
1684        match item.container {
1685            AssocItemContainer::Trait => {
1686                if let ty::AssocKind::Type = item.kind {
1687                    self.encode_explicit_item_bounds(def_id);
1688                    self.encode_explicit_item_self_bounds(def_id);
1689                    if tcx.is_conditionally_const(def_id) {
1690                        record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1691                            <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1692                    }
1693                }
1694            }
1695            AssocItemContainer::Impl => {
1696                if let Some(trait_item_def_id) = item.trait_item_def_id {
1697                    self.tables.trait_item_def_id.set_some(def_id.index, trait_item_def_id.into());
1698                }
1699            }
1700        }
1701        if let Some(rpitit_info) = item.opt_rpitit_info {
1702            record!(self.tables.opt_rpitit_info[def_id] <- rpitit_info);
1703            if matches!(rpitit_info, ty::ImplTraitInTraitData::Trait { .. }) {
1704                record_array!(
1705                    self.tables.assumed_wf_types_for_rpitit[def_id]
1706                        <- self.tcx.assumed_wf_types_for_rpitit(def_id)
1707                );
1708                self.encode_precise_capturing_args(def_id);
1709            }
1710        }
1711    }
1712
1713    fn encode_precise_capturing_args(&mut self, def_id: DefId) {
1714        let Some(precise_capturing_args) = self.tcx.rendered_precise_capturing_args(def_id) else {
1715            return;
1716        };
1717
1718        record_array!(self.tables.rendered_precise_capturing_args[def_id] <- precise_capturing_args);
1719    }
1720
1721    fn encode_mir(&mut self) {
1722        if self.is_proc_macro {
1723            return;
1724        }
1725
1726        let tcx = self.tcx;
1727        let reachable_set = tcx.reachable_set(());
1728
1729        let keys_and_jobs = tcx.mir_keys(()).iter().filter_map(|&def_id| {
1730            let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
1731            if encode_const || encode_opt { Some((def_id, encode_const, encode_opt)) } else { None }
1732        });
1733        for (def_id, encode_const, encode_opt) in keys_and_jobs {
1734            debug_assert!(encode_const || encode_opt);
1735
1736            debug!("EntryBuilder::encode_mir({:?})", def_id);
1737            if encode_opt {
1738                record!(self.tables.optimized_mir[def_id.to_def_id()] <- tcx.optimized_mir(def_id));
1739                self.tables
1740                    .cross_crate_inlinable
1741                    .set(def_id.to_def_id().index, self.tcx.cross_crate_inlinable(def_id));
1742                record!(self.tables.closure_saved_names_of_captured_variables[def_id.to_def_id()]
1743                    <- tcx.closure_saved_names_of_captured_variables(def_id));
1744
1745                if self.tcx.is_coroutine(def_id.to_def_id())
1746                    && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1747                {
1748                    record!(self.tables.mir_coroutine_witnesses[def_id.to_def_id()] <- witnesses);
1749                }
1750            }
1751            if encode_const {
1752                record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- tcx.mir_for_ctfe(def_id));
1753
1754                // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir`
1755                let abstract_const = tcx.thir_abstract_const(def_id);
1756                if let Ok(Some(abstract_const)) = abstract_const {
1757                    record!(self.tables.thir_abstract_const[def_id.to_def_id()] <- abstract_const);
1758                }
1759
1760                if should_encode_const(tcx.def_kind(def_id)) {
1761                    let qualifs = tcx.mir_const_qualif(def_id);
1762                    record!(self.tables.mir_const_qualif[def_id.to_def_id()] <- qualifs);
1763                    let body = tcx.hir_maybe_body_owned_by(def_id);
1764                    if let Some(body) = body {
1765                        let const_data = rendered_const(self.tcx, &body, def_id);
1766                        record!(self.tables.rendered_const[def_id.to_def_id()] <- const_data);
1767                    }
1768                }
1769            }
1770            record!(self.tables.promoted_mir[def_id.to_def_id()] <- tcx.promoted_mir(def_id));
1771
1772            if self.tcx.is_coroutine(def_id.to_def_id())
1773                && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1774            {
1775                record!(self.tables.mir_coroutine_witnesses[def_id.to_def_id()] <- witnesses);
1776            }
1777        }
1778
1779        // Encode all the deduced parameter attributes for everything that has MIR, even for items
1780        // that can't be inlined. But don't if we aren't optimizing in non-incremental mode, to
1781        // save the query traffic.
1782        if tcx.sess.opts.output_types.should_codegen()
1783            && tcx.sess.opts.optimize != OptLevel::No
1784            && tcx.sess.opts.incremental.is_none()
1785        {
1786            for &local_def_id in tcx.mir_keys(()) {
1787                if let DefKind::AssocFn | DefKind::Fn = tcx.def_kind(local_def_id) {
1788                    record_array!(self.tables.deduced_param_attrs[local_def_id.to_def_id()] <-
1789                        self.tcx.deduced_param_attrs(local_def_id.to_def_id()));
1790                }
1791            }
1792        }
1793    }
1794
1795    #[instrument(level = "debug", skip(self))]
1796    fn encode_stability(&mut self, def_id: DefId) {
1797        // The query lookup can take a measurable amount of time in crates with many items. Check if
1798        // the stability attributes are even enabled before using their queries.
1799        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1800            if let Some(stab) = self.tcx.lookup_stability(def_id) {
1801                record!(self.tables.lookup_stability[def_id] <- stab)
1802            }
1803        }
1804    }
1805
1806    #[instrument(level = "debug", skip(self))]
1807    fn encode_const_stability(&mut self, def_id: DefId) {
1808        // The query lookup can take a measurable amount of time in crates with many items. Check if
1809        // the stability attributes are even enabled before using their queries.
1810        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1811            if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1812                record!(self.tables.lookup_const_stability[def_id] <- stab)
1813            }
1814        }
1815    }
1816
1817    #[instrument(level = "debug", skip(self))]
1818    fn encode_default_body_stability(&mut self, def_id: DefId) {
1819        // The query lookup can take a measurable amount of time in crates with many items. Check if
1820        // the stability attributes are even enabled before using their queries.
1821        if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1822            if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
1823                record!(self.tables.lookup_default_body_stability[def_id] <- stab)
1824            }
1825        }
1826    }
1827
1828    #[instrument(level = "debug", skip(self))]
1829    fn encode_deprecation(&mut self, def_id: DefId) {
1830        if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1831            record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1832        }
1833    }
1834
1835    #[instrument(level = "debug", skip(self))]
1836    fn encode_info_for_macro(&mut self, def_id: LocalDefId) {
1837        let tcx = self.tcx;
1838
1839        let hir::ItemKind::Macro(macro_def, _) = tcx.hir_expect_item(def_id).kind else { bug!() };
1840        self.tables.is_macro_rules.set(def_id.local_def_index, macro_def.macro_rules);
1841        record!(self.tables.macro_definition[def_id.to_def_id()] <- &*macro_def.body);
1842    }
1843
1844    fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
1845        empty_proc_macro!(self);
1846        let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1847        self.lazy_array(used_libraries.iter())
1848    }
1849
1850    fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
1851        empty_proc_macro!(self);
1852        let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1853        self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
1854    }
1855
1856    fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1857        let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1858        let mut expn_data_table: TableBuilder<_, _> = Default::default();
1859        let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1860
1861        self.hygiene_ctxt.encode(
1862            &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1863            |(this, syntax_contexts, _, _), index, ctxt_data| {
1864                syntax_contexts.set_some(index, this.lazy(ctxt_data));
1865            },
1866            |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1867                if let Some(index) = index.as_local() {
1868                    expn_data_table.set_some(index.as_raw(), this.lazy(expn_data));
1869                    expn_hash_table.set_some(index.as_raw(), this.lazy(hash));
1870                }
1871            },
1872        );
1873
1874        (
1875            syntax_contexts.encode(&mut self.opaque),
1876            expn_data_table.encode(&mut self.opaque),
1877            expn_hash_table.encode(&mut self.opaque),
1878        )
1879    }
1880
1881    fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1882        let is_proc_macro = self.tcx.crate_types().contains(&CrateType::ProcMacro);
1883        if is_proc_macro {
1884            let tcx = self.tcx;
1885            let hir = tcx.hir();
1886
1887            let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1888            let stability = tcx.lookup_stability(CRATE_DEF_ID);
1889            let macros =
1890                self.lazy_array(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1891            for (i, span) in self.tcx.sess.psess.proc_macro_quoted_spans() {
1892                let span = self.lazy(span);
1893                self.tables.proc_macro_quoted_spans.set_some(i, span);
1894            }
1895
1896            self.tables.def_kind.set_some(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
1897            record!(self.tables.def_span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1898            self.encode_attrs(LOCAL_CRATE.as_def_id().expect_local());
1899            let vis = tcx.local_visibility(CRATE_DEF_ID).map_id(|def_id| def_id.local_def_index);
1900            record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- vis);
1901            if let Some(stability) = stability {
1902                record!(self.tables.lookup_stability[LOCAL_CRATE.as_def_id()] <- stability);
1903            }
1904            self.encode_deprecation(LOCAL_CRATE.as_def_id());
1905            if let Some(res_map) = tcx.resolutions(()).doc_link_resolutions.get(&CRATE_DEF_ID) {
1906                record!(self.tables.doc_link_resolutions[LOCAL_CRATE.as_def_id()] <- res_map);
1907            }
1908            if let Some(traits) = tcx.resolutions(()).doc_link_traits_in_scope.get(&CRATE_DEF_ID) {
1909                record_array!(self.tables.doc_link_traits_in_scope[LOCAL_CRATE.as_def_id()] <- traits);
1910            }
1911
1912            // Normally, this information is encoded when we walk the items
1913            // defined in this crate. However, we skip doing that for proc-macro crates,
1914            // so we manually encode just the information that we need
1915            for &proc_macro in &tcx.resolutions(()).proc_macros {
1916                let id = proc_macro;
1917                let proc_macro = tcx.local_def_id_to_hir_id(proc_macro);
1918                let mut name = tcx.hir_name(proc_macro);
1919                let span = hir.span(proc_macro);
1920                // Proc-macros may have attributes like `#[allow_internal_unstable]`,
1921                // so downstream crates need access to them.
1922                let attrs = tcx.hir_attrs(proc_macro);
1923                let macro_kind = if ast::attr::contains_name(attrs, sym::proc_macro) {
1924                    MacroKind::Bang
1925                } else if ast::attr::contains_name(attrs, sym::proc_macro_attribute) {
1926                    MacroKind::Attr
1927                } else if let Some(attr) = ast::attr::find_by_name(attrs, sym::proc_macro_derive) {
1928                    // This unwrap chain should have been checked by the proc-macro harness.
1929                    name = attr.meta_item_list().unwrap()[0]
1930                        .meta_item()
1931                        .unwrap()
1932                        .ident()
1933                        .unwrap()
1934                        .name;
1935                    MacroKind::Derive
1936                } else {
1937                    bug!("Unknown proc-macro type for item {:?}", id);
1938                };
1939
1940                let mut def_key = self.tcx.hir_def_key(id);
1941                def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1942
1943                let def_id = id.to_def_id();
1944                self.tables.def_kind.set_some(def_id.index, DefKind::Macro(macro_kind));
1945                self.tables.proc_macro.set_some(def_id.index, macro_kind);
1946                self.encode_attrs(id);
1947                record!(self.tables.def_keys[def_id] <- def_key);
1948                record!(self.tables.def_ident_span[def_id] <- span);
1949                record!(self.tables.def_span[def_id] <- span);
1950                record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1951                if let Some(stability) = stability {
1952                    record!(self.tables.lookup_stability[def_id] <- stability);
1953                }
1954            }
1955
1956            Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1957        } else {
1958            None
1959        }
1960    }
1961
1962    fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
1963        empty_proc_macro!(self);
1964        self.lazy_array(
1965            self.tcx
1966                .debugger_visualizers(LOCAL_CRATE)
1967                .iter()
1968                // Erase the path since it may contain privacy sensitive data
1969                // that we don't want to end up in crate metadata.
1970                // The path is only needed for the local crate because of
1971                // `--emit dep-info`.
1972                .map(DebuggerVisualizerFile::path_erased),
1973        )
1974    }
1975
1976    fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
1977        empty_proc_macro!(self);
1978
1979        let deps = self
1980            .tcx
1981            .crates(())
1982            .iter()
1983            .map(|&cnum| {
1984                let dep = CrateDep {
1985                    name: self.tcx.crate_name(cnum),
1986                    hash: self.tcx.crate_hash(cnum),
1987                    host_hash: self.tcx.crate_host_hash(cnum),
1988                    kind: self.tcx.dep_kind(cnum),
1989                    extra_filename: self.tcx.extra_filename(cnum).clone(),
1990                    is_private: self.tcx.is_private_dep(cnum),
1991                };
1992                (cnum, dep)
1993            })
1994            .collect::<Vec<_>>();
1995
1996        {
1997            // Sanity-check the crate numbers
1998            let mut expected_cnum = 1;
1999            for &(n, _) in &deps {
2000                assert_eq!(n, CrateNum::new(expected_cnum));
2001                expected_cnum += 1;
2002            }
2003        }
2004
2005        // We're just going to write a list of crate 'name-hash-version's, with
2006        // the assumption that they are numbered 1 to n.
2007        // FIXME (#2166): This is not nearly enough to support correct versioning
2008        // but is enough to get transitive crate dependencies working.
2009        self.lazy_array(deps.iter().map(|(_, dep)| dep))
2010    }
2011
2012    fn encode_target_modifiers(&mut self) -> LazyArray<TargetModifier> {
2013        empty_proc_macro!(self);
2014        let tcx = self.tcx;
2015        self.lazy_array(tcx.sess.opts.gather_target_modifiers())
2016    }
2017
2018    fn encode_lib_features(&mut self) -> LazyArray<(Symbol, FeatureStability)> {
2019        empty_proc_macro!(self);
2020        let tcx = self.tcx;
2021        let lib_features = tcx.lib_features(LOCAL_CRATE);
2022        self.lazy_array(lib_features.to_sorted_vec())
2023    }
2024
2025    fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
2026        empty_proc_macro!(self);
2027        let tcx = self.tcx;
2028        let implications = tcx.stability_implications(LOCAL_CRATE);
2029        let sorted = implications.to_sorted_stable_ord();
2030        self.lazy_array(sorted.into_iter().map(|(k, v)| (*k, *v)))
2031    }
2032
2033    fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, DefIndex)> {
2034        empty_proc_macro!(self);
2035        let tcx = self.tcx;
2036        let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
2037        self.lazy_array(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
2038    }
2039
2040    fn encode_lang_items(&mut self) -> LazyArray<(DefIndex, LangItem)> {
2041        empty_proc_macro!(self);
2042        let lang_items = self.tcx.lang_items().iter();
2043        self.lazy_array(lang_items.filter_map(|(lang_item, def_id)| {
2044            def_id.as_local().map(|id| (id.local_def_index, lang_item))
2045        }))
2046    }
2047
2048    fn encode_lang_items_missing(&mut self) -> LazyArray<LangItem> {
2049        empty_proc_macro!(self);
2050        let tcx = self.tcx;
2051        self.lazy_array(&tcx.lang_items().missing)
2052    }
2053
2054    fn encode_stripped_cfg_items(&mut self) -> LazyArray<StrippedCfgItem<DefIndex>> {
2055        self.lazy_array(
2056            self.tcx
2057                .stripped_cfg_items(LOCAL_CRATE)
2058                .into_iter()
2059                .map(|item| item.clone().map_mod_id(|def_id| def_id.index)),
2060        )
2061    }
2062
2063    fn encode_traits(&mut self) -> LazyArray<DefIndex> {
2064        empty_proc_macro!(self);
2065        self.lazy_array(self.tcx.traits(LOCAL_CRATE).iter().map(|def_id| def_id.index))
2066    }
2067
2068    /// Encodes an index, mapping each trait to its (local) implementations.
2069    #[instrument(level = "debug", skip(self))]
2070    fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
2071        empty_proc_macro!(self);
2072        let tcx = self.tcx;
2073        let mut trait_impls: FxIndexMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
2074            FxIndexMap::default();
2075
2076        for id in tcx.hir_free_items() {
2077            let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else {
2078                continue;
2079            };
2080            let def_id = id.owner_id.to_def_id();
2081
2082            self.tables.defaultness.set_some(def_id.index, tcx.defaultness(def_id));
2083
2084            if of_trait && let Some(header) = tcx.impl_trait_header(def_id) {
2085                record!(self.tables.impl_trait_header[def_id] <- header);
2086
2087                let trait_ref = header.trait_ref.instantiate_identity();
2088                let simplified_self_ty = fast_reject::simplify_type(
2089                    self.tcx,
2090                    trait_ref.self_ty(),
2091                    TreatParams::InstantiateWithInfer,
2092                );
2093                trait_impls
2094                    .entry(trait_ref.def_id)
2095                    .or_default()
2096                    .push((id.owner_id.def_id.local_def_index, simplified_self_ty));
2097
2098                let trait_def = tcx.trait_def(trait_ref.def_id);
2099                if let Ok(mut an) = trait_def.ancestors(tcx, def_id) {
2100                    if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) {
2101                        self.tables.impl_parent.set_some(def_id.index, parent.into());
2102                    }
2103                }
2104
2105                // if this is an impl of `CoerceUnsized`, create its
2106                // "unsized info", else just store None
2107                if tcx.is_lang_item(trait_ref.def_id, LangItem::CoerceUnsized) {
2108                    let coerce_unsized_info = tcx.coerce_unsized_info(def_id).unwrap();
2109                    record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
2110                }
2111            }
2112        }
2113
2114        let trait_impls: Vec<_> = trait_impls
2115            .into_iter()
2116            .map(|(trait_def_id, impls)| TraitImpls {
2117                trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
2118                impls: self.lazy_array(&impls),
2119            })
2120            .collect();
2121
2122        self.lazy_array(&trait_impls)
2123    }
2124
2125    #[instrument(level = "debug", skip(self))]
2126    fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
2127        empty_proc_macro!(self);
2128        let tcx = self.tcx;
2129
2130        let all_impls: Vec<_> = tcx
2131            .crate_inherent_impls(())
2132            .0
2133            .incoherent_impls
2134            .iter()
2135            .map(|(&simp, impls)| IncoherentImpls {
2136                self_ty: simp,
2137                impls: self.lazy_array(impls.iter().map(|def_id| def_id.local_def_index)),
2138            })
2139            .collect();
2140
2141        self.lazy_array(&all_impls)
2142    }
2143
2144    // Encodes all symbols exported from this crate into the metadata.
2145    //
2146    // This pass is seeded off the reachability list calculated in the
2147    // middle::reachable module but filters out items that either don't have a
2148    // symbol associated with them (they weren't translated) or if they're an FFI
2149    // definition (as that's not defined in this crate).
2150    fn encode_exported_symbols(
2151        &mut self,
2152        exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
2153    ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
2154        empty_proc_macro!(self);
2155        // The metadata symbol name is special. It should not show up in
2156        // downstream crates.
2157        let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
2158
2159        self.lazy_array(
2160            exported_symbols
2161                .iter()
2162                .filter(|&(exported_symbol, _)| match *exported_symbol {
2163                    ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
2164                    _ => true,
2165                })
2166                .cloned(),
2167        )
2168    }
2169
2170    fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
2171        empty_proc_macro!(self);
2172        let formats = self.tcx.dependency_formats(());
2173        if let Some(arr) = formats.get(&CrateType::Dylib) {
2174            return self.lazy_array(arr.iter().skip(1 /* skip LOCAL_CRATE */).map(
2175                |slot| match *slot {
2176                    Linkage::NotLinked | Linkage::IncludedFromDylib => None,
2177
2178                    Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
2179                    Linkage::Static => Some(LinkagePreference::RequireStatic),
2180                },
2181            ));
2182        }
2183        LazyArray::default()
2184    }
2185}
2186
2187/// Used to prefetch queries which will be needed later by metadata encoding.
2188/// Only a subset of the queries are actually prefetched to keep this code smaller.
2189fn prefetch_mir(tcx: TyCtxt<'_>) {
2190    if !tcx.sess.opts.output_types.should_codegen() {
2191        // We won't emit MIR, so don't prefetch it.
2192        return;
2193    }
2194
2195    let reachable_set = tcx.reachable_set(());
2196    par_for_each_in(tcx.mir_keys(()), |&def_id| {
2197        let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
2198
2199        if encode_const {
2200            tcx.ensure_done().mir_for_ctfe(def_id);
2201        }
2202        if encode_opt {
2203            tcx.ensure_done().optimized_mir(def_id);
2204        }
2205        if encode_opt || encode_const {
2206            tcx.ensure_done().promoted_mir(def_id);
2207        }
2208    })
2209}
2210
2211// NOTE(eddyb) The following comment was preserved for posterity, even
2212// though it's no longer relevant as EBML (which uses nested & tagged
2213// "documents") was replaced with a scheme that can't go out of bounds.
2214//
2215// And here we run into yet another obscure archive bug: in which metadata
2216// loaded from archives may have trailing garbage bytes. Awhile back one of
2217// our tests was failing sporadically on the macOS 64-bit builders (both nopt
2218// and opt) by having ebml generate an out-of-bounds panic when looking at
2219// metadata.
2220//
2221// Upon investigation it turned out that the metadata file inside of an rlib
2222// (and ar archive) was being corrupted. Some compilations would generate a
2223// metadata file which would end in a few extra bytes, while other
2224// compilations would not have these extra bytes appended to the end. These
2225// extra bytes were interpreted by ebml as an extra tag, so they ended up
2226// being interpreted causing the out-of-bounds.
2227//
2228// The root cause of why these extra bytes were appearing was never
2229// discovered, and in the meantime the solution we're employing is to insert
2230// the length of the metadata to the start of the metadata. Later on this
2231// will allow us to slice the metadata to the precise length that we just
2232// generated regardless of trailing bytes that end up in it.
2233
2234pub struct EncodedMetadata {
2235    // The declaration order matters because `mmap` should be dropped before `_temp_dir`.
2236    mmap: Option<Mmap>,
2237    // We need to carry MaybeTempDir to avoid deleting the temporary
2238    // directory while accessing the Mmap.
2239    _temp_dir: Option<MaybeTempDir>,
2240}
2241
2242impl EncodedMetadata {
2243    #[inline]
2244    pub fn from_path(path: PathBuf, temp_dir: Option<MaybeTempDir>) -> std::io::Result<Self> {
2245        let file = std::fs::File::open(&path)?;
2246        let file_metadata = file.metadata()?;
2247        if file_metadata.len() == 0 {
2248            return Ok(Self { mmap: None, _temp_dir: None });
2249        }
2250        let mmap = unsafe { Some(Mmap::map(file)?) };
2251        Ok(Self { mmap, _temp_dir: temp_dir })
2252    }
2253
2254    #[inline]
2255    pub fn raw_data(&self) -> &[u8] {
2256        self.mmap.as_deref().unwrap_or_default()
2257    }
2258}
2259
2260impl<S: Encoder> Encodable<S> for EncodedMetadata {
2261    fn encode(&self, s: &mut S) {
2262        let slice = self.raw_data();
2263        slice.encode(s)
2264    }
2265}
2266
2267impl<D: Decoder> Decodable<D> for EncodedMetadata {
2268    fn decode(d: &mut D) -> Self {
2269        let len = d.read_usize();
2270        let mmap = if len > 0 {
2271            let mut mmap = MmapMut::map_anon(len).unwrap();
2272            mmap.copy_from_slice(d.read_raw_bytes(len));
2273            Some(mmap.make_read_only().unwrap())
2274        } else {
2275            None
2276        };
2277
2278        Self { mmap, _temp_dir: None }
2279    }
2280}
2281
2282pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path) {
2283    let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2284
2285    // Since encoding metadata is not in a query, and nothing is cached,
2286    // there's no need to do dep-graph tracking for any of it.
2287    tcx.dep_graph.assert_ignored();
2288
2289    if tcx.sess.threads() != 1 {
2290        // Prefetch some queries used by metadata encoding.
2291        // This is not necessary for correctness, but is only done for performance reasons.
2292        // It can be removed if it turns out to cause trouble or be detrimental to performance.
2293        join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2294    }
2295
2296    let mut encoder = opaque::FileEncoder::new(path)
2297        .unwrap_or_else(|err| tcx.dcx().emit_fatal(FailCreateFileEncoder { err }));
2298    encoder.emit_raw_bytes(METADATA_HEADER);
2299
2300    // Will be filled with the root position after encoding everything.
2301    encoder.emit_raw_bytes(&0u64.to_le_bytes());
2302
2303    let source_map_files = tcx.sess.source_map().files();
2304    let source_file_cache = (Arc::clone(&source_map_files[0]), 0);
2305    let required_source_files = Some(FxIndexSet::default());
2306    drop(source_map_files);
2307
2308    let hygiene_ctxt = HygieneEncodeContext::default();
2309
2310    let mut ecx = EncodeContext {
2311        opaque: encoder,
2312        tcx,
2313        feat: tcx.features(),
2314        tables: Default::default(),
2315        lazy_state: LazyState::NoNode,
2316        span_shorthands: Default::default(),
2317        type_shorthands: Default::default(),
2318        predicate_shorthands: Default::default(),
2319        source_file_cache,
2320        interpret_allocs: Default::default(),
2321        required_source_files,
2322        is_proc_macro: tcx.crate_types().contains(&CrateType::ProcMacro),
2323        hygiene_ctxt: &hygiene_ctxt,
2324        symbol_table: Default::default(),
2325    };
2326
2327    // Encode the rustc version string in a predictable location.
2328    rustc_version(tcx.sess.cfg_version).encode(&mut ecx);
2329
2330    // Encode all the entries and extra information in the crate,
2331    // culminating in the `CrateRoot` which points to all of it.
2332    let root = ecx.encode_crate_root();
2333
2334    // Make sure we report any errors from writing to the file.
2335    // If we forget this, compilation can succeed with an incomplete rmeta file,
2336    // causing an ICE when the rmeta file is read by another compilation.
2337    if let Err((path, err)) = ecx.opaque.finish() {
2338        tcx.dcx().emit_fatal(FailWriteFile { path: &path, err });
2339    }
2340
2341    let file = ecx.opaque.file();
2342    if let Err(err) = encode_root_position(file, root.position.get()) {
2343        tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2344    }
2345
2346    // Record metadata size for self-profiling
2347    tcx.prof.artifact_size("crate_metadata", "crate_metadata", file.metadata().unwrap().len());
2348}
2349
2350fn encode_root_position(mut file: &File, pos: usize) -> Result<(), std::io::Error> {
2351    // We will return to this position after writing the root position.
2352    let pos_before_seek = file.stream_position().unwrap();
2353
2354    // Encode the root position.
2355    let header = METADATA_HEADER.len();
2356    file.seek(std::io::SeekFrom::Start(header as u64))?;
2357    file.write_all(&pos.to_le_bytes())?;
2358
2359    // Return to the position where we are before writing the root position.
2360    file.seek(std::io::SeekFrom::Start(pos_before_seek))?;
2361    Ok(())
2362}
2363
2364pub(crate) fn provide(providers: &mut Providers) {
2365    *providers = Providers {
2366        doc_link_resolutions: |tcx, def_id| {
2367            tcx.resolutions(())
2368                .doc_link_resolutions
2369                .get(&def_id)
2370                .unwrap_or_else(|| span_bug!(tcx.def_span(def_id), "no resolutions for a doc link"))
2371        },
2372        doc_link_traits_in_scope: |tcx, def_id| {
2373            tcx.resolutions(()).doc_link_traits_in_scope.get(&def_id).unwrap_or_else(|| {
2374                span_bug!(tcx.def_span(def_id), "no traits in scope for a doc link")
2375            })
2376        },
2377
2378        ..*providers
2379    }
2380}
2381
2382/// Build a textual representation of an unevaluated constant expression.
2383///
2384/// If the const expression is too complex, an underscore `_` is returned.
2385/// For const arguments, it's `{ _ }` to be precise.
2386/// This means that the output is not necessarily valid Rust code.
2387///
2388/// Currently, only
2389///
2390/// * literals (optionally with a leading `-`)
2391/// * unit `()`
2392/// * blocks (`{ … }`) around simple expressions and
2393/// * paths without arguments
2394///
2395/// are considered simple enough. Simple blocks are included since they are
2396/// necessary to disambiguate unit from the unit type.
2397/// This list might get extended in the future.
2398///
2399/// Without this censoring, in a lot of cases the output would get too large
2400/// and verbose. Consider `match` expressions, blocks and deeply nested ADTs.
2401/// Further, private and `doc(hidden)` fields of structs would get leaked
2402/// since HIR datatypes like the `body` parameter do not contain enough
2403/// semantic information for this function to be able to hide them –
2404/// at least not without significant performance overhead.
2405///
2406/// Whenever possible, prefer to evaluate the constant first and try to
2407/// use a different method for pretty-printing. Ideally this function
2408/// should only ever be used as a fallback.
2409pub fn rendered_const<'tcx>(tcx: TyCtxt<'tcx>, body: &hir::Body<'_>, def_id: LocalDefId) -> String {
2410    let value = body.value;
2411
2412    #[derive(PartialEq, Eq)]
2413    enum Classification {
2414        Literal,
2415        Simple,
2416        Complex,
2417    }
2418
2419    use Classification::*;
2420
2421    fn classify(expr: &hir::Expr<'_>) -> Classification {
2422        match &expr.kind {
2423            hir::ExprKind::Unary(hir::UnOp::Neg, expr) => {
2424                if matches!(expr.kind, hir::ExprKind::Lit(_)) { Literal } else { Complex }
2425            }
2426            hir::ExprKind::Lit(_) => Literal,
2427            hir::ExprKind::Tup([]) => Simple,
2428            hir::ExprKind::Block(hir::Block { stmts: [], expr: Some(expr), .. }, _) => {
2429                if classify(expr) == Complex { Complex } else { Simple }
2430            }
2431            // Paths with a self-type or arguments are too “complex” following our measure since
2432            // they may leak private fields of structs (with feature `adt_const_params`).
2433            // Consider: `<Self as Trait<{ Struct { private: () } }>>::CONSTANT`.
2434            // Paths without arguments are definitely harmless though.
2435            hir::ExprKind::Path(hir::QPath::Resolved(_, hir::Path { segments, .. })) => {
2436                if segments.iter().all(|segment| segment.args.is_none()) { Simple } else { Complex }
2437            }
2438            // FIXME: Claiming that those kinds of QPaths are simple is probably not true if the Ty
2439            //        contains const arguments. Is there a *concise* way to check for this?
2440            hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => Simple,
2441            // FIXME: Can they contain const arguments and thus leak private struct fields?
2442            hir::ExprKind::Path(hir::QPath::LangItem(..)) => Simple,
2443            _ => Complex,
2444        }
2445    }
2446
2447    match classify(value) {
2448        // For non-macro literals, we avoid invoking the pretty-printer and use the source snippet
2449        // instead to preserve certain stylistic choices the user likely made for the sake of
2450        // legibility, like:
2451        //
2452        // * hexadecimal notation
2453        // * underscores
2454        // * character escapes
2455        //
2456        // FIXME: This passes through `-/*spacer*/0` verbatim.
2457        Literal
2458            if !value.span.from_expansion()
2459                && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(value.span) =>
2460        {
2461            snippet
2462        }
2463
2464        // Otherwise we prefer pretty-printing to get rid of extraneous whitespace, comments and
2465        // other formatting artifacts.
2466        Literal | Simple => id_to_string(&tcx, body.id().hir_id),
2467
2468        // FIXME: Omit the curly braces if the enclosing expression is an array literal
2469        //        with a repeated element (an `ExprKind::Repeat`) as in such case it
2470        //        would not actually need any disambiguation.
2471        Complex => {
2472            if tcx.def_kind(def_id) == DefKind::AnonConst {
2473                "{ _ }".to_owned()
2474            } else {
2475                "_".to_owned()
2476            }
2477        }
2478    }
2479}