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 source_file_cache: (Arc<SourceFile>, usize),
57 required_source_files: Option<FxIndexSet<usize>>,
64 is_proc_macro: bool,
65 hygiene_ctxt: &'a HygieneEncodeContext,
66 symbol_table: FxHashMap<Symbol, usize>,
67}
68
69macro_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 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 let last_location = *o.get();
175 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 span.data().encode(self);
199 }
200 }
201 }
202
203 fn encode_symbol(&mut self, symbol: Symbol) {
204 if symbol.is_preinterned() {
206 self.opaque.emit_u8(SYMBOL_PREINTERNED);
207 self.opaque.emit_u32(symbol.as_u32());
208 } else {
209 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 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 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 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 let (kind, metadata_index) = if source_file.is_imported() && !s.is_proc_macro {
315 let metadata_index = {
325 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 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 let lo = self.lo - source_file.start_pos;
347
348 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 metadata_index.encode(s);
364
365 if kind == SpanKind::Foreign {
366 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 for EncodeContext<'a, 'tcx> {
382 const CLEAR_CROSS_CRATE: bool = true;
383
384 type I = TyCtxt<'tcx>;
385
386 fn position(&self) -> usize {
387 self.opaque.position()
388 }
389
390 fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> {
391 &mut self.type_shorthands
392 }
393
394 fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> {
395 &mut self.predicate_shorthands
396 }
397
398 fn encode_alloc_id(&mut self, alloc_id: &rustc_middle::mir::interpret::AllocId) {
399 let (index, _) = self.interpret_allocs.insert_full(*alloc_id);
400
401 index.encode(self);
402 }
403}
404
405macro_rules! record {
408 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
409 {
410 let value = $value;
411 let lazy = $self.lazy(value);
412 $self.$tables.$table.set_some($def_id.index, lazy);
413 }
414 }};
415}
416
417macro_rules! record_array {
420 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
421 {
422 let value = $value;
423 let lazy = $self.lazy_array(value);
424 $self.$tables.$table.set_some($def_id.index, lazy);
425 }
426 }};
427}
428
429macro_rules! record_defaulted_array {
430 ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
431 {
432 let value = $value;
433 let lazy = $self.lazy_array(value);
434 $self.$tables.$table.set($def_id.index, lazy);
435 }
436 }};
437}
438
439impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
440 fn emit_lazy_distance(&mut self, position: NonZero<usize>) {
441 let pos = position.get();
442 let distance = match self.lazy_state {
443 LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
444 LazyState::NodeStart(start) => {
445 let start = start.get();
446 assert!(pos <= start);
447 start - pos
448 }
449 LazyState::Previous(last_pos) => {
450 assert!(
451 last_pos <= position,
452 "make sure that the calls to `lazy*` \
453 are in the same order as the metadata fields",
454 );
455 position.get() - last_pos.get()
456 }
457 };
458 self.lazy_state = LazyState::Previous(NonZero::new(pos).unwrap());
459 self.emit_usize(distance);
460 }
461
462 fn lazy<T: ParameterizedOverTcx, B: Borrow<T::Value<'tcx>>>(&mut self, value: B) -> LazyValue<T>
463 where
464 T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
465 {
466 let pos = NonZero::new(self.position()).unwrap();
467
468 assert_eq!(self.lazy_state, LazyState::NoNode);
469 self.lazy_state = LazyState::NodeStart(pos);
470 value.borrow().encode(self);
471 self.lazy_state = LazyState::NoNode;
472
473 assert!(pos.get() <= self.position());
474
475 LazyValue::from_position(pos)
476 }
477
478 fn lazy_array<T: ParameterizedOverTcx, I: IntoIterator<Item = B>, B: Borrow<T::Value<'tcx>>>(
479 &mut self,
480 values: I,
481 ) -> LazyArray<T>
482 where
483 T::Value<'tcx>: Encodable<EncodeContext<'a, 'tcx>>,
484 {
485 let pos = NonZero::new(self.position()).unwrap();
486
487 assert_eq!(self.lazy_state, LazyState::NoNode);
488 self.lazy_state = LazyState::NodeStart(pos);
489 let len = values.into_iter().map(|value| value.borrow().encode(self)).count();
490 self.lazy_state = LazyState::NoNode;
491
492 assert!(pos.get() <= self.position());
493
494 LazyArray::from_position_and_num_elems(pos, len)
495 }
496
497 fn encode_def_path_table(&mut self) {
498 let table = self.tcx.def_path_table();
499 if self.is_proc_macro {
500 for def_index in std::iter::once(CRATE_DEF_INDEX)
501 .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index))
502 {
503 let def_key = self.lazy(table.def_key(def_index));
504 let def_path_hash = table.def_path_hash(def_index);
505 self.tables.def_keys.set_some(def_index, def_key);
506 self.tables.def_path_hashes.set(def_index, def_path_hash.local_hash().as_u64());
507 }
508 } else {
509 for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() {
510 let def_key = self.lazy(def_key);
511 self.tables.def_keys.set_some(def_index, def_key);
512 self.tables.def_path_hashes.set(def_index, def_path_hash.local_hash().as_u64());
513 }
514 }
515 }
516
517 fn encode_def_path_hash_map(&mut self) -> LazyValue<DefPathHashMapRef<'static>> {
518 self.lazy(DefPathHashMapRef::BorrowedFromTcx(self.tcx.def_path_hash_to_def_index_map()))
519 }
520
521 fn encode_source_map(&mut self) -> LazyTable<u32, Option<LazyValue<rustc_span::SourceFile>>> {
522 let source_map = self.tcx.sess.source_map();
523 let all_source_files = source_map.files();
524
525 let required_source_files = self.required_source_files.take().unwrap();
529
530 let working_directory = &self.tcx.sess.opts.working_dir;
531
532 let mut adapted = TableBuilder::default();
533
534 let local_crate_stable_id = self.tcx.stable_crate_id(LOCAL_CRATE);
535
536 for (on_disk_index, &source_file_index) in required_source_files.iter().enumerate() {
541 let source_file = &all_source_files[source_file_index];
542 assert!(!source_file.is_imported() || self.is_proc_macro);
544
545 let mut adapted_source_file = (**source_file).clone();
553
554 match source_file.name {
555 FileName::Real(ref original_file_name) => {
556 let adapted_file_name = source_map
559 .path_mapping()
560 .to_embeddable_absolute_path(original_file_name.clone(), working_directory);
561
562 adapted_source_file.name = FileName::Real(adapted_file_name);
563 }
564 _ => {
565 }
567 };
568
569 if self.is_proc_macro {
576 adapted_source_file.cnum = LOCAL_CRATE;
577 }
578
579 adapted_source_file.stable_id = StableSourceFileId::from_filename_for_export(
583 &adapted_source_file.name,
584 local_crate_stable_id,
585 );
586
587 let on_disk_index: u32 =
588 on_disk_index.try_into().expect("cannot export more than U32_MAX files");
589 adapted.set_some(on_disk_index, self.lazy(adapted_source_file));
590 }
591
592 adapted.encode(&mut self.opaque)
593 }
594
595 fn encode_crate_root(&mut self) -> LazyValue<CrateRoot> {
596 let tcx = self.tcx;
597 let mut stats: Vec<(&'static str, usize)> = Vec::with_capacity(32);
598
599 macro_rules! stat {
600 ($label:literal, $f:expr) => {{
601 let orig_pos = self.position();
602 let res = $f();
603 stats.push(($label, self.position() - orig_pos));
604 res
605 }};
606 }
607
608 stats.push(("preamble", self.position()));
610
611 let (crate_deps, dylib_dependency_formats) =
612 stat!("dep", || (self.encode_crate_deps(), self.encode_dylib_dependency_formats()));
613
614 let lib_features = stat!("lib-features", || self.encode_lib_features());
615
616 let stability_implications =
617 stat!("stability-implications", || self.encode_stability_implications());
618
619 let (lang_items, lang_items_missing) = stat!("lang-items", || {
620 (self.encode_lang_items(), self.encode_lang_items_missing())
621 });
622
623 let stripped_cfg_items = stat!("stripped-cfg-items", || self.encode_stripped_cfg_items());
624
625 let diagnostic_items = stat!("diagnostic-items", || self.encode_diagnostic_items());
626
627 let native_libraries = stat!("native-libs", || self.encode_native_libraries());
628
629 let foreign_modules = stat!("foreign-modules", || self.encode_foreign_modules());
630
631 _ = stat!("def-path-table", || self.encode_def_path_table());
632
633 let traits = stat!("traits", || self.encode_traits());
635
636 let impls = stat!("impls", || self.encode_impls());
638
639 let incoherent_impls = stat!("incoherent-impls", || self.encode_incoherent_impls());
640
641 _ = stat!("mir", || self.encode_mir());
642
643 _ = stat!("def-ids", || self.encode_def_ids());
644
645 let interpret_alloc_index = stat!("interpret-alloc-index", || {
646 let mut interpret_alloc_index = Vec::new();
647 let mut n = 0;
648 trace!("beginning to encode alloc ids");
649 loop {
650 let new_n = self.interpret_allocs.len();
651 if n == new_n {
653 break;
655 }
656 trace!("encoding {} further alloc ids", new_n - n);
657 for idx in n..new_n {
658 let id = self.interpret_allocs[idx];
659 let pos = self.position() as u64;
660 interpret_alloc_index.push(pos);
661 interpret::specialized_encode_alloc_id(self, tcx, id);
662 }
663 n = new_n;
664 }
665 self.lazy_array(interpret_alloc_index)
666 });
667
668 let proc_macro_data = stat!("proc-macro-data", || self.encode_proc_macros());
672
673 let tables = stat!("tables", || self.tables.encode(&mut self.opaque));
674
675 let debugger_visualizers =
676 stat!("debugger-visualizers", || self.encode_debugger_visualizers());
677
678 let exported_symbols = stat!("exported-symbols", || {
680 self.encode_exported_symbols(tcx.exported_symbols(LOCAL_CRATE))
681 });
682
683 let (syntax_contexts, expn_data, expn_hashes) = stat!("hygiene", || self.encode_hygiene());
690
691 let def_path_hash_map = stat!("def-path-hash-map", || self.encode_def_path_hash_map());
692
693 let source_map = stat!("source-map", || self.encode_source_map());
696 let target_modifiers = stat!("target-modifiers", || self.encode_target_modifiers());
697
698 let root = stat!("final", || {
699 let attrs = tcx.hir().krate_attrs();
700 self.lazy(CrateRoot {
701 header: CrateHeader {
702 name: tcx.crate_name(LOCAL_CRATE),
703 triple: tcx.sess.opts.target_triple.clone(),
704 hash: tcx.crate_hash(LOCAL_CRATE),
705 is_proc_macro_crate: proc_macro_data.is_some(),
706 },
707 extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
708 stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(),
709 required_panic_strategy: tcx.required_panic_strategy(LOCAL_CRATE),
710 panic_in_drop_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
711 edition: tcx.sess.edition(),
712 has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
713 has_alloc_error_handler: tcx.has_alloc_error_handler(LOCAL_CRATE),
714 has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
715 has_default_lib_allocator: ast::attr::contains_name(
716 attrs,
717 sym::default_lib_allocator,
718 ),
719 proc_macro_data,
720 debugger_visualizers,
721 compiler_builtins: ast::attr::contains_name(attrs, sym::compiler_builtins),
722 needs_allocator: ast::attr::contains_name(attrs, sym::needs_allocator),
723 needs_panic_runtime: ast::attr::contains_name(attrs, sym::needs_panic_runtime),
724 no_builtins: ast::attr::contains_name(attrs, sym::no_builtins),
725 panic_runtime: ast::attr::contains_name(attrs, sym::panic_runtime),
726 profiler_runtime: ast::attr::contains_name(attrs, sym::profiler_runtime),
727 symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(),
728
729 crate_deps,
730 dylib_dependency_formats,
731 lib_features,
732 stability_implications,
733 lang_items,
734 diagnostic_items,
735 lang_items_missing,
736 stripped_cfg_items,
737 native_libraries,
738 foreign_modules,
739 source_map,
740 target_modifiers,
741 traits,
742 impls,
743 incoherent_impls,
744 exported_symbols,
745 interpret_alloc_index,
746 tables,
747 syntax_contexts,
748 expn_data,
749 expn_hashes,
750 def_path_hash_map,
751 specialization_enabled_in: tcx.specialization_enabled_in(LOCAL_CRATE),
752 })
753 });
754
755 let total_bytes = self.position();
756
757 let computed_total_bytes: usize = stats.iter().map(|(_, size)| size).sum();
758 assert_eq!(total_bytes, computed_total_bytes);
759
760 if tcx.sess.opts.unstable_opts.meta_stats {
761 self.opaque.flush();
762
763 let pos_before_rewind = self.opaque.file().stream_position().unwrap();
765 let mut zero_bytes = 0;
766 self.opaque.file().rewind().unwrap();
767 let file = std::io::BufReader::new(self.opaque.file());
768 for e in file.bytes() {
769 if e.unwrap() == 0 {
770 zero_bytes += 1;
771 }
772 }
773 assert_eq!(self.opaque.file().stream_position().unwrap(), pos_before_rewind);
774
775 stats.sort_by_key(|&(_, usize)| usize);
776
777 let prefix = "meta-stats";
778 let perc = |bytes| (bytes * 100) as f64 / total_bytes as f64;
779
780 eprintln!("{prefix} METADATA STATS");
781 eprintln!("{} {:<23}{:>10}", prefix, "Section", "Size");
782 eprintln!("{prefix} ----------------------------------------------------------------");
783 for (label, size) in stats {
784 eprintln!(
785 "{} {:<23}{:>10} ({:4.1}%)",
786 prefix,
787 label,
788 format_with_underscores(size),
789 perc(size)
790 );
791 }
792 eprintln!("{prefix} ----------------------------------------------------------------");
793 eprintln!(
794 "{} {:<23}{:>10} (of which {:.1}% are zero bytes)",
795 prefix,
796 "Total",
797 format_with_underscores(total_bytes),
798 perc(zero_bytes)
799 );
800 eprintln!("{prefix}");
801 }
802
803 root
804 }
805}
806
807struct AnalyzeAttrState<'a> {
808 is_exported: bool,
809 is_doc_hidden: bool,
810 features: &'a Features,
811}
812
813#[inline]
823fn analyze_attr(attr: &impl AttributeExt, state: &mut AnalyzeAttrState<'_>) -> bool {
824 let mut should_encode = false;
825 if !rustc_feature::encode_cross_crate(attr.name_or_empty()) {
826 } else if attr.doc_str().is_some() {
828 if state.is_exported {
832 should_encode = true;
833 }
834 } else if attr.has_name(sym::doc) {
835 if let Some(item_list) = attr.meta_item_list() {
838 for item in item_list {
839 if !item.has_name(sym::inline) {
840 should_encode = true;
841 if item.has_name(sym::hidden) {
842 state.is_doc_hidden = true;
843 break;
844 }
845 }
846 }
847 }
848 } else if attr.path().starts_with(&[sym::diagnostic]) && attr.path().len() == 2 {
849 should_encode =
850 rustc_feature::is_stable_diagnostic_attribute(attr.path()[1], state.features);
851 } else {
852 should_encode = true;
853 }
854 should_encode
855}
856
857fn should_encode_span(def_kind: DefKind) -> bool {
858 match def_kind {
859 DefKind::Mod
860 | DefKind::Struct
861 | DefKind::Union
862 | DefKind::Enum
863 | DefKind::Variant
864 | DefKind::Trait
865 | DefKind::TyAlias
866 | DefKind::ForeignTy
867 | DefKind::TraitAlias
868 | DefKind::AssocTy
869 | DefKind::TyParam
870 | DefKind::ConstParam
871 | DefKind::LifetimeParam
872 | DefKind::Fn
873 | DefKind::Const
874 | DefKind::Static { .. }
875 | DefKind::Ctor(..)
876 | DefKind::AssocFn
877 | DefKind::AssocConst
878 | DefKind::Macro(_)
879 | DefKind::ExternCrate
880 | DefKind::Use
881 | DefKind::AnonConst
882 | DefKind::InlineConst
883 | DefKind::OpaqueTy
884 | DefKind::Field
885 | DefKind::Impl { .. }
886 | DefKind::Closure
887 | DefKind::SyntheticCoroutineBody => true,
888 DefKind::ForeignMod | DefKind::GlobalAsm => false,
889 }
890}
891
892fn should_encode_attrs(def_kind: DefKind) -> bool {
893 match def_kind {
894 DefKind::Mod
895 | DefKind::Struct
896 | DefKind::Union
897 | DefKind::Enum
898 | DefKind::Variant
899 | DefKind::Trait
900 | DefKind::TyAlias
901 | DefKind::ForeignTy
902 | DefKind::TraitAlias
903 | DefKind::AssocTy
904 | DefKind::Fn
905 | DefKind::Const
906 | DefKind::Static { nested: false, .. }
907 | DefKind::AssocFn
908 | DefKind::AssocConst
909 | DefKind::Macro(_)
910 | DefKind::Field
911 | DefKind::Impl { .. } => true,
912 DefKind::Closure => true,
917 DefKind::SyntheticCoroutineBody => false,
918 DefKind::TyParam
919 | DefKind::ConstParam
920 | DefKind::Ctor(..)
921 | DefKind::ExternCrate
922 | DefKind::Use
923 | DefKind::ForeignMod
924 | DefKind::AnonConst
925 | DefKind::InlineConst
926 | DefKind::OpaqueTy
927 | DefKind::LifetimeParam
928 | DefKind::Static { nested: true, .. }
929 | DefKind::GlobalAsm => false,
930 }
931}
932
933fn should_encode_expn_that_defined(def_kind: DefKind) -> bool {
934 match def_kind {
935 DefKind::Mod
936 | DefKind::Struct
937 | DefKind::Union
938 | DefKind::Enum
939 | DefKind::Variant
940 | DefKind::Trait
941 | DefKind::Impl { .. } => true,
942 DefKind::TyAlias
943 | DefKind::ForeignTy
944 | DefKind::TraitAlias
945 | DefKind::AssocTy
946 | DefKind::TyParam
947 | DefKind::Fn
948 | DefKind::Const
949 | DefKind::ConstParam
950 | DefKind::Static { .. }
951 | DefKind::Ctor(..)
952 | DefKind::AssocFn
953 | DefKind::AssocConst
954 | DefKind::Macro(_)
955 | DefKind::ExternCrate
956 | DefKind::Use
957 | DefKind::ForeignMod
958 | DefKind::AnonConst
959 | DefKind::InlineConst
960 | DefKind::OpaqueTy
961 | DefKind::Field
962 | DefKind::LifetimeParam
963 | DefKind::GlobalAsm
964 | DefKind::Closure
965 | DefKind::SyntheticCoroutineBody => false,
966 }
967}
968
969fn should_encode_visibility(def_kind: DefKind) -> bool {
970 match def_kind {
971 DefKind::Mod
972 | DefKind::Struct
973 | DefKind::Union
974 | DefKind::Enum
975 | DefKind::Variant
976 | DefKind::Trait
977 | DefKind::TyAlias
978 | DefKind::ForeignTy
979 | DefKind::TraitAlias
980 | DefKind::AssocTy
981 | DefKind::Fn
982 | DefKind::Const
983 | DefKind::Static { nested: false, .. }
984 | DefKind::Ctor(..)
985 | DefKind::AssocFn
986 | DefKind::AssocConst
987 | DefKind::Macro(..)
988 | DefKind::Field => true,
989 DefKind::Use
990 | DefKind::ForeignMod
991 | DefKind::TyParam
992 | DefKind::ConstParam
993 | DefKind::LifetimeParam
994 | DefKind::AnonConst
995 | DefKind::InlineConst
996 | DefKind::Static { nested: true, .. }
997 | DefKind::OpaqueTy
998 | DefKind::GlobalAsm
999 | DefKind::Impl { .. }
1000 | DefKind::Closure
1001 | DefKind::ExternCrate
1002 | DefKind::SyntheticCoroutineBody => false,
1003 }
1004}
1005
1006fn should_encode_stability(def_kind: DefKind) -> bool {
1007 match def_kind {
1008 DefKind::Mod
1009 | DefKind::Ctor(..)
1010 | DefKind::Variant
1011 | DefKind::Field
1012 | DefKind::Struct
1013 | DefKind::AssocTy
1014 | DefKind::AssocFn
1015 | DefKind::AssocConst
1016 | DefKind::TyParam
1017 | DefKind::ConstParam
1018 | DefKind::Static { .. }
1019 | DefKind::Const
1020 | DefKind::Fn
1021 | DefKind::ForeignMod
1022 | DefKind::TyAlias
1023 | DefKind::OpaqueTy
1024 | DefKind::Enum
1025 | DefKind::Union
1026 | DefKind::Impl { .. }
1027 | DefKind::Trait
1028 | DefKind::TraitAlias
1029 | DefKind::Macro(..)
1030 | DefKind::ForeignTy => true,
1031 DefKind::Use
1032 | DefKind::LifetimeParam
1033 | DefKind::AnonConst
1034 | DefKind::InlineConst
1035 | DefKind::GlobalAsm
1036 | DefKind::Closure
1037 | DefKind::ExternCrate
1038 | DefKind::SyntheticCoroutineBody => false,
1039 }
1040}
1041
1042fn should_encode_mir(
1063 tcx: TyCtxt<'_>,
1064 reachable_set: &LocalDefIdSet,
1065 def_id: LocalDefId,
1066) -> (bool, bool) {
1067 match tcx.def_kind(def_id) {
1068 DefKind::Ctor(_, _) => {
1070 let mir_opt_base = tcx.sess.opts.output_types.should_codegen()
1071 || tcx.sess.opts.unstable_opts.always_encode_mir;
1072 (true, mir_opt_base)
1073 }
1074 DefKind::AnonConst | DefKind::InlineConst | DefKind::AssocConst | DefKind::Const => {
1076 (true, false)
1077 }
1078 DefKind::Closure if tcx.is_coroutine(def_id.to_def_id()) => (false, true),
1080 DefKind::SyntheticCoroutineBody => (false, true),
1081 DefKind::AssocFn | DefKind::Fn | DefKind::Closure => {
1083 let generics = tcx.generics_of(def_id);
1084 let opt = tcx.sess.opts.unstable_opts.always_encode_mir
1085 || (tcx.sess.opts.output_types.should_codegen()
1086 && reachable_set.contains(&def_id)
1087 && (generics.requires_monomorphization(tcx)
1088 || tcx.cross_crate_inlinable(def_id)));
1089 let is_const_fn = tcx.is_const_fn(def_id.to_def_id())
1091 || tcx.is_const_default_method(def_id.to_def_id());
1092 (is_const_fn, opt)
1093 }
1094 _ => (false, false),
1096 }
1097}
1098
1099fn should_encode_variances<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: DefKind) -> bool {
1100 match def_kind {
1101 DefKind::Struct
1102 | DefKind::Union
1103 | DefKind::Enum
1104 | DefKind::Variant
1105 | DefKind::OpaqueTy
1106 | DefKind::Fn
1107 | DefKind::Ctor(..)
1108 | DefKind::AssocFn => true,
1109 DefKind::AssocTy => {
1110 matches!(tcx.opt_rpitit_info(def_id), Some(ty::ImplTraitInTraitData::Trait { .. }))
1112 }
1113 DefKind::Mod
1114 | DefKind::Field
1115 | DefKind::AssocConst
1116 | DefKind::TyParam
1117 | DefKind::ConstParam
1118 | DefKind::Static { .. }
1119 | DefKind::Const
1120 | DefKind::ForeignMod
1121 | DefKind::Impl { .. }
1122 | DefKind::Trait
1123 | DefKind::TraitAlias
1124 | DefKind::Macro(..)
1125 | DefKind::ForeignTy
1126 | DefKind::Use
1127 | DefKind::LifetimeParam
1128 | DefKind::AnonConst
1129 | DefKind::InlineConst
1130 | DefKind::GlobalAsm
1131 | DefKind::Closure
1132 | DefKind::ExternCrate
1133 | DefKind::SyntheticCoroutineBody => false,
1134 DefKind::TyAlias => tcx.type_alias_is_lazy(def_id),
1135 }
1136}
1137
1138fn should_encode_generics(def_kind: DefKind) -> bool {
1139 match def_kind {
1140 DefKind::Struct
1141 | DefKind::Union
1142 | DefKind::Enum
1143 | DefKind::Variant
1144 | DefKind::Trait
1145 | DefKind::TyAlias
1146 | DefKind::ForeignTy
1147 | DefKind::TraitAlias
1148 | DefKind::AssocTy
1149 | DefKind::Fn
1150 | DefKind::Const
1151 | DefKind::Static { .. }
1152 | DefKind::Ctor(..)
1153 | DefKind::AssocFn
1154 | DefKind::AssocConst
1155 | DefKind::AnonConst
1156 | DefKind::InlineConst
1157 | DefKind::OpaqueTy
1158 | DefKind::Impl { .. }
1159 | DefKind::Field
1160 | DefKind::TyParam
1161 | DefKind::Closure
1162 | DefKind::SyntheticCoroutineBody => true,
1163 DefKind::Mod
1164 | DefKind::ForeignMod
1165 | DefKind::ConstParam
1166 | DefKind::Macro(..)
1167 | DefKind::Use
1168 | DefKind::LifetimeParam
1169 | DefKind::GlobalAsm
1170 | DefKind::ExternCrate => false,
1171 }
1172}
1173
1174fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> bool {
1175 match def_kind {
1176 DefKind::Struct
1177 | DefKind::Union
1178 | DefKind::Enum
1179 | DefKind::Variant
1180 | DefKind::Ctor(..)
1181 | DefKind::Field
1182 | DefKind::Fn
1183 | DefKind::Const
1184 | DefKind::Static { nested: false, .. }
1185 | DefKind::TyAlias
1186 | DefKind::ForeignTy
1187 | DefKind::Impl { .. }
1188 | DefKind::AssocFn
1189 | DefKind::AssocConst
1190 | DefKind::Closure
1191 | DefKind::ConstParam
1192 | DefKind::AnonConst
1193 | DefKind::InlineConst
1194 | DefKind::SyntheticCoroutineBody => true,
1195
1196 DefKind::OpaqueTy => {
1197 let origin = tcx.local_opaque_ty_origin(def_id);
1198 if let hir::OpaqueTyOrigin::FnReturn { parent, .. }
1199 | hir::OpaqueTyOrigin::AsyncFn { parent, .. } = origin
1200 && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(parent)
1201 && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
1202 {
1203 false
1204 } else {
1205 true
1206 }
1207 }
1208
1209 DefKind::AssocTy => {
1210 let assoc_item = tcx.associated_item(def_id);
1211 match assoc_item.container {
1212 ty::AssocItemContainer::Impl => true,
1213 ty::AssocItemContainer::Trait => assoc_item.defaultness(tcx).has_value(),
1214 }
1215 }
1216 DefKind::TyParam => {
1217 let hir::Node::GenericParam(param) = tcx.hir_node_by_def_id(def_id) else { bug!() };
1218 let hir::GenericParamKind::Type { default, .. } = param.kind else { bug!() };
1219 default.is_some()
1220 }
1221
1222 DefKind::Trait
1223 | DefKind::TraitAlias
1224 | DefKind::Mod
1225 | DefKind::ForeignMod
1226 | DefKind::Macro(..)
1227 | DefKind::Static { nested: true, .. }
1228 | DefKind::Use
1229 | DefKind::LifetimeParam
1230 | DefKind::GlobalAsm
1231 | DefKind::ExternCrate => false,
1232 }
1233}
1234
1235fn should_encode_fn_sig(def_kind: DefKind) -> bool {
1236 match def_kind {
1237 DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn) => true,
1238
1239 DefKind::Struct
1240 | DefKind::Union
1241 | DefKind::Enum
1242 | DefKind::Variant
1243 | DefKind::Field
1244 | DefKind::Const
1245 | DefKind::Static { .. }
1246 | DefKind::Ctor(..)
1247 | DefKind::TyAlias
1248 | DefKind::OpaqueTy
1249 | DefKind::ForeignTy
1250 | DefKind::Impl { .. }
1251 | DefKind::AssocConst
1252 | DefKind::Closure
1253 | DefKind::ConstParam
1254 | DefKind::AnonConst
1255 | DefKind::InlineConst
1256 | DefKind::AssocTy
1257 | DefKind::TyParam
1258 | DefKind::Trait
1259 | DefKind::TraitAlias
1260 | DefKind::Mod
1261 | DefKind::ForeignMod
1262 | DefKind::Macro(..)
1263 | DefKind::Use
1264 | DefKind::LifetimeParam
1265 | DefKind::GlobalAsm
1266 | DefKind::ExternCrate
1267 | DefKind::SyntheticCoroutineBody => false,
1268 }
1269}
1270
1271fn should_encode_constness(def_kind: DefKind) -> bool {
1272 match def_kind {
1273 DefKind::Fn | DefKind::AssocFn | DefKind::Closure | DefKind::Ctor(_, CtorKind::Fn) => true,
1274
1275 DefKind::Struct
1276 | DefKind::Union
1277 | DefKind::Enum
1278 | DefKind::Field
1279 | DefKind::Const
1280 | DefKind::AssocConst
1281 | DefKind::AnonConst
1282 | DefKind::Static { .. }
1283 | DefKind::TyAlias
1284 | DefKind::OpaqueTy
1285 | DefKind::Impl { .. }
1286 | DefKind::ForeignTy
1287 | DefKind::ConstParam
1288 | DefKind::InlineConst
1289 | DefKind::AssocTy
1290 | DefKind::TyParam
1291 | DefKind::Trait
1292 | DefKind::TraitAlias
1293 | DefKind::Mod
1294 | DefKind::ForeignMod
1295 | DefKind::Macro(..)
1296 | DefKind::Use
1297 | DefKind::LifetimeParam
1298 | DefKind::GlobalAsm
1299 | DefKind::ExternCrate
1300 | DefKind::Ctor(_, CtorKind::Const)
1301 | DefKind::Variant
1302 | DefKind::SyntheticCoroutineBody => false,
1303 }
1304}
1305
1306fn should_encode_const(def_kind: DefKind) -> bool {
1307 match def_kind {
1308 DefKind::Const | DefKind::AssocConst | DefKind::AnonConst | DefKind::InlineConst => true,
1309
1310 DefKind::Struct
1311 | DefKind::Union
1312 | DefKind::Enum
1313 | DefKind::Variant
1314 | DefKind::Ctor(..)
1315 | DefKind::Field
1316 | DefKind::Fn
1317 | DefKind::Static { .. }
1318 | DefKind::TyAlias
1319 | DefKind::OpaqueTy
1320 | DefKind::ForeignTy
1321 | DefKind::Impl { .. }
1322 | DefKind::AssocFn
1323 | DefKind::Closure
1324 | DefKind::ConstParam
1325 | DefKind::AssocTy
1326 | DefKind::TyParam
1327 | DefKind::Trait
1328 | DefKind::TraitAlias
1329 | DefKind::Mod
1330 | DefKind::ForeignMod
1331 | DefKind::Macro(..)
1332 | DefKind::Use
1333 | DefKind::LifetimeParam
1334 | DefKind::GlobalAsm
1335 | DefKind::ExternCrate
1336 | DefKind::SyntheticCoroutineBody => false,
1337 }
1338}
1339
1340fn should_encode_fn_impl_trait_in_trait<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
1341 if let Some(assoc_item) = tcx.opt_associated_item(def_id)
1342 && assoc_item.container == ty::AssocItemContainer::Trait
1343 && assoc_item.kind == ty::AssocKind::Fn
1344 {
1345 true
1346 } else {
1347 false
1348 }
1349}
1350
1351impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
1352 fn encode_attrs(&mut self, def_id: LocalDefId) {
1353 let tcx = self.tcx;
1354 let mut state = AnalyzeAttrState {
1355 is_exported: tcx.effective_visibilities(()).is_exported(def_id),
1356 is_doc_hidden: false,
1357 features: &tcx.features(),
1358 };
1359 let attr_iter = tcx
1360 .hir()
1361 .attrs(tcx.local_def_id_to_hir_id(def_id))
1362 .iter()
1363 .filter(|attr| analyze_attr(*attr, &mut state));
1364
1365 record_array!(self.tables.attributes[def_id.to_def_id()] <- attr_iter);
1366
1367 let mut attr_flags = AttrFlags::empty();
1368 if state.is_doc_hidden {
1369 attr_flags |= AttrFlags::IS_DOC_HIDDEN;
1370 }
1371 self.tables.attr_flags.set(def_id.local_def_index, attr_flags);
1372 }
1373
1374 fn encode_def_ids(&mut self) {
1375 self.encode_info_for_mod(CRATE_DEF_ID);
1376
1377 if self.is_proc_macro {
1380 return;
1381 }
1382
1383 let tcx = self.tcx;
1384
1385 for local_id in tcx.iter_local_def_id() {
1386 let def_id = local_id.to_def_id();
1387 let def_kind = tcx.def_kind(local_id);
1388 self.tables.def_kind.set_some(def_id.index, def_kind);
1389
1390 if def_kind == DefKind::AnonConst
1395 && match tcx.hir_node_by_def_id(local_id) {
1396 hir::Node::ConstArg(hir::ConstArg { kind, .. }) => match kind {
1397 hir::ConstArgKind::Path(..) | hir::ConstArgKind::Infer(..) => true,
1399 hir::ConstArgKind::Anon(..) => false,
1400 },
1401 _ => false,
1402 }
1403 {
1404 continue;
1405 }
1406
1407 if def_kind == DefKind::Field
1408 && let hir::Node::Field(field) = tcx.hir_node_by_def_id(local_id)
1409 && let Some(anon) = field.default
1410 {
1411 record!(self.tables.default_fields[def_id] <- anon.def_id.to_def_id());
1412 }
1413
1414 if should_encode_span(def_kind) {
1415 let def_span = tcx.def_span(local_id);
1416 record!(self.tables.def_span[def_id] <- def_span);
1417 }
1418 if should_encode_attrs(def_kind) {
1419 self.encode_attrs(local_id);
1420 }
1421 if should_encode_expn_that_defined(def_kind) {
1422 record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id));
1423 }
1424 if should_encode_span(def_kind)
1425 && let Some(ident_span) = tcx.def_ident_span(def_id)
1426 {
1427 record!(self.tables.def_ident_span[def_id] <- ident_span);
1428 }
1429 if def_kind.has_codegen_attrs() {
1430 record!(self.tables.codegen_fn_attrs[def_id] <- self.tcx.codegen_fn_attrs(def_id));
1431 }
1432 if should_encode_visibility(def_kind) {
1433 let vis =
1434 self.tcx.local_visibility(local_id).map_id(|def_id| def_id.local_def_index);
1435 record!(self.tables.visibility[def_id] <- vis);
1436 }
1437 if should_encode_stability(def_kind) {
1438 self.encode_stability(def_id);
1439 self.encode_const_stability(def_id);
1440 self.encode_default_body_stability(def_id);
1441 self.encode_deprecation(def_id);
1442 }
1443 if should_encode_variances(tcx, def_id, def_kind) {
1444 let v = self.tcx.variances_of(def_id);
1445 record_array!(self.tables.variances_of[def_id] <- v);
1446 }
1447 if should_encode_fn_sig(def_kind) {
1448 record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id));
1449 }
1450 if should_encode_generics(def_kind) {
1451 let g = tcx.generics_of(def_id);
1452 record!(self.tables.generics_of[def_id] <- g);
1453 record!(self.tables.explicit_predicates_of[def_id] <- self.tcx.explicit_predicates_of(def_id));
1454 let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
1455 record_defaulted_array!(self.tables.inferred_outlives_of[def_id] <- inferred_outlives);
1456
1457 for param in &g.own_params {
1458 if let ty::GenericParamDefKind::Const { has_default: true, .. } = param.kind {
1459 let default = self.tcx.const_param_default(param.def_id);
1460 record!(self.tables.const_param_default[param.def_id] <- default);
1461 }
1462 }
1463 }
1464 if tcx.is_conditionally_const(def_id) {
1465 record!(self.tables.const_conditions[def_id] <- self.tcx.const_conditions(def_id));
1466 }
1467 if should_encode_type(tcx, local_id, def_kind) {
1468 record!(self.tables.type_of[def_id] <- self.tcx.type_of(def_id));
1469 }
1470 if should_encode_constness(def_kind) {
1471 self.tables.constness.set_some(def_id.index, self.tcx.constness(def_id));
1472 }
1473 if let DefKind::Fn | DefKind::AssocFn = def_kind {
1474 self.tables.asyncness.set_some(def_id.index, tcx.asyncness(def_id));
1475 record_array!(self.tables.fn_arg_names[def_id] <- tcx.fn_arg_names(def_id));
1476 }
1477 if let Some(name) = tcx.intrinsic(def_id) {
1478 record!(self.tables.intrinsic[def_id] <- name);
1479 }
1480 if let DefKind::TyParam = def_kind {
1481 let default = self.tcx.object_lifetime_default(def_id);
1482 record!(self.tables.object_lifetime_default[def_id] <- default);
1483 }
1484 if let DefKind::Trait = def_kind {
1485 record!(self.tables.trait_def[def_id] <- self.tcx.trait_def(def_id));
1486 record_defaulted_array!(self.tables.explicit_super_predicates_of[def_id] <-
1487 self.tcx.explicit_super_predicates_of(def_id).skip_binder());
1488 record_defaulted_array!(self.tables.explicit_implied_predicates_of[def_id] <-
1489 self.tcx.explicit_implied_predicates_of(def_id).skip_binder());
1490 let module_children = self.tcx.module_children_local(local_id);
1491 record_array!(self.tables.module_children_non_reexports[def_id] <-
1492 module_children.iter().map(|child| child.res.def_id().index));
1493 if self.tcx.is_const_trait(def_id) {
1494 record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1495 <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1496 }
1497 }
1498 if let DefKind::TraitAlias = def_kind {
1499 record!(self.tables.trait_def[def_id] <- self.tcx.trait_def(def_id));
1500 record_defaulted_array!(self.tables.explicit_super_predicates_of[def_id] <-
1501 self.tcx.explicit_super_predicates_of(def_id).skip_binder());
1502 record_defaulted_array!(self.tables.explicit_implied_predicates_of[def_id] <-
1503 self.tcx.explicit_implied_predicates_of(def_id).skip_binder());
1504 }
1505 if let DefKind::Trait | DefKind::Impl { .. } = def_kind {
1506 let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id);
1507 record_array!(self.tables.associated_item_or_field_def_ids[def_id] <-
1508 associated_item_def_ids.iter().map(|&def_id| {
1509 assert!(def_id.is_local());
1510 def_id.index
1511 })
1512 );
1513 for &def_id in associated_item_def_ids {
1514 self.encode_info_for_assoc_item(def_id);
1515 }
1516 }
1517 if let DefKind::Closure | DefKind::SyntheticCoroutineBody = def_kind
1518 && let Some(coroutine_kind) = self.tcx.coroutine_kind(def_id)
1519 {
1520 self.tables.coroutine_kind.set(def_id.index, Some(coroutine_kind))
1521 }
1522 if def_kind == DefKind::Closure
1523 && tcx.type_of(def_id).skip_binder().is_coroutine_closure()
1524 {
1525 let coroutine_for_closure = self.tcx.coroutine_for_closure(def_id);
1526 self.tables
1527 .coroutine_for_closure
1528 .set_some(def_id.index, coroutine_for_closure.into());
1529
1530 if tcx.needs_coroutine_by_move_body_def_id(coroutine_for_closure) {
1532 self.tables.coroutine_by_move_body_def_id.set_some(
1533 coroutine_for_closure.index,
1534 self.tcx.coroutine_by_move_body_def_id(coroutine_for_closure).into(),
1535 );
1536 }
1537 }
1538 if let DefKind::Static { .. } = def_kind {
1539 if !self.tcx.is_foreign_item(def_id) {
1540 let data = self.tcx.eval_static_initializer(def_id).unwrap();
1541 record!(self.tables.eval_static_initializer[def_id] <- data);
1542 }
1543 }
1544 if let DefKind::Enum | DefKind::Struct | DefKind::Union = def_kind {
1545 self.encode_info_for_adt(local_id);
1546 }
1547 if let DefKind::Mod = def_kind {
1548 self.encode_info_for_mod(local_id);
1549 }
1550 if let DefKind::Macro(_) = def_kind {
1551 self.encode_info_for_macro(local_id);
1552 }
1553 if let DefKind::TyAlias = def_kind {
1554 self.tables
1555 .type_alias_is_lazy
1556 .set(def_id.index, self.tcx.type_alias_is_lazy(def_id));
1557 }
1558 if let DefKind::OpaqueTy = def_kind {
1559 self.encode_explicit_item_bounds(def_id);
1560 self.encode_explicit_item_self_bounds(def_id);
1561 record!(self.tables.opaque_ty_origin[def_id] <- self.tcx.opaque_ty_origin(def_id));
1562 self.encode_precise_capturing_args(def_id);
1563 if tcx.is_conditionally_const(def_id) {
1564 record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1565 <- tcx.explicit_implied_const_bounds(def_id).skip_binder());
1566 }
1567 }
1568 if tcx.impl_method_has_trait_impl_trait_tys(def_id)
1569 && let Ok(table) = self.tcx.collect_return_position_impl_trait_in_trait_tys(def_id)
1570 {
1571 record!(self.tables.trait_impl_trait_tys[def_id] <- table);
1572 }
1573 if should_encode_fn_impl_trait_in_trait(tcx, def_id) {
1574 let table = tcx.associated_types_for_impl_traits_in_associated_fn(def_id);
1575 record_defaulted_array!(self.tables.associated_types_for_impl_traits_in_associated_fn[def_id] <- table);
1576 }
1577 }
1578
1579 for (def_id, impls) in &tcx.crate_inherent_impls(()).0.inherent_impls {
1580 record_defaulted_array!(self.tables.inherent_impls[def_id.to_def_id()] <- impls.iter().map(|def_id| {
1581 assert!(def_id.is_local());
1582 def_id.index
1583 }));
1584 }
1585
1586 for (def_id, res_map) in &tcx.resolutions(()).doc_link_resolutions {
1587 record!(self.tables.doc_link_resolutions[def_id.to_def_id()] <- res_map);
1588 }
1589
1590 for (def_id, traits) in &tcx.resolutions(()).doc_link_traits_in_scope {
1591 record_array!(self.tables.doc_link_traits_in_scope[def_id.to_def_id()] <- traits);
1592 }
1593 }
1594
1595 #[instrument(level = "trace", skip(self))]
1596 fn encode_info_for_adt(&mut self, local_def_id: LocalDefId) {
1597 let def_id = local_def_id.to_def_id();
1598 let tcx = self.tcx;
1599 let adt_def = tcx.adt_def(def_id);
1600 record!(self.tables.repr_options[def_id] <- adt_def.repr());
1601
1602 let params_in_repr = self.tcx.params_in_repr(def_id);
1603 record!(self.tables.params_in_repr[def_id] <- params_in_repr);
1604
1605 if adt_def.is_enum() {
1606 let module_children = tcx.module_children_local(local_def_id);
1607 record_array!(self.tables.module_children_non_reexports[def_id] <-
1608 module_children.iter().map(|child| child.res.def_id().index));
1609 } else {
1610 debug_assert_eq!(adt_def.variants().len(), 1);
1612 debug_assert_eq!(adt_def.non_enum_variant().def_id, def_id);
1613 }
1615
1616 for (idx, variant) in adt_def.variants().iter_enumerated() {
1617 let data = VariantData {
1618 discr: variant.discr,
1619 idx,
1620 ctor: variant.ctor.map(|(kind, def_id)| (kind, def_id.index)),
1621 is_non_exhaustive: variant.is_field_list_non_exhaustive(),
1622 };
1623 record!(self.tables.variant_data[variant.def_id] <- data);
1624
1625 record_array!(self.tables.associated_item_or_field_def_ids[variant.def_id] <- variant.fields.iter().map(|f| {
1626 assert!(f.did.is_local());
1627 f.did.index
1628 }));
1629
1630 for field in &variant.fields {
1631 self.tables.safety.set_some(field.did.index, field.safety);
1632 }
1633
1634 if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
1635 let fn_sig = tcx.fn_sig(ctor_def_id);
1636 record!(self.tables.fn_sig[variant.def_id] <- fn_sig);
1638 }
1639 }
1640 }
1641
1642 #[instrument(level = "debug", skip(self))]
1643 fn encode_info_for_mod(&mut self, local_def_id: LocalDefId) {
1644 let tcx = self.tcx;
1645 let def_id = local_def_id.to_def_id();
1646
1647 if self.is_proc_macro {
1653 record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id));
1655 } else {
1656 let module_children = tcx.module_children_local(local_def_id);
1657
1658 record_array!(self.tables.module_children_non_reexports[def_id] <-
1659 module_children.iter().filter(|child| child.reexport_chain.is_empty())
1660 .map(|child| child.res.def_id().index));
1661
1662 record_defaulted_array!(self.tables.module_children_reexports[def_id] <-
1663 module_children.iter().filter(|child| !child.reexport_chain.is_empty()));
1664 }
1665 }
1666
1667 fn encode_explicit_item_bounds(&mut self, def_id: DefId) {
1668 debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id);
1669 let bounds = self.tcx.explicit_item_bounds(def_id).skip_binder();
1670 record_defaulted_array!(self.tables.explicit_item_bounds[def_id] <- bounds);
1671 }
1672
1673 fn encode_explicit_item_self_bounds(&mut self, def_id: DefId) {
1674 debug!("EncodeContext::encode_explicit_item_self_bounds({:?})", def_id);
1675 let bounds = self.tcx.explicit_item_self_bounds(def_id).skip_binder();
1676 record_defaulted_array!(self.tables.explicit_item_self_bounds[def_id] <- bounds);
1677 }
1678
1679 #[instrument(level = "debug", skip(self))]
1680 fn encode_info_for_assoc_item(&mut self, def_id: DefId) {
1681 let tcx = self.tcx;
1682 let item = tcx.associated_item(def_id);
1683
1684 self.tables.defaultness.set_some(def_id.index, item.defaultness(tcx));
1685 self.tables.assoc_container.set_some(def_id.index, item.container);
1686
1687 match item.container {
1688 AssocItemContainer::Trait => {
1689 if let ty::AssocKind::Type = item.kind {
1690 self.encode_explicit_item_bounds(def_id);
1691 self.encode_explicit_item_self_bounds(def_id);
1692 if tcx.is_conditionally_const(def_id) {
1693 record_defaulted_array!(self.tables.explicit_implied_const_bounds[def_id]
1694 <- self.tcx.explicit_implied_const_bounds(def_id).skip_binder());
1695 }
1696 }
1697 }
1698 AssocItemContainer::Impl => {
1699 if let Some(trait_item_def_id) = item.trait_item_def_id {
1700 self.tables.trait_item_def_id.set_some(def_id.index, trait_item_def_id.into());
1701 }
1702 }
1703 }
1704 if let Some(rpitit_info) = item.opt_rpitit_info {
1705 record!(self.tables.opt_rpitit_info[def_id] <- rpitit_info);
1706 if matches!(rpitit_info, ty::ImplTraitInTraitData::Trait { .. }) {
1707 record_array!(
1708 self.tables.assumed_wf_types_for_rpitit[def_id]
1709 <- self.tcx.assumed_wf_types_for_rpitit(def_id)
1710 );
1711 self.encode_precise_capturing_args(def_id);
1712 }
1713 }
1714 }
1715
1716 fn encode_precise_capturing_args(&mut self, def_id: DefId) {
1717 let Some(precise_capturing_args) = self.tcx.rendered_precise_capturing_args(def_id) else {
1718 return;
1719 };
1720
1721 record_array!(self.tables.rendered_precise_capturing_args[def_id] <- precise_capturing_args);
1722 }
1723
1724 fn encode_mir(&mut self) {
1725 if self.is_proc_macro {
1726 return;
1727 }
1728
1729 let tcx = self.tcx;
1730 let reachable_set = tcx.reachable_set(());
1731
1732 let keys_and_jobs = tcx.mir_keys(()).iter().filter_map(|&def_id| {
1733 let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
1734 if encode_const || encode_opt { Some((def_id, encode_const, encode_opt)) } else { None }
1735 });
1736 for (def_id, encode_const, encode_opt) in keys_and_jobs {
1737 debug_assert!(encode_const || encode_opt);
1738
1739 debug!("EntryBuilder::encode_mir({:?})", def_id);
1740 if encode_opt {
1741 record!(self.tables.optimized_mir[def_id.to_def_id()] <- tcx.optimized_mir(def_id));
1742 self.tables
1743 .cross_crate_inlinable
1744 .set(def_id.to_def_id().index, self.tcx.cross_crate_inlinable(def_id));
1745 record!(self.tables.closure_saved_names_of_captured_variables[def_id.to_def_id()]
1746 <- tcx.closure_saved_names_of_captured_variables(def_id));
1747
1748 if self.tcx.is_coroutine(def_id.to_def_id())
1749 && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1750 {
1751 record!(self.tables.mir_coroutine_witnesses[def_id.to_def_id()] <- witnesses);
1752 }
1753 }
1754 if encode_const {
1755 record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- tcx.mir_for_ctfe(def_id));
1756
1757 let abstract_const = tcx.thir_abstract_const(def_id);
1759 if let Ok(Some(abstract_const)) = abstract_const {
1760 record!(self.tables.thir_abstract_const[def_id.to_def_id()] <- abstract_const);
1761 }
1762
1763 if should_encode_const(tcx.def_kind(def_id)) {
1764 let qualifs = tcx.mir_const_qualif(def_id);
1765 record!(self.tables.mir_const_qualif[def_id.to_def_id()] <- qualifs);
1766 let body = tcx.hir().maybe_body_owned_by(def_id);
1767 if let Some(body) = body {
1768 let const_data = rendered_const(self.tcx, &body, def_id);
1769 record!(self.tables.rendered_const[def_id.to_def_id()] <- const_data);
1770 }
1771 }
1772 }
1773 record!(self.tables.promoted_mir[def_id.to_def_id()] <- tcx.promoted_mir(def_id));
1774
1775 if self.tcx.is_coroutine(def_id.to_def_id())
1776 && let Some(witnesses) = tcx.mir_coroutine_witnesses(def_id)
1777 {
1778 record!(self.tables.mir_coroutine_witnesses[def_id.to_def_id()] <- witnesses);
1779 }
1780 }
1781
1782 if tcx.sess.opts.output_types.should_codegen()
1786 && tcx.sess.opts.optimize != OptLevel::No
1787 && tcx.sess.opts.incremental.is_none()
1788 {
1789 for &local_def_id in tcx.mir_keys(()) {
1790 if let DefKind::AssocFn | DefKind::Fn = tcx.def_kind(local_def_id) {
1791 record_array!(self.tables.deduced_param_attrs[local_def_id.to_def_id()] <-
1792 self.tcx.deduced_param_attrs(local_def_id.to_def_id()));
1793 }
1794 }
1795 }
1796 }
1797
1798 #[instrument(level = "debug", skip(self))]
1799 fn encode_stability(&mut self, def_id: DefId) {
1800 if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1803 if let Some(stab) = self.tcx.lookup_stability(def_id) {
1804 record!(self.tables.lookup_stability[def_id] <- stab)
1805 }
1806 }
1807 }
1808
1809 #[instrument(level = "debug", skip(self))]
1810 fn encode_const_stability(&mut self, def_id: DefId) {
1811 if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1814 if let Some(stab) = self.tcx.lookup_const_stability(def_id) {
1815 record!(self.tables.lookup_const_stability[def_id] <- stab)
1816 }
1817 }
1818 }
1819
1820 #[instrument(level = "debug", skip(self))]
1821 fn encode_default_body_stability(&mut self, def_id: DefId) {
1822 if self.feat.staged_api() || self.tcx.sess.opts.unstable_opts.force_unstable_if_unmarked {
1825 if let Some(stab) = self.tcx.lookup_default_body_stability(def_id) {
1826 record!(self.tables.lookup_default_body_stability[def_id] <- stab)
1827 }
1828 }
1829 }
1830
1831 #[instrument(level = "debug", skip(self))]
1832 fn encode_deprecation(&mut self, def_id: DefId) {
1833 if let Some(depr) = self.tcx.lookup_deprecation(def_id) {
1834 record!(self.tables.lookup_deprecation_entry[def_id] <- depr);
1835 }
1836 }
1837
1838 #[instrument(level = "debug", skip(self))]
1839 fn encode_info_for_macro(&mut self, def_id: LocalDefId) {
1840 let tcx = self.tcx;
1841
1842 let hir::ItemKind::Macro(macro_def, _) = tcx.hir().expect_item(def_id).kind else { bug!() };
1843 self.tables.is_macro_rules.set(def_id.local_def_index, macro_def.macro_rules);
1844 record!(self.tables.macro_definition[def_id.to_def_id()] <- &*macro_def.body);
1845 }
1846
1847 fn encode_native_libraries(&mut self) -> LazyArray<NativeLib> {
1848 empty_proc_macro!(self);
1849 let used_libraries = self.tcx.native_libraries(LOCAL_CRATE);
1850 self.lazy_array(used_libraries.iter())
1851 }
1852
1853 fn encode_foreign_modules(&mut self) -> LazyArray<ForeignModule> {
1854 empty_proc_macro!(self);
1855 let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE);
1856 self.lazy_array(foreign_modules.iter().map(|(_, m)| m).cloned())
1857 }
1858
1859 fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) {
1860 let mut syntax_contexts: TableBuilder<_, _> = Default::default();
1861 let mut expn_data_table: TableBuilder<_, _> = Default::default();
1862 let mut expn_hash_table: TableBuilder<_, _> = Default::default();
1863
1864 self.hygiene_ctxt.encode(
1865 &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table),
1866 |(this, syntax_contexts, _, _), index, ctxt_data| {
1867 syntax_contexts.set_some(index, this.lazy(ctxt_data));
1868 },
1869 |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| {
1870 if let Some(index) = index.as_local() {
1871 expn_data_table.set_some(index.as_raw(), this.lazy(expn_data));
1872 expn_hash_table.set_some(index.as_raw(), this.lazy(hash));
1873 }
1874 },
1875 );
1876
1877 (
1878 syntax_contexts.encode(&mut self.opaque),
1879 expn_data_table.encode(&mut self.opaque),
1880 expn_hash_table.encode(&mut self.opaque),
1881 )
1882 }
1883
1884 fn encode_proc_macros(&mut self) -> Option<ProcMacroData> {
1885 let is_proc_macro = self.tcx.crate_types().contains(&CrateType::ProcMacro);
1886 if is_proc_macro {
1887 let tcx = self.tcx;
1888 let hir = tcx.hir();
1889
1890 let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index;
1891 let stability = tcx.lookup_stability(CRATE_DEF_ID);
1892 let macros =
1893 self.lazy_array(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index));
1894 for (i, span) in self.tcx.sess.psess.proc_macro_quoted_spans() {
1895 let span = self.lazy(span);
1896 self.tables.proc_macro_quoted_spans.set_some(i, span);
1897 }
1898
1899 self.tables.def_kind.set_some(LOCAL_CRATE.as_def_id().index, DefKind::Mod);
1900 record!(self.tables.def_span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id()));
1901 self.encode_attrs(LOCAL_CRATE.as_def_id().expect_local());
1902 let vis = tcx.local_visibility(CRATE_DEF_ID).map_id(|def_id| def_id.local_def_index);
1903 record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- vis);
1904 if let Some(stability) = stability {
1905 record!(self.tables.lookup_stability[LOCAL_CRATE.as_def_id()] <- stability);
1906 }
1907 self.encode_deprecation(LOCAL_CRATE.as_def_id());
1908 if let Some(res_map) = tcx.resolutions(()).doc_link_resolutions.get(&CRATE_DEF_ID) {
1909 record!(self.tables.doc_link_resolutions[LOCAL_CRATE.as_def_id()] <- res_map);
1910 }
1911 if let Some(traits) = tcx.resolutions(()).doc_link_traits_in_scope.get(&CRATE_DEF_ID) {
1912 record_array!(self.tables.doc_link_traits_in_scope[LOCAL_CRATE.as_def_id()] <- traits);
1913 }
1914
1915 for &proc_macro in &tcx.resolutions(()).proc_macros {
1919 let id = proc_macro;
1920 let proc_macro = tcx.local_def_id_to_hir_id(proc_macro);
1921 let mut name = hir.name(proc_macro);
1922 let span = hir.span(proc_macro);
1923 let attrs = hir.attrs(proc_macro);
1926 let macro_kind = if ast::attr::contains_name(attrs, sym::proc_macro) {
1927 MacroKind::Bang
1928 } else if ast::attr::contains_name(attrs, sym::proc_macro_attribute) {
1929 MacroKind::Attr
1930 } else if let Some(attr) = ast::attr::find_by_name(attrs, sym::proc_macro_derive) {
1931 name = attr.meta_item_list().unwrap()[0]
1933 .meta_item()
1934 .unwrap()
1935 .ident()
1936 .unwrap()
1937 .name;
1938 MacroKind::Derive
1939 } else {
1940 bug!("Unknown proc-macro type for item {:?}", id);
1941 };
1942
1943 let mut def_key = self.tcx.hir().def_key(id);
1944 def_key.disambiguated_data.data = DefPathData::MacroNs(name);
1945
1946 let def_id = id.to_def_id();
1947 self.tables.def_kind.set_some(def_id.index, DefKind::Macro(macro_kind));
1948 self.tables.proc_macro.set_some(def_id.index, macro_kind);
1949 self.encode_attrs(id);
1950 record!(self.tables.def_keys[def_id] <- def_key);
1951 record!(self.tables.def_ident_span[def_id] <- span);
1952 record!(self.tables.def_span[def_id] <- span);
1953 record!(self.tables.visibility[def_id] <- ty::Visibility::Public);
1954 if let Some(stability) = stability {
1955 record!(self.tables.lookup_stability[def_id] <- stability);
1956 }
1957 }
1958
1959 Some(ProcMacroData { proc_macro_decls_static, stability, macros })
1960 } else {
1961 None
1962 }
1963 }
1964
1965 fn encode_debugger_visualizers(&mut self) -> LazyArray<DebuggerVisualizerFile> {
1966 empty_proc_macro!(self);
1967 self.lazy_array(
1968 self.tcx
1969 .debugger_visualizers(LOCAL_CRATE)
1970 .iter()
1971 .map(DebuggerVisualizerFile::path_erased),
1976 )
1977 }
1978
1979 fn encode_crate_deps(&mut self) -> LazyArray<CrateDep> {
1980 empty_proc_macro!(self);
1981
1982 let deps = self
1983 .tcx
1984 .crates(())
1985 .iter()
1986 .map(|&cnum| {
1987 let dep = CrateDep {
1988 name: self.tcx.crate_name(cnum),
1989 hash: self.tcx.crate_hash(cnum),
1990 host_hash: self.tcx.crate_host_hash(cnum),
1991 kind: self.tcx.dep_kind(cnum),
1992 extra_filename: self.tcx.extra_filename(cnum).clone(),
1993 is_private: self.tcx.is_private_dep(cnum),
1994 };
1995 (cnum, dep)
1996 })
1997 .collect::<Vec<_>>();
1998
1999 {
2000 let mut expected_cnum = 1;
2002 for &(n, _) in &deps {
2003 assert_eq!(n, CrateNum::new(expected_cnum));
2004 expected_cnum += 1;
2005 }
2006 }
2007
2008 self.lazy_array(deps.iter().map(|(_, dep)| dep))
2013 }
2014
2015 fn encode_target_modifiers(&mut self) -> LazyArray<TargetModifier> {
2016 empty_proc_macro!(self);
2017 let tcx = self.tcx;
2018 self.lazy_array(tcx.sess.opts.gather_target_modifiers())
2019 }
2020
2021 fn encode_lib_features(&mut self) -> LazyArray<(Symbol, FeatureStability)> {
2022 empty_proc_macro!(self);
2023 let tcx = self.tcx;
2024 let lib_features = tcx.lib_features(LOCAL_CRATE);
2025 self.lazy_array(lib_features.to_sorted_vec())
2026 }
2027
2028 fn encode_stability_implications(&mut self) -> LazyArray<(Symbol, Symbol)> {
2029 empty_proc_macro!(self);
2030 let tcx = self.tcx;
2031 let implications = tcx.stability_implications(LOCAL_CRATE);
2032 let sorted = implications.to_sorted_stable_ord();
2033 self.lazy_array(sorted.into_iter().map(|(k, v)| (*k, *v)))
2034 }
2035
2036 fn encode_diagnostic_items(&mut self) -> LazyArray<(Symbol, DefIndex)> {
2037 empty_proc_macro!(self);
2038 let tcx = self.tcx;
2039 let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id;
2040 self.lazy_array(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index)))
2041 }
2042
2043 fn encode_lang_items(&mut self) -> LazyArray<(DefIndex, LangItem)> {
2044 empty_proc_macro!(self);
2045 let lang_items = self.tcx.lang_items().iter();
2046 self.lazy_array(lang_items.filter_map(|(lang_item, def_id)| {
2047 def_id.as_local().map(|id| (id.local_def_index, lang_item))
2048 }))
2049 }
2050
2051 fn encode_lang_items_missing(&mut self) -> LazyArray<LangItem> {
2052 empty_proc_macro!(self);
2053 let tcx = self.tcx;
2054 self.lazy_array(&tcx.lang_items().missing)
2055 }
2056
2057 fn encode_stripped_cfg_items(&mut self) -> LazyArray<StrippedCfgItem<DefIndex>> {
2058 self.lazy_array(
2059 self.tcx
2060 .stripped_cfg_items(LOCAL_CRATE)
2061 .into_iter()
2062 .map(|item| item.clone().map_mod_id(|def_id| def_id.index)),
2063 )
2064 }
2065
2066 fn encode_traits(&mut self) -> LazyArray<DefIndex> {
2067 empty_proc_macro!(self);
2068 self.lazy_array(self.tcx.traits(LOCAL_CRATE).iter().map(|def_id| def_id.index))
2069 }
2070
2071 #[instrument(level = "debug", skip(self))]
2073 fn encode_impls(&mut self) -> LazyArray<TraitImpls> {
2074 empty_proc_macro!(self);
2075 let tcx = self.tcx;
2076 let mut trait_impls: FxIndexMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
2077 FxIndexMap::default();
2078
2079 for id in tcx.hir().items() {
2080 let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else {
2081 continue;
2082 };
2083 let def_id = id.owner_id.to_def_id();
2084
2085 self.tables.defaultness.set_some(def_id.index, tcx.defaultness(def_id));
2086
2087 if of_trait && let Some(header) = tcx.impl_trait_header(def_id) {
2088 record!(self.tables.impl_trait_header[def_id] <- header);
2089
2090 let trait_ref = header.trait_ref.instantiate_identity();
2091 let simplified_self_ty = fast_reject::simplify_type(
2092 self.tcx,
2093 trait_ref.self_ty(),
2094 TreatParams::InstantiateWithInfer,
2095 );
2096 trait_impls
2097 .entry(trait_ref.def_id)
2098 .or_default()
2099 .push((id.owner_id.def_id.local_def_index, simplified_self_ty));
2100
2101 let trait_def = tcx.trait_def(trait_ref.def_id);
2102 if let Ok(mut an) = trait_def.ancestors(tcx, def_id) {
2103 if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) {
2104 self.tables.impl_parent.set_some(def_id.index, parent.into());
2105 }
2106 }
2107
2108 if tcx.is_lang_item(trait_ref.def_id, LangItem::CoerceUnsized) {
2111 let coerce_unsized_info = tcx.coerce_unsized_info(def_id).unwrap();
2112 record!(self.tables.coerce_unsized_info[def_id] <- coerce_unsized_info);
2113 }
2114 }
2115 }
2116
2117 let trait_impls: Vec<_> = trait_impls
2118 .into_iter()
2119 .map(|(trait_def_id, impls)| TraitImpls {
2120 trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
2121 impls: self.lazy_array(&impls),
2122 })
2123 .collect();
2124
2125 self.lazy_array(&trait_impls)
2126 }
2127
2128 #[instrument(level = "debug", skip(self))]
2129 fn encode_incoherent_impls(&mut self) -> LazyArray<IncoherentImpls> {
2130 empty_proc_macro!(self);
2131 let tcx = self.tcx;
2132
2133 let all_impls: Vec<_> = tcx
2134 .crate_inherent_impls(())
2135 .0
2136 .incoherent_impls
2137 .iter()
2138 .map(|(&simp, impls)| IncoherentImpls {
2139 self_ty: simp,
2140 impls: self.lazy_array(impls.iter().map(|def_id| def_id.local_def_index)),
2141 })
2142 .collect();
2143
2144 self.lazy_array(&all_impls)
2145 }
2146
2147 fn encode_exported_symbols(
2154 &mut self,
2155 exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportInfo)],
2156 ) -> LazyArray<(ExportedSymbol<'static>, SymbolExportInfo)> {
2157 empty_proc_macro!(self);
2158 let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx));
2161
2162 self.lazy_array(
2163 exported_symbols
2164 .iter()
2165 .filter(|&(exported_symbol, _)| match *exported_symbol {
2166 ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name,
2167 _ => true,
2168 })
2169 .cloned(),
2170 )
2171 }
2172
2173 fn encode_dylib_dependency_formats(&mut self) -> LazyArray<Option<LinkagePreference>> {
2174 empty_proc_macro!(self);
2175 let formats = self.tcx.dependency_formats(());
2176 if let Some(arr) = formats.get(&CrateType::Dylib) {
2177 return self.lazy_array(arr.iter().skip(1 ).map(
2178 |slot| match *slot {
2179 Linkage::NotLinked | Linkage::IncludedFromDylib => None,
2180
2181 Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
2182 Linkage::Static => Some(LinkagePreference::RequireStatic),
2183 },
2184 ));
2185 }
2186 LazyArray::default()
2187 }
2188}
2189
2190fn prefetch_mir(tcx: TyCtxt<'_>) {
2193 if !tcx.sess.opts.output_types.should_codegen() {
2194 return;
2196 }
2197
2198 let reachable_set = tcx.reachable_set(());
2199 par_for_each_in(tcx.mir_keys(()), |&def_id| {
2200 let (encode_const, encode_opt) = should_encode_mir(tcx, reachable_set, def_id);
2201
2202 if encode_const {
2203 tcx.ensure_done().mir_for_ctfe(def_id);
2204 }
2205 if encode_opt {
2206 tcx.ensure_done().optimized_mir(def_id);
2207 }
2208 if encode_opt || encode_const {
2209 tcx.ensure_done().promoted_mir(def_id);
2210 }
2211 })
2212}
2213
2214pub struct EncodedMetadata {
2238 mmap: Option<Mmap>,
2240 _temp_dir: Option<MaybeTempDir>,
2243}
2244
2245impl EncodedMetadata {
2246 #[inline]
2247 pub fn from_path(path: PathBuf, temp_dir: Option<MaybeTempDir>) -> std::io::Result<Self> {
2248 let file = std::fs::File::open(&path)?;
2249 let file_metadata = file.metadata()?;
2250 if file_metadata.len() == 0 {
2251 return Ok(Self { mmap: None, _temp_dir: None });
2252 }
2253 let mmap = unsafe { Some(Mmap::map(file)?) };
2254 Ok(Self { mmap, _temp_dir: temp_dir })
2255 }
2256
2257 #[inline]
2258 pub fn raw_data(&self) -> &[u8] {
2259 self.mmap.as_deref().unwrap_or_default()
2260 }
2261}
2262
2263impl<S: Encoder> Encodable<S> for EncodedMetadata {
2264 fn encode(&self, s: &mut S) {
2265 let slice = self.raw_data();
2266 slice.encode(s)
2267 }
2268}
2269
2270impl<D: Decoder> Decodable<D> for EncodedMetadata {
2271 fn decode(d: &mut D) -> Self {
2272 let len = d.read_usize();
2273 let mmap = if len > 0 {
2274 let mut mmap = MmapMut::map_anon(len).unwrap();
2275 mmap.copy_from_slice(d.read_raw_bytes(len));
2276 Some(mmap.make_read_only().unwrap())
2277 } else {
2278 None
2279 };
2280
2281 Self { mmap, _temp_dir: None }
2282 }
2283}
2284
2285pub fn encode_metadata(tcx: TyCtxt<'_>, path: &Path) {
2286 let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata");
2287
2288 tcx.dep_graph.assert_ignored();
2291
2292 if tcx.sess.threads() != 1 {
2293 join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE));
2297 }
2298
2299 let mut encoder = opaque::FileEncoder::new(path)
2300 .unwrap_or_else(|err| tcx.dcx().emit_fatal(FailCreateFileEncoder { err }));
2301 encoder.emit_raw_bytes(METADATA_HEADER);
2302
2303 encoder.emit_raw_bytes(&0u64.to_le_bytes());
2305
2306 let source_map_files = tcx.sess.source_map().files();
2307 let source_file_cache = (Arc::clone(&source_map_files[0]), 0);
2308 let required_source_files = Some(FxIndexSet::default());
2309 drop(source_map_files);
2310
2311 let hygiene_ctxt = HygieneEncodeContext::default();
2312
2313 let mut ecx = EncodeContext {
2314 opaque: encoder,
2315 tcx,
2316 feat: tcx.features(),
2317 tables: Default::default(),
2318 lazy_state: LazyState::NoNode,
2319 span_shorthands: Default::default(),
2320 type_shorthands: Default::default(),
2321 predicate_shorthands: Default::default(),
2322 source_file_cache,
2323 interpret_allocs: Default::default(),
2324 required_source_files,
2325 is_proc_macro: tcx.crate_types().contains(&CrateType::ProcMacro),
2326 hygiene_ctxt: &hygiene_ctxt,
2327 symbol_table: Default::default(),
2328 };
2329
2330 rustc_version(tcx.sess.cfg_version).encode(&mut ecx);
2332
2333 let root = ecx.encode_crate_root();
2336
2337 if let Err((path, err)) = ecx.opaque.finish() {
2341 tcx.dcx().emit_fatal(FailWriteFile { path: &path, err });
2342 }
2343
2344 let file = ecx.opaque.file();
2345 if let Err(err) = encode_root_position(file, root.position.get()) {
2346 tcx.dcx().emit_fatal(FailWriteFile { path: ecx.opaque.path(), err });
2347 }
2348
2349 tcx.prof.artifact_size("crate_metadata", "crate_metadata", file.metadata().unwrap().len());
2351}
2352
2353fn encode_root_position(mut file: &File, pos: usize) -> Result<(), std::io::Error> {
2354 let pos_before_seek = file.stream_position().unwrap();
2356
2357 let header = METADATA_HEADER.len();
2359 file.seek(std::io::SeekFrom::Start(header as u64))?;
2360 file.write_all(&pos.to_le_bytes())?;
2361
2362 file.seek(std::io::SeekFrom::Start(pos_before_seek))?;
2364 Ok(())
2365}
2366
2367pub(crate) fn provide(providers: &mut Providers) {
2368 *providers = Providers {
2369 doc_link_resolutions: |tcx, def_id| {
2370 tcx.resolutions(())
2371 .doc_link_resolutions
2372 .get(&def_id)
2373 .unwrap_or_else(|| span_bug!(tcx.def_span(def_id), "no resolutions for a doc link"))
2374 },
2375 doc_link_traits_in_scope: |tcx, def_id| {
2376 tcx.resolutions(()).doc_link_traits_in_scope.get(&def_id).unwrap_or_else(|| {
2377 span_bug!(tcx.def_span(def_id), "no traits in scope for a doc link")
2378 })
2379 },
2380
2381 ..*providers
2382 }
2383}
2384
2385pub fn rendered_const<'tcx>(tcx: TyCtxt<'tcx>, body: &hir::Body<'_>, def_id: LocalDefId) -> String {
2413 let hir = tcx.hir();
2414 let value = body.value;
2415
2416 #[derive(PartialEq, Eq)]
2417 enum Classification {
2418 Literal,
2419 Simple,
2420 Complex,
2421 }
2422
2423 use Classification::*;
2424
2425 fn classify(expr: &hir::Expr<'_>) -> Classification {
2426 match &expr.kind {
2427 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => {
2428 if matches!(expr.kind, hir::ExprKind::Lit(_)) { Literal } else { Complex }
2429 }
2430 hir::ExprKind::Lit(_) => Literal,
2431 hir::ExprKind::Tup([]) => Simple,
2432 hir::ExprKind::Block(hir::Block { stmts: [], expr: Some(expr), .. }, _) => {
2433 if classify(expr) == Complex { Complex } else { Simple }
2434 }
2435 hir::ExprKind::Path(hir::QPath::Resolved(_, hir::Path { segments, .. })) => {
2440 if segments.iter().all(|segment| segment.args.is_none()) { Simple } else { Complex }
2441 }
2442 hir::ExprKind::Path(hir::QPath::TypeRelative(..)) => Simple,
2445 hir::ExprKind::Path(hir::QPath::LangItem(..)) => Simple,
2447 _ => Complex,
2448 }
2449 }
2450
2451 match classify(value) {
2452 Literal
2462 if !value.span.from_expansion()
2463 && let Ok(snippet) = tcx.sess.source_map().span_to_snippet(value.span) =>
2464 {
2465 snippet
2466 }
2467
2468 Literal | Simple => id_to_string(&hir, body.id().hir_id),
2471
2472 Complex => {
2476 if tcx.def_kind(def_id) == DefKind::AnonConst {
2477 "{ _ }".to_owned()
2478 } else {
2479 "_".to_owned()
2480 }
2481 }
2482 }
2483}