2 * Methods for the various MIR types. These are intended for use after
3 * building is complete.
7 use crate::ty::{self, Ty, TyCtxt};
9 use rustc_target::abi::VariantIdx;
11 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)]
12 pub struct PlaceTy<'tcx> {
14 /// Downcast to a particular variant of an enum or a generator, if included.
15 pub variant_index: Option<VariantIdx>,
18 // At least on 64 bit systems, `PlaceTy` should not be larger than two or three pointers.
19 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
20 static_assert_size!(PlaceTy<'_>, 16);
22 impl<'tcx> PlaceTy<'tcx> {
24 pub fn from_ty(ty: Ty<'tcx>) -> PlaceTy<'tcx> {
25 PlaceTy { ty, variant_index: None }
28 /// `place_ty.field_ty(tcx, f)` computes the type at a given field
29 /// of a record or enum-variant. (Most clients of `PlaceTy` can
30 /// instead just extract the relevant type directly from their
31 /// `PlaceElem`, but some instances of `ProjectionElem<V, T>` do
32 /// not carry a `Ty` for `T`.)
34 /// Note that the resulting type has not been normalized.
35 #[instrument(level = "debug", skip(tcx), ret)]
36 pub fn field_ty(self, tcx: TyCtxt<'tcx>, f: Field) -> Ty<'tcx> {
37 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.variant(variant_index)
46 let field_def = &variant_def.fields[f.index()];
47 field_def.ty(tcx, substs)
49 ty::Tuple(tys) => tys[f.index()],
50 _ => bug!("extracting field of non-tuple non-adt: {:?}", self),
54 /// Convenience wrapper around `projection_ty_core` for
55 /// `PlaceElem`, where we can just use the `Ty` that is already
56 /// stored inline on field projection elems.
57 pub fn projection_ty(self, tcx: TyCtxt<'tcx>, elem: PlaceElem<'tcx>) -> PlaceTy<'tcx> {
58 self.projection_ty_core(tcx, ty::ParamEnv::empty(), &elem, |_, _, ty| ty, |_, ty| ty)
61 /// `place_ty.projection_ty_core(tcx, elem, |...| { ... })`
62 /// projects `place_ty` onto `elem`, returning the appropriate
63 /// `Ty` or downcast variant corresponding to that projection.
64 /// The `handle_field` callback must map a `Field` to its `Ty`,
65 /// (which should be trivial when `T` = `Ty`).
66 pub fn projection_ty_core<V, T>(
69 param_env: ty::ParamEnv<'tcx>,
70 elem: &ProjectionElem<V, T>,
71 mut handle_field: impl FnMut(&Self, Field, T) -> Ty<'tcx>,
72 mut handle_opaque_cast: impl FnMut(&Self, T) -> Ty<'tcx>,
76 T: ::std::fmt::Debug + Copy,
78 if self.variant_index.is_some() && !matches!(elem, ProjectionElem::Field(..)) {
79 bug!("cannot use non field projection on downcasted place")
81 let answer = match *elem {
82 ProjectionElem::Deref => {
87 bug!("deref projection of non-dereferenceable ty {:?}", self)
92 ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. } => {
93 PlaceTy::from_ty(self.ty.builtin_index().unwrap())
95 ProjectionElem::Subslice { from, to, from_end } => {
96 PlaceTy::from_ty(match self.ty.kind() {
97 ty::Slice(..) => self.ty,
98 ty::Array(inner, _) if !from_end => tcx.mk_array(*inner, (to - from) as u64),
99 ty::Array(inner, size) if from_end => {
100 let size = size.eval_usize(tcx, param_env);
101 let len = size - (from as u64) - (to as u64);
102 tcx.mk_array(*inner, len)
104 _ => bug!("cannot subslice non-array type: `{:?}`", self),
107 ProjectionElem::Downcast(_name, index) => {
108 PlaceTy { ty: self.ty, variant_index: Some(index) }
110 ProjectionElem::Field(f, fty) => PlaceTy::from_ty(handle_field(&self, f, fty)),
111 ProjectionElem::OpaqueCast(ty) => PlaceTy::from_ty(handle_opaque_cast(&self, ty)),
113 debug!("projection_ty self: {:?} elem: {:?} yields: {:?}", self, elem, answer);
118 impl<'tcx> Place<'tcx> {
121 projection: &[PlaceElem<'tcx>],
126 D: HasLocalDecls<'tcx>,
130 .fold(PlaceTy::from_ty(local_decls.local_decls()[local].ty), |place_ty, &elem| {
131 place_ty.projection_ty(tcx, elem)
135 pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>
137 D: HasLocalDecls<'tcx>,
139 Place::ty_from(self.local, &self.projection, local_decls, tcx)
143 impl<'tcx> PlaceRef<'tcx> {
144 pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>
146 D: HasLocalDecls<'tcx>,
148 Place::ty_from(self.local, &self.projection, local_decls, tcx)
152 pub enum RvalueInitializationState {
157 impl<'tcx> Rvalue<'tcx> {
158 pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
160 D: HasLocalDecls<'tcx>,
163 Rvalue::Use(ref operand) => operand.ty(local_decls, tcx),
164 Rvalue::Repeat(ref operand, count) => {
165 tcx.mk_ty(ty::Array(operand.ty(local_decls, tcx), count))
167 Rvalue::ThreadLocalRef(did) => {
168 let static_ty = tcx.type_of(did);
169 if tcx.is_mutable_static(did) {
170 tcx.mk_mut_ptr(static_ty)
171 } else if tcx.is_foreign_item(did) {
172 tcx.mk_imm_ptr(static_ty)
174 // FIXME: These things don't *really* have 'static lifetime.
175 tcx.mk_imm_ref(tcx.lifetimes.re_static, static_ty)
178 Rvalue::Ref(reg, bk, ref place) => {
179 let place_ty = place.ty(local_decls, tcx).ty;
180 tcx.mk_ref(reg, ty::TypeAndMut { ty: place_ty, mutbl: bk.to_mutbl_lossy() })
182 Rvalue::AddressOf(mutability, ref place) => {
183 let place_ty = place.ty(local_decls, tcx).ty;
184 tcx.mk_ptr(ty::TypeAndMut { ty: place_ty, mutbl: mutability })
186 Rvalue::Len(..) => tcx.types.usize,
187 Rvalue::Cast(.., ty) => ty,
188 Rvalue::BinaryOp(op, box (ref lhs, ref rhs)) => {
189 let lhs_ty = lhs.ty(local_decls, tcx);
190 let rhs_ty = rhs.ty(local_decls, tcx);
191 op.ty(tcx, lhs_ty, rhs_ty)
193 Rvalue::CheckedBinaryOp(op, box (ref lhs, ref rhs)) => {
194 let lhs_ty = lhs.ty(local_decls, tcx);
195 let rhs_ty = rhs.ty(local_decls, tcx);
196 let ty = op.ty(tcx, lhs_ty, rhs_ty);
197 tcx.intern_tup(&[ty, tcx.types.bool])
199 Rvalue::UnaryOp(UnOp::Not | UnOp::Neg, ref operand) => operand.ty(local_decls, tcx),
200 Rvalue::Discriminant(ref place) => place.ty(local_decls, tcx).ty.discriminant_ty(tcx),
201 Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, _) => tcx.types.usize,
202 Rvalue::Aggregate(ref ak, ref ops) => match **ak {
203 AggregateKind::Array(ty) => tcx.mk_array(ty, ops.len() as u64),
204 AggregateKind::Tuple => tcx.mk_tup(ops.iter().map(|op| op.ty(local_decls, tcx))),
205 AggregateKind::Adt(did, _, substs, _, _) => {
206 tcx.bound_type_of(did).subst(tcx, substs)
208 AggregateKind::Closure(did, substs) => tcx.mk_closure(did.to_def_id(), substs),
209 AggregateKind::Generator(did, substs, movability) => {
210 tcx.mk_generator(did.to_def_id(), substs, movability)
213 Rvalue::ShallowInitBox(_, ty) => tcx.mk_box(ty),
214 Rvalue::CopyForDeref(ref place) => place.ty(local_decls, tcx).ty,
219 /// Returns `true` if this rvalue is deeply initialized (most rvalues) or
220 /// whether its only shallowly initialized (`Rvalue::Box`).
221 pub fn initialization_state(&self) -> RvalueInitializationState {
223 Rvalue::ShallowInitBox(_, _) => RvalueInitializationState::Shallow,
224 _ => RvalueInitializationState::Deep,
229 impl<'tcx> Operand<'tcx> {
230 pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
232 D: HasLocalDecls<'tcx>,
235 &Operand::Copy(ref l) | &Operand::Move(ref l) => l.ty(local_decls, tcx).ty,
236 Operand::Constant(c) => c.literal.ty(),
242 pub fn ty(&self, tcx: TyCtxt<'tcx>, lhs_ty: Ty<'tcx>, rhs_ty: Ty<'tcx>) -> Ty<'tcx> {
243 // FIXME: handle SIMD correctly
253 // these should be integers or floats of the same size.
254 assert_eq!(lhs_ty, rhs_ty);
257 &BinOp::Shl | &BinOp::Shr | &BinOp::Offset => {
258 lhs_ty // lhs_ty can be != rhs_ty
260 &BinOp::Eq | &BinOp::Lt | &BinOp::Le | &BinOp::Ne | &BinOp::Ge | &BinOp::Gt => {
268 pub fn to_mutbl_lossy(self) -> hir::Mutability {
270 BorrowKind::Mut { .. } => hir::Mutability::Mut,
271 BorrowKind::Shared => hir::Mutability::Not,
273 // We have no type corresponding to a unique imm borrow, so
274 // use `&mut`. It gives all the capabilities of a `&uniq`
275 // and hence is a safe "over approximation".
276 BorrowKind::Unique => hir::Mutability::Mut,
278 // We have no type corresponding to a shallow borrow, so use
279 // `&` as an approximation.
280 BorrowKind::Shallow => hir::Mutability::Not,
286 pub fn to_hir_binop(self) -> hir::BinOpKind {
288 BinOp::Add => hir::BinOpKind::Add,
289 BinOp::Sub => hir::BinOpKind::Sub,
290 BinOp::Mul => hir::BinOpKind::Mul,
291 BinOp::Div => hir::BinOpKind::Div,
292 BinOp::Rem => hir::BinOpKind::Rem,
293 BinOp::BitXor => hir::BinOpKind::BitXor,
294 BinOp::BitAnd => hir::BinOpKind::BitAnd,
295 BinOp::BitOr => hir::BinOpKind::BitOr,
296 BinOp::Shl => hir::BinOpKind::Shl,
297 BinOp::Shr => hir::BinOpKind::Shr,
298 BinOp::Eq => hir::BinOpKind::Eq,
299 BinOp::Ne => hir::BinOpKind::Ne,
300 BinOp::Lt => hir::BinOpKind::Lt,
301 BinOp::Gt => hir::BinOpKind::Gt,
302 BinOp::Le => hir::BinOpKind::Le,
303 BinOp::Ge => hir::BinOpKind::Ge,
304 BinOp::Offset => unreachable!(),