-
Notifications
You must be signed in to change notification settings - Fork 12.7k
/
encoder.rs
1875 lines (1668 loc) · 74.7 KB
/
encoder.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::rmeta::table::FixedSizeEncoding;
use crate::rmeta::*;
use log::{debug, trace};
use rustc::hir::map::Map;
use rustc::middle::cstore::{EncodedMetadata, ForeignModule, LinkagePreference, NativeLibrary};
use rustc::middle::dependency_format::Linkage;
use rustc::middle::exported_symbols::{metadata_symbol_name, ExportedSymbol, SymbolExportLevel};
use rustc::middle::lang_items;
use rustc::mir::{self, interpret};
use rustc::traits::specialization_graph;
use rustc::ty::codec::{self as ty_codec, TyEncoder};
use rustc::ty::layout::VariantIdx;
use rustc::ty::{self, SymbolName, Ty, TyCtxt};
use rustc_ast::ast::{self, Ident};
use rustc_ast::attr;
use rustc_data_structures::fingerprint::Fingerprint;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stable_hasher::StableHasher;
use rustc_data_structures::sync::{join, Lrc};
use rustc_hir as hir;
use rustc_hir::def::CtorKind;
use rustc_hir::def_id::DefIdSet;
use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc_hir::definitions::DefPathTable;
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_hir::itemlikevisit::{ItemLikeVisitor, ParItemLikeVisitor};
use rustc_hir::{AnonConst, GenericParamKind};
use rustc_index::vec::Idx;
use rustc_serialize::{opaque, Encodable, Encoder, SpecializedEncoder};
use rustc_session::config::{self, CrateType};
use rustc_span::source_map::Spanned;
use rustc_span::symbol::{kw, sym, Symbol};
use rustc_span::{self, ExternalSource, FileName, SourceFile, Span};
use std::hash::Hash;
use std::num::NonZeroUsize;
use std::path::Path;
use std::u32;
struct EncodeContext<'tcx> {
opaque: opaque::Encoder,
tcx: TyCtxt<'tcx>,
per_def: PerDefTableBuilders<'tcx>,
lazy_state: LazyState,
type_shorthands: FxHashMap<Ty<'tcx>, usize>,
predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
interpret_allocs: FxHashMap<interpret::AllocId, usize>,
interpret_allocs_inverse: Vec<interpret::AllocId>,
// This is used to speed up Span encoding.
source_file_cache: Lrc<SourceFile>,
}
macro_rules! encoder_methods {
($($name:ident($ty:ty);)*) => {
$(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
self.opaque.$name(value)
})*
}
}
impl<'tcx> Encoder for EncodeContext<'tcx> {
type Error = <opaque::Encoder as Encoder>::Error;
fn emit_unit(&mut self) -> Result<(), Self::Error> {
Ok(())
}
encoder_methods! {
emit_usize(usize);
emit_u128(u128);
emit_u64(u64);
emit_u32(u32);
emit_u16(u16);
emit_u8(u8);
emit_isize(isize);
emit_i128(i128);
emit_i64(i64);
emit_i32(i32);
emit_i16(i16);
emit_i8(i8);
emit_bool(bool);
emit_f64(f64);
emit_f32(f32);
emit_char(char);
emit_str(&str);
}
}
impl<'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'tcx> {
fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
self.emit_lazy_distance(*lazy)
}
}
impl<'tcx, T> SpecializedEncoder<Lazy<[T]>> for EncodeContext<'tcx> {
fn specialized_encode(&mut self, lazy: &Lazy<[T]>) -> Result<(), Self::Error> {
self.emit_usize(lazy.meta)?;
if lazy.meta == 0 {
return Ok(());
}
self.emit_lazy_distance(*lazy)
}
}
impl<'tcx, I: Idx, T> SpecializedEncoder<Lazy<Table<I, T>>> for EncodeContext<'tcx>
where
Option<T>: FixedSizeEncoding,
{
fn specialized_encode(&mut self, lazy: &Lazy<Table<I, T>>) -> Result<(), Self::Error> {
self.emit_usize(lazy.meta)?;
self.emit_lazy_distance(*lazy)
}
}
impl<'tcx> SpecializedEncoder<CrateNum> for EncodeContext<'tcx> {
#[inline]
fn specialized_encode(&mut self, cnum: &CrateNum) -> Result<(), Self::Error> {
self.emit_u32(cnum.as_u32())
}
}
impl<'tcx> SpecializedEncoder<DefId> for EncodeContext<'tcx> {
#[inline]
fn specialized_encode(&mut self, def_id: &DefId) -> Result<(), Self::Error> {
let DefId { krate, index } = *def_id;
krate.encode(self)?;
index.encode(self)
}
}
impl<'tcx> SpecializedEncoder<DefIndex> for EncodeContext<'tcx> {
#[inline]
fn specialized_encode(&mut self, def_index: &DefIndex) -> Result<(), Self::Error> {
self.emit_u32(def_index.as_u32())
}
}
impl<'tcx> SpecializedEncoder<Span> for EncodeContext<'tcx> {
fn specialized_encode(&mut self, span: &Span) -> Result<(), Self::Error> {
if span.is_dummy() {
return TAG_INVALID_SPAN.encode(self);
}
let span = span.data();
// The Span infrastructure should make sure that this invariant holds:
debug_assert!(span.lo <= span.hi);
if !self.source_file_cache.contains(span.lo) {
let source_map = self.tcx.sess.source_map();
let source_file_index = source_map.lookup_source_file_idx(span.lo);
self.source_file_cache = source_map.files()[source_file_index].clone();
}
if !self.source_file_cache.contains(span.hi) {
// Unfortunately, macro expansion still sometimes generates Spans
// that malformed in this way.
return TAG_INVALID_SPAN.encode(self);
}
// There are two possible cases here:
// 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the
// crate we are writing metadata for. When the metadata for *this* crate gets
// deserialized, the deserializer will need to know which crate it originally came
// from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should
// be deserialized after the rest of the span data, which tells the deserializer
// which crate contains the source map information.
// 2. This span comes from our own crate. No special hamdling is needed - we just
// write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use
// our own source map information.
let (tag, lo, hi) = if self.source_file_cache.is_imported() {
// To simplify deserialization, we 'rebase' this span onto the crate it originally came from
// (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values
// are relative to the source map information for the 'foreign' crate whose CrateNum
// we write into the metadata. This allows `imported_source_files` to binary
// search through the 'foreign' crate's source map information, using the
// deserialized 'lo' and 'hi' values directly.
//
// All of this logic ensures that the final result of deserialization is a 'normal'
// Span that can be used without any additional trouble.
let external_start_pos = {
// Introduce a new scope so that we drop the 'lock()' temporary
match &*self.source_file_cache.external_src.lock() {
ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos,
src => panic!("Unexpected external source {:?}", src),
}
};
let lo = (span.lo - self.source_file_cache.start_pos) + external_start_pos;
let hi = (span.hi - self.source_file_cache.start_pos) + external_start_pos;
(TAG_VALID_SPAN_FOREIGN, lo, hi)
} else {
(TAG_VALID_SPAN_LOCAL, span.lo, span.hi)
};
tag.encode(self)?;
lo.encode(self)?;
// Encode length which is usually less than span.hi and profits more
// from the variable-length integer encoding that we use.
let len = hi - lo;
len.encode(self)?;
if tag == TAG_VALID_SPAN_FOREIGN {
// This needs to be two lines to avoid holding the `self.source_file_cache`
// while calling `cnum.encode(self)`
let cnum = self.source_file_cache.cnum;
cnum.encode(self)?;
}
Ok(())
// Don't encode the expansion context.
}
}
impl<'tcx> SpecializedEncoder<LocalDefId> for EncodeContext<'tcx> {
#[inline]
fn specialized_encode(&mut self, def_id: &LocalDefId) -> Result<(), Self::Error> {
self.specialized_encode(&def_id.to_def_id())
}
}
impl<'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'tcx> {
fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands)
}
}
impl<'tcx> SpecializedEncoder<interpret::AllocId> for EncodeContext<'tcx> {
fn specialized_encode(&mut self, alloc_id: &interpret::AllocId) -> Result<(), Self::Error> {
use std::collections::hash_map::Entry;
let index = match self.interpret_allocs.entry(*alloc_id) {
Entry::Occupied(e) => *e.get(),
Entry::Vacant(e) => {
let idx = self.interpret_allocs_inverse.len();
self.interpret_allocs_inverse.push(*alloc_id);
e.insert(idx);
idx
}
};
index.encode(self)
}
}
impl<'tcx> SpecializedEncoder<&'tcx [(ty::Predicate<'tcx>, Span)]> for EncodeContext<'tcx> {
fn specialized_encode(
&mut self,
predicates: &&'tcx [(ty::Predicate<'tcx>, Span)],
) -> Result<(), Self::Error> {
ty_codec::encode_spanned_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands)
}
}
impl<'tcx> SpecializedEncoder<Fingerprint> for EncodeContext<'tcx> {
fn specialized_encode(&mut self, f: &Fingerprint) -> Result<(), Self::Error> {
f.encode_opaque(&mut self.opaque)
}
}
impl<'tcx, T: Encodable> SpecializedEncoder<mir::ClearCrossCrate<T>> for EncodeContext<'tcx> {
fn specialized_encode(&mut self, _: &mir::ClearCrossCrate<T>) -> Result<(), Self::Error> {
Ok(())
}
}
impl<'tcx> TyEncoder for EncodeContext<'tcx> {
fn position(&self) -> usize {
self.opaque.position()
}
}
/// Helper trait to allow overloading `EncodeContext::lazy` for iterators.
trait EncodeContentsForLazy<T: ?Sized + LazyMeta> {
fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) -> T::Meta;
}
impl<T: Encodable> EncodeContentsForLazy<T> for &T {
fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) {
self.encode(ecx).unwrap()
}
}
impl<T: Encodable> EncodeContentsForLazy<T> for T {
fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) {
self.encode(ecx).unwrap()
}
}
impl<I, T: Encodable> EncodeContentsForLazy<[T]> for I
where
I: IntoIterator,
I::Item: EncodeContentsForLazy<T>,
{
fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'tcx>) -> usize {
self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count()
}
}
// Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would
// normally need extra variables to avoid errors about multiple mutable borrows.
macro_rules! record {
($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{
{
let value = $value;
let lazy = $self.lazy(value);
$self.$tables.$table.set($def_id.index, lazy);
}
}};
}
impl<'tcx> EncodeContext<'tcx> {
fn emit_lazy_distance<T: ?Sized + LazyMeta>(
&mut self,
lazy: Lazy<T>,
) -> Result<(), <Self as Encoder>::Error> {
let min_end = lazy.position.get() + T::min_size(lazy.meta);
let distance = match self.lazy_state {
LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
LazyState::NodeStart(start) => {
let start = start.get();
assert!(min_end <= start);
start - min_end
}
LazyState::Previous(last_min_end) => {
assert!(
last_min_end <= lazy.position,
"make sure that the calls to `lazy*` \
are in the same order as the metadata fields",
);
lazy.position.get() - last_min_end.get()
}
};
self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap());
self.emit_usize(distance)
}
fn lazy<T: ?Sized + LazyMeta>(&mut self, value: impl EncodeContentsForLazy<T>) -> Lazy<T> {
let pos = NonZeroUsize::new(self.position()).unwrap();
assert_eq!(self.lazy_state, LazyState::NoNode);
self.lazy_state = LazyState::NodeStart(pos);
let meta = value.encode_contents_for_lazy(self);
self.lazy_state = LazyState::NoNode;
assert!(pos.get() + <T>::min_size(meta) <= self.position());
Lazy::from_position_and_meta(pos, meta)
}
fn encode_info_for_items(&mut self) {
let krate = self.tcx.hir().krate();
let vis = Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Public };
self.encode_info_for_mod(hir::CRATE_HIR_ID, &krate.item.module, &krate.item.attrs, &vis);
krate.visit_all_item_likes(&mut self.as_deep_visitor());
for macro_def in krate.exported_macros {
self.visit_macro_def(macro_def);
}
}
fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
let definitions = self.tcx.hir().definitions();
self.lazy(definitions.def_path_table())
}
fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> {
let source_map = self.tcx.sess.source_map();
let all_source_files = source_map.files();
let (working_dir, _cwd_remapped) = self.tcx.sess.working_dir.clone();
let adapted = all_source_files
.iter()
.filter(|source_file| {
// No need to re-export imported source_files, as any downstream
// crate will import them from their original source.
// FIXME(eddyb) the `Span` encoding should take that into account.
!source_file.is_imported()
})
.map(|source_file| {
match source_file.name {
// This path of this SourceFile has been modified by
// path-remapping, so we use it verbatim (and avoid
// cloning the whole map in the process).
_ if source_file.name_was_remapped => source_file.clone(),
// Otherwise expand all paths to absolute paths because
// any relative paths are potentially relative to a
// wrong directory.
FileName::Real(ref name) => {
let mut adapted = (**source_file).clone();
adapted.name = Path::new(&working_dir).join(name).into();
adapted.name_hash = {
let mut hasher: StableHasher = StableHasher::new();
adapted.name.hash(&mut hasher);
hasher.finish::<u128>()
};
Lrc::new(adapted)
}
// expanded code, not from a file
_ => source_file.clone(),
}
})
.collect::<Vec<_>>();
self.lazy(adapted.iter().map(|rc| &**rc))
}
fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> {
let is_proc_macro = self.tcx.sess.crate_types.borrow().contains(&CrateType::ProcMacro);
let mut i = self.position();
let crate_deps = self.encode_crate_deps();
let dylib_dependency_formats = self.encode_dylib_dependency_formats();
let dep_bytes = self.position() - i;
// Encode the lib features.
i = self.position();
let lib_features = self.encode_lib_features();
let lib_feature_bytes = self.position() - i;
// Encode the language items.
i = self.position();
let lang_items = self.encode_lang_items();
let lang_items_missing = self.encode_lang_items_missing();
let lang_item_bytes = self.position() - i;
// Encode the diagnostic items.
i = self.position();
let diagnostic_items = self.encode_diagnostic_items();
let diagnostic_item_bytes = self.position() - i;
// Encode the native libraries used
i = self.position();
let native_libraries = self.encode_native_libraries();
let native_lib_bytes = self.position() - i;
let foreign_modules = self.encode_foreign_modules();
// Encode source_map
i = self.position();
let source_map = self.encode_source_map();
let source_map_bytes = self.position() - i;
// Encode DefPathTable
i = self.position();
let def_path_table = self.encode_def_path_table();
let def_path_table_bytes = self.position() - i;
// Encode the def IDs of impls, for coherence checking.
i = self.position();
let impls = self.encode_impls();
let impl_bytes = self.position() - i;
let tcx = self.tcx;
// Encode the items.
i = self.position();
self.encode_info_for_items();
let item_bytes = self.position() - i;
// Encode the allocation index
let interpret_alloc_index = {
let mut interpret_alloc_index = Vec::new();
let mut n = 0;
trace!("beginning to encode alloc ids");
loop {
let new_n = self.interpret_allocs_inverse.len();
// if we have found new ids, serialize those, too
if n == new_n {
// otherwise, abort
break;
}
trace!("encoding {} further alloc ids", new_n - n);
for idx in n..new_n {
let id = self.interpret_allocs_inverse[idx];
let pos = self.position() as u32;
interpret_alloc_index.push(pos);
interpret::specialized_encode_alloc_id(self, tcx, id).unwrap();
}
n = new_n;
}
self.lazy(interpret_alloc_index)
};
i = self.position();
let per_def = self.per_def.encode(&mut self.opaque);
let per_def_bytes = self.position() - i;
// Encode the proc macro data
i = self.position();
let proc_macro_data = self.encode_proc_macros();
let proc_macro_data_bytes = self.position() - i;
// Encode exported symbols info. This is prefetched in `encode_metadata` so we encode
// this last to give the prefetching as much time as possible to complete.
i = self.position();
let exported_symbols = self.tcx.exported_symbols(LOCAL_CRATE);
let exported_symbols = self.encode_exported_symbols(&exported_symbols);
let exported_symbols_bytes = self.position() - i;
let attrs = tcx.hir().krate_attrs();
let has_default_lib_allocator = attr::contains_name(&attrs, sym::default_lib_allocator);
let root = self.lazy(CrateRoot {
name: tcx.crate_name(LOCAL_CRATE),
extra_filename: tcx.sess.opts.cg.extra_filename.clone(),
triple: tcx.sess.opts.target_triple.clone(),
hash: tcx.crate_hash(LOCAL_CRATE),
disambiguator: tcx.sess.local_crate_disambiguator(),
panic_strategy: tcx.sess.panic_strategy(),
edition: tcx.sess.edition(),
has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE),
has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE),
has_default_lib_allocator,
plugin_registrar_fn: tcx.plugin_registrar_fn(LOCAL_CRATE).map(|id| id.index),
proc_macro_decls_static: if is_proc_macro {
let id = tcx.proc_macro_decls_static(LOCAL_CRATE).unwrap();
Some(id.index)
} else {
None
},
proc_macro_data,
proc_macro_stability: if is_proc_macro {
tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied()
} else {
None
},
compiler_builtins: attr::contains_name(&attrs, sym::compiler_builtins),
needs_allocator: attr::contains_name(&attrs, sym::needs_allocator),
needs_panic_runtime: attr::contains_name(&attrs, sym::needs_panic_runtime),
no_builtins: attr::contains_name(&attrs, sym::no_builtins),
panic_runtime: attr::contains_name(&attrs, sym::panic_runtime),
profiler_runtime: attr::contains_name(&attrs, sym::profiler_runtime),
symbol_mangling_version: tcx.sess.opts.debugging_opts.symbol_mangling_version,
crate_deps,
dylib_dependency_formats,
lib_features,
lang_items,
diagnostic_items,
lang_items_missing,
native_libraries,
foreign_modules,
source_map,
def_path_table,
impls,
exported_symbols,
interpret_alloc_index,
per_def,
});
let total_bytes = self.position();
if self.tcx.sess.meta_stats() {
let mut zero_bytes = 0;
for e in self.opaque.data.iter() {
if *e == 0 {
zero_bytes += 1;
}
}
println!("metadata stats:");
println!(" dep bytes: {}", dep_bytes);
println!(" lib feature bytes: {}", lib_feature_bytes);
println!(" lang item bytes: {}", lang_item_bytes);
println!(" diagnostic item bytes: {}", diagnostic_item_bytes);
println!(" native bytes: {}", native_lib_bytes);
println!(" source_map bytes: {}", source_map_bytes);
println!(" impl bytes: {}", impl_bytes);
println!(" exp. symbols bytes: {}", exported_symbols_bytes);
println!(" def-path table bytes: {}", def_path_table_bytes);
println!(" proc-macro-data-bytes: {}", proc_macro_data_bytes);
println!(" item bytes: {}", item_bytes);
println!(" per-def table bytes: {}", per_def_bytes);
println!(" zero bytes: {}", zero_bytes);
println!(" total bytes: {}", total_bytes);
}
root
}
}
impl EncodeContext<'tcx> {
fn encode_variances_of(&mut self, def_id: DefId) {
debug!("EncodeContext::encode_variances_of({:?})", def_id);
record!(self.per_def.variances[def_id] <- &self.tcx.variances_of(def_id)[..]);
}
fn encode_item_type(&mut self, def_id: DefId) {
debug!("EncodeContext::encode_item_type({:?})", def_id);
record!(self.per_def.ty[def_id] <- self.tcx.type_of(def_id));
}
fn encode_enum_variant_info(&mut self, enum_did: DefId, index: VariantIdx) {
let tcx = self.tcx;
let def = tcx.adt_def(enum_did);
let variant = &def.variants[index];
let def_id = variant.def_id;
debug!("EncodeContext::encode_enum_variant_info({:?})", def_id);
let data = VariantData {
ctor_kind: variant.ctor_kind,
discr: variant.discr,
ctor: variant.ctor_def_id.map(|did| did.index),
};
let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
let enum_vis = &tcx.hir().expect_item(enum_id).vis;
record!(self.per_def.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
record!(self.per_def.visibility[def_id] <-
ty::Visibility::from_hir(enum_vis, enum_id, self.tcx));
record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
record!(self.per_def.attributes[def_id] <- &self.tcx.get_attrs(def_id)[..]);
record!(self.per_def.children[def_id] <- variant.fields.iter().map(|f| {
assert!(f.did.is_local());
f.did.index
}));
self.encode_ident_span(def_id, variant.ident);
self.encode_stability(def_id);
self.encode_deprecation(def_id);
self.encode_item_type(def_id);
if variant.ctor_kind == CtorKind::Fn {
// FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`.
if let Some(ctor_def_id) = variant.ctor_def_id {
record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id));
}
// FIXME(eddyb) is this ever used?
self.encode_variances_of(def_id);
}
self.encode_generics(def_id);
self.encode_explicit_predicates(def_id);
self.encode_inferred_outlives(def_id);
self.encode_optimized_mir(def_id);
self.encode_promoted_mir(def_id);
}
fn encode_enum_variant_ctor(&mut self, enum_did: DefId, index: VariantIdx) {
let tcx = self.tcx;
let def = tcx.adt_def(enum_did);
let variant = &def.variants[index];
let def_id = variant.ctor_def_id.unwrap();
debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id);
// FIXME(eddyb) encode only the `CtorKind` for constructors.
let data = VariantData {
ctor_kind: variant.ctor_kind,
discr: variant.discr,
ctor: Some(def_id.index),
};
// Variant constructors have the same visibility as the parent enums, unless marked as
// non-exhaustive, in which case they are lowered to `pub(crate)`.
let enum_id = tcx.hir().as_local_hir_id(enum_did).unwrap();
let enum_vis = &tcx.hir().expect_item(enum_id).vis;
let mut ctor_vis = ty::Visibility::from_hir(enum_vis, enum_id, tcx);
if variant.is_field_list_non_exhaustive() && ctor_vis == ty::Visibility::Public {
ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
}
record!(self.per_def.kind[def_id] <- EntryKind::Variant(self.lazy(data)));
record!(self.per_def.visibility[def_id] <- ctor_vis);
record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
self.encode_stability(def_id);
self.encode_deprecation(def_id);
self.encode_item_type(def_id);
if variant.ctor_kind == CtorKind::Fn {
record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
self.encode_variances_of(def_id);
}
self.encode_generics(def_id);
self.encode_explicit_predicates(def_id);
self.encode_inferred_outlives(def_id);
self.encode_optimized_mir(def_id);
self.encode_promoted_mir(def_id);
}
fn encode_info_for_mod(
&mut self,
id: hir::HirId,
md: &hir::Mod<'_>,
attrs: &[ast::Attribute],
vis: &hir::Visibility<'_>,
) {
let tcx = self.tcx;
let def_id = tcx.hir().local_def_id(id);
debug!("EncodeContext::encode_info_for_mod({:?})", def_id);
let data = ModData {
reexports: match tcx.module_exports(def_id) {
Some(exports) => self.lazy(exports),
_ => Lazy::empty(),
},
};
record!(self.per_def.kind[def_id] <- EntryKind::Mod(self.lazy(data)));
record!(self.per_def.visibility[def_id] <- ty::Visibility::from_hir(vis, id, self.tcx));
record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
record!(self.per_def.attributes[def_id] <- attrs);
record!(self.per_def.children[def_id] <- md.item_ids.iter().map(|item_id| {
tcx.hir().local_def_id(item_id.id).index
}));
self.encode_stability(def_id);
self.encode_deprecation(def_id);
}
fn encode_field(&mut self, adt_def_id: DefId, variant_index: VariantIdx, field_index: usize) {
let tcx = self.tcx;
let variant = &tcx.adt_def(adt_def_id).variants[variant_index];
let field = &variant.fields[field_index];
let def_id = field.did;
debug!("EncodeContext::encode_field({:?})", def_id);
let variant_id = tcx.hir().as_local_hir_id(variant.def_id).unwrap();
let variant_data = tcx.hir().expect_variant_data(variant_id);
record!(self.per_def.kind[def_id] <- EntryKind::Field);
record!(self.per_def.visibility[def_id] <- field.vis);
record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
record!(self.per_def.attributes[def_id] <- variant_data.fields()[field_index].attrs);
self.encode_ident_span(def_id, field.ident);
self.encode_stability(def_id);
self.encode_deprecation(def_id);
self.encode_item_type(def_id);
self.encode_generics(def_id);
self.encode_explicit_predicates(def_id);
self.encode_inferred_outlives(def_id);
}
fn encode_struct_ctor(&mut self, adt_def_id: DefId, def_id: DefId) {
debug!("EncodeContext::encode_struct_ctor({:?})", def_id);
let tcx = self.tcx;
let adt_def = tcx.adt_def(adt_def_id);
let variant = adt_def.non_enum_variant();
let data = VariantData {
ctor_kind: variant.ctor_kind,
discr: variant.discr,
ctor: Some(def_id.index),
};
let struct_id = tcx.hir().as_local_hir_id(adt_def_id).unwrap();
let struct_vis = &tcx.hir().expect_item(struct_id).vis;
let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
for field in &variant.fields {
if ctor_vis.is_at_least(field.vis, tcx) {
ctor_vis = field.vis;
}
}
// If the structure is marked as non_exhaustive then lower the visibility
// to within the crate.
if adt_def.non_enum_variant().is_field_list_non_exhaustive()
&& ctor_vis == ty::Visibility::Public
{
ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX));
}
record!(self.per_def.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr));
record!(self.per_def.visibility[def_id] <- ctor_vis);
record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
self.encode_stability(def_id);
self.encode_deprecation(def_id);
self.encode_item_type(def_id);
if variant.ctor_kind == CtorKind::Fn {
record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
self.encode_variances_of(def_id);
}
self.encode_generics(def_id);
self.encode_explicit_predicates(def_id);
self.encode_inferred_outlives(def_id);
self.encode_optimized_mir(def_id);
self.encode_promoted_mir(def_id);
}
fn encode_generics(&mut self, def_id: DefId) {
debug!("EncodeContext::encode_generics({:?})", def_id);
record!(self.per_def.generics[def_id] <- self.tcx.generics_of(def_id));
}
fn encode_explicit_predicates(&mut self, def_id: DefId) {
debug!("EncodeContext::encode_explicit_predicates({:?})", def_id);
record!(self.per_def.explicit_predicates[def_id] <-
self.tcx.explicit_predicates_of(def_id));
}
fn encode_inferred_outlives(&mut self, def_id: DefId) {
debug!("EncodeContext::encode_inferred_outlives({:?})", def_id);
let inferred_outlives = self.tcx.inferred_outlives_of(def_id);
if !inferred_outlives.is_empty() {
record!(self.per_def.inferred_outlives[def_id] <- inferred_outlives);
}
}
fn encode_super_predicates(&mut self, def_id: DefId) {
debug!("EncodeContext::encode_super_predicates({:?})", def_id);
record!(self.per_def.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id));
}
fn encode_info_for_trait_item(&mut self, def_id: DefId) {
debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id);
let tcx = self.tcx;
let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
let ast_item = tcx.hir().expect_trait_item(hir_id);
let trait_item = tcx.associated_item(def_id);
let container = match trait_item.defaultness {
hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault,
hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired,
hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"),
};
record!(self.per_def.kind[def_id] <- match trait_item.kind {
ty::AssocKind::Const => {
let rendered = rustc_hir_pretty::to_string(
&(&self.tcx.hir() as &dyn intravisit::Map<'_>),
|s| s.print_trait_item(ast_item)
);
let rendered_const = self.lazy(RenderedConst(rendered));
EntryKind::AssocConst(
container,
Default::default(),
rendered_const,
)
}
ty::AssocKind::Method => {
let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind {
let param_names = match *m {
hir::TraitFn::Required(ref names) => {
self.encode_fn_param_names(names)
}
hir::TraitFn::Provided(body) => {
self.encode_fn_param_names_for_body(body)
}
};
FnData {
asyncness: m_sig.header.asyncness,
constness: hir::Constness::NotConst,
param_names,
}
} else {
bug!()
};
EntryKind::AssocFn(self.lazy(AssocFnData {
fn_data,
container,
has_self: trait_item.method_has_self_argument,
}))
}
ty::AssocKind::Type => EntryKind::AssocType(container),
ty::AssocKind::OpaqueTy => span_bug!(ast_item.span, "opaque type in trait"),
});
record!(self.per_def.visibility[def_id] <- trait_item.vis);
record!(self.per_def.span[def_id] <- ast_item.span);
record!(self.per_def.attributes[def_id] <- ast_item.attrs);
self.encode_ident_span(def_id, ast_item.ident);
self.encode_stability(def_id);
self.encode_const_stability(def_id);
self.encode_deprecation(def_id);
match trait_item.kind {
ty::AssocKind::Const | ty::AssocKind::Method => {
self.encode_item_type(def_id);
}
ty::AssocKind::Type => {
if trait_item.defaultness.has_value() {
self.encode_item_type(def_id);
}
}
ty::AssocKind::OpaqueTy => unreachable!(),
}
if trait_item.kind == ty::AssocKind::Method {
record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
self.encode_variances_of(def_id);
}
self.encode_generics(def_id);
self.encode_explicit_predicates(def_id);
self.encode_inferred_outlives(def_id);
// This should be kept in sync with `PrefetchVisitor.visit_trait_item`.
self.encode_optimized_mir(def_id);
self.encode_promoted_mir(def_id);
}
fn metadata_output_only(&self) -> bool {
// MIR optimisation can be skipped when we're just interested in the metadata.
!self.tcx.sess.opts.output_types.should_codegen()
}
fn encode_info_for_impl_item(&mut self, def_id: DefId) {
debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id);
let tcx = self.tcx;
let hir_id = self.tcx.hir().as_local_hir_id(def_id).unwrap();
let ast_item = self.tcx.hir().expect_impl_item(hir_id);
let impl_item = self.tcx.associated_item(def_id);
let container = match impl_item.defaultness {
hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault,
hir::Defaultness::Final => AssocContainer::ImplFinal,
hir::Defaultness::Default { has_value: false } => {
span_bug!(ast_item.span, "impl items always have values (currently)")
}
};
record!(self.per_def.kind[def_id] <- match impl_item.kind {
ty::AssocKind::Const => {
if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind {
let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id);
EntryKind::AssocConst(
container,
qualifs,
self.encode_rendered_const_for_body(body_id))
} else {
bug!()
}
}
ty::AssocKind::Method => {
let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind {
FnData {
asyncness: sig.header.asyncness,
constness: sig.header.constness,
param_names: self.encode_fn_param_names_for_body(body),
}
} else {
bug!()
};
EntryKind::AssocFn(self.lazy(AssocFnData {
fn_data,
container,
has_self: impl_item.method_has_self_argument,
}))
}
ty::AssocKind::OpaqueTy => EntryKind::AssocOpaqueTy(container),
ty::AssocKind::Type => EntryKind::AssocType(container)
});
record!(self.per_def.visibility[def_id] <- impl_item.vis);
record!(self.per_def.span[def_id] <- ast_item.span);
record!(self.per_def.attributes[def_id] <- ast_item.attrs);
self.encode_ident_span(def_id, impl_item.ident);
self.encode_stability(def_id);
self.encode_const_stability(def_id);
self.encode_deprecation(def_id);
self.encode_item_type(def_id);
if impl_item.kind == ty::AssocKind::Method {
record!(self.per_def.fn_sig[def_id] <- tcx.fn_sig(def_id));
self.encode_variances_of(def_id);
}
self.encode_generics(def_id);
self.encode_explicit_predicates(def_id);
self.encode_inferred_outlives(def_id);
// The following part should be kept in sync with `PrefetchVisitor.visit_impl_item`.
let mir = match ast_item.kind {
hir::ImplItemKind::Const(..) => true,
hir::ImplItemKind::Fn(ref sig, _) => {
let generics = self.tcx.generics_of(def_id);
let needs_inline = (generics.requires_monomorphization(self.tcx)
|| tcx.codegen_fn_attrs(def_id).requests_inline())
&& !self.metadata_output_only();
let is_const_fn = sig.header.constness == hir::Constness::Const;
let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
needs_inline || is_const_fn || always_encode_mir
}
hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(..) => false,
};
if mir {
self.encode_optimized_mir(def_id);
self.encode_promoted_mir(def_id);
}
}
fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[ast::Name]> {
self.tcx.dep_graph.with_ignore(|| {
let body = self.tcx.hir().body(body_id);
self.lazy(body.params.iter().map(|arg| match arg.pat.kind {
hir::PatKind::Binding(_, _, ident, _) => ident.name,
_ => kw::Invalid,
}))
})
}
fn encode_fn_param_names(&mut self, param_names: &[ast::Ident]) -> Lazy<[ast::Name]> {
self.lazy(param_names.iter().map(|ident| ident.name))
}