]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/tcx.rs
Rollup merge of #67880 - lbonn:fix/multi-substs, r=petrochenkov
[rust.git] / src / librustc / mir / tcx.rs
1 /*!
2  * Methods for the various MIR types. These are intended for use after
3  * building is complete.
4  */
5
6 use crate::mir::*;
7 use crate::ty::layout::VariantIdx;
8 use crate::ty::subst::Subst;
9 use crate::ty::util::IntTypeExt;
10 use crate::ty::{self, Ty, TyCtxt};
11 use rustc_hir as hir;
12
13 #[derive(Copy, Clone, Debug, TypeFoldable)]
14 pub struct PlaceTy<'tcx> {
15     pub ty: Ty<'tcx>,
16     /// Downcast to a particular variant of an enum, if included.
17     pub variant_index: Option<VariantIdx>,
18 }
19
20 // At least on 64 bit systems, `PlaceTy` should not be larger than two or three pointers.
21 #[cfg(target_arch = "x86_64")]
22 static_assert_size!(PlaceTy<'_>, 16);
23
24 impl<'tcx> PlaceTy<'tcx> {
25     pub fn from_ty(ty: Ty<'tcx>) -> PlaceTy<'tcx> {
26         PlaceTy { ty, variant_index: None }
27     }
28
29     /// `place_ty.field_ty(tcx, f)` computes the type at a given field
30     /// of a record or enum-variant. (Most clients of `PlaceTy` can
31     /// instead just extract the relevant type directly from their
32     /// `PlaceElem`, but some instances of `ProjectionElem<V, T>` do
33     /// not carry a `Ty` for `T`.)
34     ///
35     /// Note that the resulting type has not been normalized.
36     pub fn field_ty(self, tcx: TyCtxt<'tcx>, f: &Field) -> Ty<'tcx> {
37         let answer = match self.ty.kind {
38             ty::Adt(adt_def, substs) => {
39                 let variant_def = match self.variant_index {
40                     None => adt_def.non_enum_variant(),
41                     Some(variant_index) => {
42                         assert!(adt_def.is_enum());
43                         &adt_def.variants[variant_index]
44                     }
45                 };
46                 let field_def = &variant_def.fields[f.index()];
47                 field_def.ty(tcx, substs)
48             }
49             ty::Tuple(ref tys) => tys[f.index()].expect_ty(),
50             _ => bug!("extracting field of non-tuple non-adt: {:?}", self),
51         };
52         debug!("field_ty self: {:?} f: {:?} yields: {:?}", self, f, answer);
53         answer
54     }
55
56     /// Convenience wrapper around `projection_ty_core` for
57     /// `PlaceElem`, where we can just use the `Ty` that is already
58     /// stored inline on field projection elems.
59     pub fn projection_ty(self, tcx: TyCtxt<'tcx>, elem: &PlaceElem<'tcx>) -> PlaceTy<'tcx> {
60         self.projection_ty_core(tcx, ty::ParamEnv::empty(), elem, |_, _, ty| ty)
61     }
62
63     /// `place_ty.projection_ty_core(tcx, elem, |...| { ... })`
64     /// projects `place_ty` onto `elem`, returning the appropriate
65     /// `Ty` or downcast variant corresponding to that projection.
66     /// The `handle_field` callback must map a `Field` to its `Ty`,
67     /// (which should be trivial when `T` = `Ty`).
68     pub fn projection_ty_core<V, T>(
69         self,
70         tcx: TyCtxt<'tcx>,
71         param_env: ty::ParamEnv<'tcx>,
72         elem: &ProjectionElem<V, T>,
73         mut handle_field: impl FnMut(&Self, &Field, &T) -> Ty<'tcx>,
74     ) -> PlaceTy<'tcx>
75     where
76         V: ::std::fmt::Debug,
77         T: ::std::fmt::Debug,
78     {
79         let answer = match *elem {
80             ProjectionElem::Deref => {
81                 let ty = self
82                     .ty
83                     .builtin_deref(true)
84                     .unwrap_or_else(|| {
85                         bug!("deref projection of non-dereferenceable ty {:?}", self)
86                     })
87                     .ty;
88                 PlaceTy::from_ty(ty)
89             }
90             ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. } => {
91                 PlaceTy::from_ty(self.ty.builtin_index().unwrap())
92             }
93             ProjectionElem::Subslice { from, to, from_end } => {
94                 PlaceTy::from_ty(match self.ty.kind {
95                     ty::Slice(..) => self.ty,
96                     ty::Array(inner, _) if !from_end => tcx.mk_array(inner, (to - from) as u64),
97                     ty::Array(inner, size) if from_end => {
98                         let size = size.eval_usize(tcx, param_env);
99                         let len = size - (from as u64) - (to as u64);
100                         tcx.mk_array(inner, len)
101                     }
102                     _ => bug!("cannot subslice non-array type: `{:?}`", self),
103                 })
104             }
105             ProjectionElem::Downcast(_name, index) => {
106                 PlaceTy { ty: self.ty, variant_index: Some(index) }
107             }
108             ProjectionElem::Field(ref f, ref fty) => PlaceTy::from_ty(handle_field(&self, f, fty)),
109         };
110         debug!("projection_ty self: {:?} elem: {:?} yields: {:?}", self, elem, answer);
111         answer
112     }
113 }
114
115 impl<'tcx> Place<'tcx> {
116     pub fn ty_from<D>(
117         base: &PlaceBase<'tcx>,
118         projection: &[PlaceElem<'tcx>],
119         local_decls: &D,
120         tcx: TyCtxt<'tcx>,
121     ) -> PlaceTy<'tcx>
122     where
123         D: HasLocalDecls<'tcx>,
124     {
125         projection
126             .iter()
127             .fold(base.ty(local_decls), |place_ty, elem| place_ty.projection_ty(tcx, elem))
128     }
129
130     pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>
131     where
132         D: HasLocalDecls<'tcx>,
133     {
134         Place::ty_from(&self.base, &self.projection, local_decls, tcx)
135     }
136 }
137
138 impl<'tcx> PlaceBase<'tcx> {
139     pub fn ty<D>(&self, local_decls: &D) -> PlaceTy<'tcx>
140     where
141         D: HasLocalDecls<'tcx>,
142     {
143         match self {
144             PlaceBase::Local(index) => PlaceTy::from_ty(local_decls.local_decls()[*index].ty),
145             PlaceBase::Static(data) => PlaceTy::from_ty(data.ty),
146         }
147     }
148 }
149
150 pub enum RvalueInitializationState {
151     Shallow,
152     Deep,
153 }
154
155 impl<'tcx> Rvalue<'tcx> {
156     pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
157     where
158         D: HasLocalDecls<'tcx>,
159     {
160         match *self {
161             Rvalue::Use(ref operand) => operand.ty(local_decls, tcx),
162             Rvalue::Repeat(ref operand, count) => tcx.mk_array(operand.ty(local_decls, tcx), count),
163             Rvalue::Ref(reg, bk, ref place) => {
164                 let place_ty = place.ty(local_decls, tcx).ty;
165                 tcx.mk_ref(reg, ty::TypeAndMut { ty: place_ty, mutbl: bk.to_mutbl_lossy() })
166             }
167             Rvalue::AddressOf(mutability, ref place) => {
168                 let place_ty = place.ty(local_decls, tcx).ty;
169                 tcx.mk_ptr(ty::TypeAndMut { ty: place_ty, mutbl: mutability.into() })
170             }
171             Rvalue::Len(..) => tcx.types.usize,
172             Rvalue::Cast(.., ty) => ty,
173             Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
174                 let lhs_ty = lhs.ty(local_decls, tcx);
175                 let rhs_ty = rhs.ty(local_decls, tcx);
176                 op.ty(tcx, lhs_ty, rhs_ty)
177             }
178             Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
179                 let lhs_ty = lhs.ty(local_decls, tcx);
180                 let rhs_ty = rhs.ty(local_decls, tcx);
181                 let ty = op.ty(tcx, lhs_ty, rhs_ty);
182                 tcx.intern_tup(&[ty, tcx.types.bool])
183             }
184             Rvalue::UnaryOp(UnOp::Not, ref operand) | Rvalue::UnaryOp(UnOp::Neg, ref operand) => {
185                 operand.ty(local_decls, tcx)
186             }
187             Rvalue::Discriminant(ref place) => {
188                 let ty = place.ty(local_decls, tcx).ty;
189                 match ty.kind {
190                     ty::Adt(adt_def, _) => adt_def.repr.discr_type().to_ty(tcx),
191                     ty::Generator(_, substs, _) => substs.as_generator().discr_ty(tcx),
192                     _ => {
193                         // This can only be `0`, for now, so `u8` will suffice.
194                         tcx.types.u8
195                     }
196                 }
197             }
198             Rvalue::NullaryOp(NullOp::Box, t) => tcx.mk_box(t),
199             Rvalue::NullaryOp(NullOp::SizeOf, _) => tcx.types.usize,
200             Rvalue::Aggregate(ref ak, ref ops) => match **ak {
201                 AggregateKind::Array(ty) => tcx.mk_array(ty, ops.len() as u64),
202                 AggregateKind::Tuple => tcx.mk_tup(ops.iter().map(|op| op.ty(local_decls, tcx))),
203                 AggregateKind::Adt(def, _, substs, _, _) => tcx.type_of(def.did).subst(tcx, substs),
204                 AggregateKind::Closure(did, substs) => tcx.mk_closure(did, substs),
205                 AggregateKind::Generator(did, substs, movability) => {
206                     tcx.mk_generator(did, substs, movability)
207                 }
208             },
209         }
210     }
211
212     #[inline]
213     /// Returns `true` if this rvalue is deeply initialized (most rvalues) or
214     /// whether its only shallowly initialized (`Rvalue::Box`).
215     pub fn initialization_state(&self) -> RvalueInitializationState {
216         match *self {
217             Rvalue::NullaryOp(NullOp::Box, _) => RvalueInitializationState::Shallow,
218             _ => RvalueInitializationState::Deep,
219         }
220     }
221 }
222
223 impl<'tcx> Operand<'tcx> {
224     pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
225     where
226         D: HasLocalDecls<'tcx>,
227     {
228         match self {
229             &Operand::Copy(ref l) | &Operand::Move(ref l) => l.ty(local_decls, tcx).ty,
230             &Operand::Constant(ref c) => c.literal.ty,
231         }
232     }
233 }
234
235 impl<'tcx> BinOp {
236     pub fn ty(&self, tcx: TyCtxt<'tcx>, lhs_ty: Ty<'tcx>, rhs_ty: Ty<'tcx>) -> Ty<'tcx> {
237         // FIXME: handle SIMD correctly
238         match self {
239             &BinOp::Add
240             | &BinOp::Sub
241             | &BinOp::Mul
242             | &BinOp::Div
243             | &BinOp::Rem
244             | &BinOp::BitXor
245             | &BinOp::BitAnd
246             | &BinOp::BitOr => {
247                 // these should be integers or floats of the same size.
248                 assert_eq!(lhs_ty, rhs_ty);
249                 lhs_ty
250             }
251             &BinOp::Shl | &BinOp::Shr | &BinOp::Offset => {
252                 lhs_ty // lhs_ty can be != rhs_ty
253             }
254             &BinOp::Eq | &BinOp::Lt | &BinOp::Le | &BinOp::Ne | &BinOp::Ge | &BinOp::Gt => {
255                 tcx.types.bool
256             }
257         }
258     }
259 }
260
261 impl BorrowKind {
262     pub fn to_mutbl_lossy(self) -> hir::Mutability {
263         match self {
264             BorrowKind::Mut { .. } => hir::Mutability::Mut,
265             BorrowKind::Shared => hir::Mutability::Not,
266
267             // We have no type corresponding to a unique imm borrow, so
268             // use `&mut`. It gives all the capabilities of an `&uniq`
269             // and hence is a safe "over approximation".
270             BorrowKind::Unique => hir::Mutability::Mut,
271
272             // We have no type corresponding to a shallow borrow, so use
273             // `&` as an approximation.
274             BorrowKind::Shallow => hir::Mutability::Not,
275         }
276     }
277 }
278
279 impl BinOp {
280     pub fn to_hir_binop(self) -> hir::BinOpKind {
281         match self {
282             BinOp::Add => hir::BinOpKind::Add,
283             BinOp::Sub => hir::BinOpKind::Sub,
284             BinOp::Mul => hir::BinOpKind::Mul,
285             BinOp::Div => hir::BinOpKind::Div,
286             BinOp::Rem => hir::BinOpKind::Rem,
287             BinOp::BitXor => hir::BinOpKind::BitXor,
288             BinOp::BitAnd => hir::BinOpKind::BitAnd,
289             BinOp::BitOr => hir::BinOpKind::BitOr,
290             BinOp::Shl => hir::BinOpKind::Shl,
291             BinOp::Shr => hir::BinOpKind::Shr,
292             BinOp::Eq => hir::BinOpKind::Eq,
293             BinOp::Ne => hir::BinOpKind::Ne,
294             BinOp::Lt => hir::BinOpKind::Lt,
295             BinOp::Gt => hir::BinOpKind::Gt,
296             BinOp::Le => hir::BinOpKind::Le,
297             BinOp::Ge => hir::BinOpKind::Ge,
298             BinOp::Offset => unreachable!(),
299         }
300     }
301 }