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