]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/codec.rs
Rollup merge of #107154 - glaubitz:m68k-alloc, r=JohnTitor
[rust.git] / compiler / rustc_middle / src / ty / codec.rs
1 //! This module contains some shared code for encoding and decoding various
2 //! things from the `ty` module, and in particular implements support for
3 //! "shorthands" which allow to have pointers back into the already encoded
4 //! stream instead of re-encoding the same thing twice.
5 //!
6 //! The functionality in here is shared between persisting to crate metadata and
7 //! persisting to incr. comp. caches.
8
9 use crate::arena::ArenaAllocatable;
10 use crate::infer::canonical::{CanonicalVarInfo, CanonicalVarInfos};
11 use crate::mir::{
12     self,
13     interpret::{AllocId, ConstAllocation},
14 };
15 use crate::traits;
16 use crate::ty::subst::SubstsRef;
17 use crate::ty::{self, AdtDef, Ty};
18 use rustc_data_structures::fx::FxHashMap;
19 use rustc_middle::ty::TyCtxt;
20 use rustc_serialize::{Decodable, Encodable};
21 use rustc_span::Span;
22 pub use rustc_type_ir::{TyDecoder, TyEncoder};
23 use std::hash::Hash;
24 use std::intrinsics;
25 use std::marker::DiscriminantKind;
26
27 /// The shorthand encoding uses an enum's variant index `usize`
28 /// and is offset by this value so it never matches a real variant.
29 /// This offset is also chosen so that the first byte is never < 0x80.
30 pub const SHORTHAND_OFFSET: usize = 0x80;
31
32 pub trait EncodableWithShorthand<E: TyEncoder>: Copy + Eq + Hash {
33     type Variant: Encodable<E>;
34     fn variant(&self) -> &Self::Variant;
35 }
36
37 #[allow(rustc::usage_of_ty_tykind)]
38 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> EncodableWithShorthand<E> for Ty<'tcx> {
39     type Variant = ty::TyKind<'tcx>;
40
41     #[inline]
42     fn variant(&self) -> &Self::Variant {
43         self.kind()
44     }
45 }
46
47 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> EncodableWithShorthand<E> for ty::PredicateKind<'tcx> {
48     type Variant = ty::PredicateKind<'tcx>;
49
50     #[inline]
51     fn variant(&self) -> &Self::Variant {
52         self
53     }
54 }
55
56 /// Trait for decoding to a reference.
57 ///
58 /// This is a separate trait from `Decodable` so that we can implement it for
59 /// upstream types, such as `FxHashSet`.
60 ///
61 /// The `TyDecodable` derive macro will use this trait for fields that are
62 /// references (and don't use a type alias to hide that).
63 ///
64 /// `Decodable` can still be implemented in cases where `Decodable` is required
65 /// by a trait bound.
66 pub trait RefDecodable<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> {
67     fn decode(d: &mut D) -> &'tcx Self;
68 }
69
70 /// Encode the given value or a previously cached shorthand.
71 pub fn encode_with_shorthand<'tcx, E, T, M>(encoder: &mut E, value: &T, cache: M)
72 where
73     E: TyEncoder<I = TyCtxt<'tcx>>,
74     M: for<'b> Fn(&'b mut E) -> &'b mut FxHashMap<T, usize>,
75     T: EncodableWithShorthand<E>,
76     // The discriminant and shorthand must have the same size.
77     T::Variant: DiscriminantKind<Discriminant = isize>,
78 {
79     let existing_shorthand = cache(encoder).get(value).copied();
80     if let Some(shorthand) = existing_shorthand {
81         encoder.emit_usize(shorthand);
82         return;
83     }
84
85     let variant = value.variant();
86
87     let start = encoder.position();
88     variant.encode(encoder);
89     let len = encoder.position() - start;
90
91     // The shorthand encoding uses the same usize as the
92     // discriminant, with an offset so they can't conflict.
93     let discriminant = intrinsics::discriminant_value(variant);
94     assert!(SHORTHAND_OFFSET > discriminant as usize);
95
96     let shorthand = start + SHORTHAND_OFFSET;
97
98     // Get the number of bits that leb128 could fit
99     // in the same space as the fully encoded type.
100     let leb128_bits = len * 7;
101
102     // Check that the shorthand is a not longer than the
103     // full encoding itself, i.e., it's an obvious win.
104     if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
105         cache(encoder).insert(*value, shorthand);
106     }
107 }
108
109 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for Ty<'tcx> {
110     fn encode(&self, e: &mut E) {
111         encode_with_shorthand(e, self, TyEncoder::type_shorthands);
112     }
113 }
114
115 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E>
116     for ty::Binder<'tcx, ty::PredicateKind<'tcx>>
117 {
118     fn encode(&self, e: &mut E) {
119         self.bound_vars().encode(e);
120         encode_with_shorthand(e, &self.skip_binder(), TyEncoder::predicate_shorthands);
121     }
122 }
123
124 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::Predicate<'tcx> {
125     fn encode(&self, e: &mut E) {
126         self.kind().encode(e);
127     }
128 }
129
130 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::Region<'tcx> {
131     fn encode(&self, e: &mut E) {
132         self.kind().encode(e);
133     }
134 }
135
136 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::Const<'tcx> {
137     fn encode(&self, e: &mut E) {
138         self.0.0.encode(e);
139     }
140 }
141
142 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ConstAllocation<'tcx> {
143     fn encode(&self, e: &mut E) {
144         self.inner().encode(e)
145     }
146 }
147
148 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for AdtDef<'tcx> {
149     fn encode(&self, e: &mut E) {
150         self.0.0.encode(e)
151     }
152 }
153
154 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for AllocId {
155     fn encode(&self, e: &mut E) {
156         e.encode_alloc_id(self)
157     }
158 }
159
160 impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::ParamEnv<'tcx> {
161     fn encode(&self, e: &mut E) {
162         self.caller_bounds().encode(e);
163         self.reveal().encode(e);
164         self.constness().encode(e);
165     }
166 }
167
168 #[inline]
169 fn decode_arena_allocable<
170     'tcx,
171     D: TyDecoder<I = TyCtxt<'tcx>>,
172     T: ArenaAllocatable<'tcx> + Decodable<D>,
173 >(
174     decoder: &mut D,
175 ) -> &'tcx T
176 where
177     D: TyDecoder,
178 {
179     decoder.interner().arena.alloc(Decodable::decode(decoder))
180 }
181
182 #[inline]
183 fn decode_arena_allocable_slice<
184     'tcx,
185     D: TyDecoder<I = TyCtxt<'tcx>>,
186     T: ArenaAllocatable<'tcx> + Decodable<D>,
187 >(
188     decoder: &mut D,
189 ) -> &'tcx [T]
190 where
191     D: TyDecoder,
192 {
193     decoder.interner().arena.alloc_from_iter(<Vec<T> as Decodable<D>>::decode(decoder))
194 }
195
196 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for Ty<'tcx> {
197     #[allow(rustc::usage_of_ty_tykind)]
198     fn decode(decoder: &mut D) -> Ty<'tcx> {
199         // Handle shorthands first, if we have a usize > 0x80.
200         if decoder.positioned_at_shorthand() {
201             let pos = decoder.read_usize();
202             assert!(pos >= SHORTHAND_OFFSET);
203             let shorthand = pos - SHORTHAND_OFFSET;
204
205             decoder.cached_ty_for_shorthand(shorthand, |decoder| {
206                 decoder.with_position(shorthand, Ty::decode)
207             })
208         } else {
209             let tcx = decoder.interner();
210             tcx.mk_ty(rustc_type_ir::TyKind::decode(decoder))
211         }
212     }
213 }
214
215 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D>
216     for ty::Binder<'tcx, ty::PredicateKind<'tcx>>
217 {
218     fn decode(decoder: &mut D) -> ty::Binder<'tcx, ty::PredicateKind<'tcx>> {
219         let bound_vars = Decodable::decode(decoder);
220         // Handle shorthands first, if we have a usize > 0x80.
221         ty::Binder::bind_with_vars(
222             if decoder.positioned_at_shorthand() {
223                 let pos = decoder.read_usize();
224                 assert!(pos >= SHORTHAND_OFFSET);
225                 let shorthand = pos - SHORTHAND_OFFSET;
226
227                 decoder.with_position(shorthand, ty::PredicateKind::decode)
228             } else {
229                 ty::PredicateKind::decode(decoder)
230             },
231             bound_vars,
232         )
233     }
234 }
235
236 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Predicate<'tcx> {
237     fn decode(decoder: &mut D) -> ty::Predicate<'tcx> {
238         let predicate_kind = Decodable::decode(decoder);
239         decoder.interner().mk_predicate(predicate_kind)
240     }
241 }
242
243 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for SubstsRef<'tcx> {
244     fn decode(decoder: &mut D) -> Self {
245         let len = decoder.read_usize();
246         let tcx = decoder.interner();
247         tcx.mk_substs(
248             (0..len).map::<ty::subst::GenericArg<'tcx>, _>(|_| Decodable::decode(decoder)),
249         )
250     }
251 }
252
253 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for mir::Place<'tcx> {
254     fn decode(decoder: &mut D) -> Self {
255         let local: mir::Local = Decodable::decode(decoder);
256         let len = decoder.read_usize();
257         let projection = decoder.interner().mk_place_elems(
258             (0..len).map::<mir::PlaceElem<'tcx>, _>(|_| Decodable::decode(decoder)),
259         );
260         mir::Place { local, projection }
261     }
262 }
263
264 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Region<'tcx> {
265     fn decode(decoder: &mut D) -> Self {
266         decoder.interner().mk_region(Decodable::decode(decoder))
267     }
268 }
269
270 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for CanonicalVarInfos<'tcx> {
271     fn decode(decoder: &mut D) -> Self {
272         let len = decoder.read_usize();
273         let interned: Vec<CanonicalVarInfo<'tcx>> =
274             (0..len).map(|_| Decodable::decode(decoder)).collect();
275         decoder.interner().intern_canonical_var_infos(interned.as_slice())
276     }
277 }
278
279 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for AllocId {
280     fn decode(decoder: &mut D) -> Self {
281         decoder.decode_alloc_id()
282     }
283 }
284
285 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::SymbolName<'tcx> {
286     fn decode(decoder: &mut D) -> Self {
287         ty::SymbolName::new(decoder.interner(), &decoder.read_str())
288     }
289 }
290
291 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::ParamEnv<'tcx> {
292     fn decode(d: &mut D) -> Self {
293         let caller_bounds = Decodable::decode(d);
294         let reveal = Decodable::decode(d);
295         let constness = Decodable::decode(d);
296         ty::ParamEnv::new(caller_bounds, reveal, constness)
297     }
298 }
299
300 macro_rules! impl_decodable_via_ref {
301     ($($t:ty,)+) => {
302         $(impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for $t {
303             fn decode(decoder: &mut D) -> Self {
304                 RefDecodable::decode(decoder)
305             }
306         })*
307     }
308 }
309
310 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for ty::List<Ty<'tcx>> {
311     fn decode(decoder: &mut D) -> &'tcx Self {
312         let len = decoder.read_usize();
313         decoder.interner().mk_type_list((0..len).map::<Ty<'tcx>, _>(|_| Decodable::decode(decoder)))
314     }
315 }
316
317 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D>
318     for ty::List<ty::PolyExistentialPredicate<'tcx>>
319 {
320     fn decode(decoder: &mut D) -> &'tcx Self {
321         let len = decoder.read_usize();
322         decoder.interner().mk_poly_existential_predicates(
323             (0..len).map::<ty::Binder<'tcx, _>, _>(|_| Decodable::decode(decoder)),
324         )
325     }
326 }
327
328 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Const<'tcx> {
329     fn decode(decoder: &mut D) -> Self {
330         let consts: ty::ConstData<'tcx> = Decodable::decode(decoder);
331         decoder.interner().mk_const(consts.kind, consts.ty)
332     }
333 }
334
335 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for [ty::ValTree<'tcx>] {
336     fn decode(decoder: &mut D) -> &'tcx Self {
337         decoder.interner().arena.alloc_from_iter(
338             (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
339         )
340     }
341 }
342
343 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ConstAllocation<'tcx> {
344     fn decode(decoder: &mut D) -> Self {
345         decoder.interner().intern_const_alloc(Decodable::decode(decoder))
346     }
347 }
348
349 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for AdtDef<'tcx> {
350     fn decode(decoder: &mut D) -> Self {
351         decoder.interner().intern_adt_def(Decodable::decode(decoder))
352     }
353 }
354
355 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D>
356     for [(ty::Predicate<'tcx>, Span)]
357 {
358     fn decode(decoder: &mut D) -> &'tcx Self {
359         decoder.interner().arena.alloc_from_iter(
360             (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
361         )
362     }
363 }
364
365 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for [(ty::Clause<'tcx>, Span)] {
366     fn decode(decoder: &mut D) -> &'tcx Self {
367         decoder.interner().arena.alloc_from_iter(
368             (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::<Vec<_>>(),
369         )
370     }
371 }
372
373 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D>
374     for ty::List<ty::BoundVariableKind>
375 {
376     fn decode(decoder: &mut D) -> &'tcx Self {
377         let len = decoder.read_usize();
378         decoder.interner().mk_bound_variable_kinds(
379             (0..len).map::<ty::BoundVariableKind, _>(|_| Decodable::decode(decoder)),
380         )
381     }
382 }
383
384 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for ty::List<ty::Const<'tcx>> {
385     fn decode(decoder: &mut D) -> &'tcx Self {
386         let len = decoder.read_usize();
387         decoder
388             .interner()
389             .mk_const_list((0..len).map::<ty::Const<'tcx>, _>(|_| Decodable::decode(decoder)))
390     }
391 }
392
393 impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for ty::List<ty::Predicate<'tcx>> {
394     fn decode(decoder: &mut D) -> &'tcx Self {
395         let len = decoder.read_usize();
396         let predicates: Vec<_> =
397             (0..len).map::<ty::Predicate<'tcx>, _>(|_| Decodable::decode(decoder)).collect();
398         decoder.interner().intern_predicates(&predicates)
399     }
400 }
401
402 impl_decodable_via_ref! {
403     &'tcx ty::TypeckResults<'tcx>,
404     &'tcx ty::List<Ty<'tcx>>,
405     &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
406     &'tcx traits::ImplSource<'tcx, ()>,
407     &'tcx mir::Body<'tcx>,
408     &'tcx mir::UnsafetyCheckResult,
409     &'tcx mir::BorrowCheckResult<'tcx>,
410     &'tcx mir::coverage::CodeRegion,
411     &'tcx ty::List<ty::BoundVariableKind>,
412     &'tcx ty::List<ty::Predicate<'tcx>>,
413 }
414
415 #[macro_export]
416 macro_rules! __impl_decoder_methods {
417     ($($name:ident -> $ty:ty;)*) => {
418         $(
419             #[inline]
420             fn $name(&mut self) -> $ty {
421                 self.opaque.$name()
422             }
423         )*
424     }
425 }
426
427 macro_rules! impl_arena_allocatable_decoder {
428     ([]$args:tt) => {};
429     ([decode $(, $attrs:ident)*]
430      [$name:ident: $ty:ty]) => {
431         impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for $ty {
432             #[inline]
433             fn decode(decoder: &mut D) -> &'tcx Self {
434                 decode_arena_allocable(decoder)
435             }
436         }
437
438         impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for [$ty] {
439             #[inline]
440             fn decode(decoder: &mut D) -> &'tcx Self {
441                 decode_arena_allocable_slice(decoder)
442             }
443         }
444     };
445 }
446
447 macro_rules! impl_arena_allocatable_decoders {
448     ([$($a:tt $name:ident: $ty:ty,)*]) => {
449         $(
450             impl_arena_allocatable_decoder!($a [$name: $ty]);
451         )*
452     }
453 }
454
455 rustc_hir::arena_types!(impl_arena_allocatable_decoders);
456 arena_types!(impl_arena_allocatable_decoders);
457
458 macro_rules! impl_arena_copy_decoder {
459     (<$tcx:tt> $($ty:ty,)*) => {
460         $(impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for $ty {
461             #[inline]
462             fn decode(decoder: &mut D) -> &'tcx Self {
463                 decoder.interner().arena.alloc(Decodable::decode(decoder))
464             }
465         }
466
467         impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for [$ty] {
468             #[inline]
469             fn decode(decoder: &mut D) -> &'tcx Self {
470                 decoder.interner().arena.alloc_from_iter(<Vec<_> as Decodable<D>>::decode(decoder))
471             }
472         })*
473     };
474 }
475
476 impl_arena_copy_decoder! {<'tcx>
477     Span,
478     rustc_span::symbol::Ident,
479     ty::Variance,
480     rustc_span::def_id::DefId,
481     rustc_span::def_id::LocalDefId,
482     (rustc_middle::middle::exported_symbols::ExportedSymbol<'tcx>, rustc_middle::middle::exported_symbols::SymbolExportInfo),
483     ty::DeducedParamAttrs,
484 }
485
486 #[macro_export]
487 macro_rules! implement_ty_decoder {
488     ($DecoderName:ident <$($typaram:tt),*>) => {
489         mod __ty_decoder_impl {
490             use std::borrow::Cow;
491             use rustc_serialize::Decoder;
492
493             use super::$DecoderName;
494
495             impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> {
496                 $crate::__impl_decoder_methods! {
497                     read_u128 -> u128;
498                     read_u64 -> u64;
499                     read_u32 -> u32;
500                     read_u16 -> u16;
501                     read_u8 -> u8;
502                     read_usize -> usize;
503
504                     read_i128 -> i128;
505                     read_i64 -> i64;
506                     read_i32 -> i32;
507                     read_i16 -> i16;
508                     read_i8 -> i8;
509                     read_isize -> isize;
510
511                     read_bool -> bool;
512                     read_f64 -> f64;
513                     read_f32 -> f32;
514                     read_char -> char;
515                     read_str -> &str;
516                 }
517
518                 #[inline]
519                 fn read_raw_bytes(&mut self, len: usize) -> &[u8] {
520                     self.opaque.read_raw_bytes(len)
521                 }
522             }
523         }
524     }
525 }
526
527 macro_rules! impl_binder_encode_decode {
528     ($($t:ty),+ $(,)?) => {
529         $(
530             impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::Binder<'tcx, $t> {
531                 fn encode(&self, e: &mut E) {
532                     self.bound_vars().encode(e);
533                     self.as_ref().skip_binder().encode(e);
534                 }
535             }
536             impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Binder<'tcx, $t> {
537                 fn decode(decoder: &mut D) -> Self {
538                     let bound_vars = Decodable::decode(decoder);
539                     ty::Binder::bind_with_vars(Decodable::decode(decoder), bound_vars)
540                 }
541             }
542         )*
543     }
544 }
545
546 impl_binder_encode_decode! {
547     &'tcx ty::List<Ty<'tcx>>,
548     ty::FnSig<'tcx>,
549     ty::Predicate<'tcx>,
550     ty::TraitPredicate<'tcx>,
551     ty::ExistentialPredicate<'tcx>,
552     ty::TraitRef<'tcx>,
553     Vec<ty::GeneratorInteriorTypeCause<'tcx>>,
554     ty::ExistentialTraitRef<'tcx>,
555 }