]> git.lizzy.rs Git - rust.git/blobdiff - src/librustc_mir/const_eval.rs
Make `may_normalize` explicit in the type system
[rust.git] / src / librustc_mir / const_eval.rs
index f83a930353b7386ea610ab5791932af921d1b764..2f8e3189d12e969f5394031128f4a2def3fe2b90 100644 (file)
@@ -11,7 +11,7 @@
 use rustc::mir::interpret::{ConstEvalErr, ErrorHandled};
 use rustc::mir;
 use rustc::ty::{self, TyCtxt, query::TyCtxtAt};
-use rustc::ty::layout::{self, LayoutOf, TyLayout, VariantIdx};
+use rustc::ty::layout::{self, LayoutOf, VariantIdx};
 use rustc::ty::subst::Subst;
 use rustc::traits::Reveal;
 use rustc_data_structures::fx::FxHashMap;
@@ -21,7 +21,8 @@
 use syntax::source_map::{Span, DUMMY_SP};
 
 use crate::interpret::{self,
-    PlaceTy, MPlaceTy, MemPlace, OpTy, Operand, Immediate, Scalar, RawConst, ConstValue, Pointer,
+    PlaceTy, MPlaceTy, MemPlace, OpTy, ImmTy, Immediate, Scalar, Pointer,
+    RawConst, ConstValue,
     EvalResult, EvalError, EvalErrorKind, GlobalId, EvalContext, StackPopCleanup,
     Allocation, AllocId, MemoryKind,
     snapshot, RefTracking,
@@ -38,7 +39,7 @@
 /// `simd_shuffle` and const patterns in match arms.
 ///
 /// The function containing the `match` that is currently being analyzed may have generic bounds
-/// that inform us about the generic bounds of the constant. E.g. using an associated constant
+/// that inform us about the generic bounds of the constant. E.g., using an associated constant
 /// of a function's generic parameter will require knowledge about the bounds on the generic
 /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
 pub(crate) fn mk_eval_cx<'a, 'mir, 'tcx>(
@@ -61,59 +62,51 @@ pub(crate) fn eval_promoted<'a, 'mir, 'tcx>(
     eval_body_using_ecx(&mut ecx, cid, Some(mir), param_env)
 }
 
-// FIXME: These two conversion functions are bad hacks.  We should just always use allocations.
-pub fn op_to_const<'tcx>(
+fn mplace_to_const<'tcx>(
+    ecx: &CompileTimeEvalContext<'_, '_, 'tcx>,
+    mplace: MPlaceTy<'tcx>,
+) -> EvalResult<'tcx, ty::Const<'tcx>> {
+    let MemPlace { ptr, align, meta } = *mplace;
+    // extract alloc-offset pair
+    assert!(meta.is_none());
+    let ptr = ptr.to_ptr()?;
+    let alloc = ecx.memory.get(ptr.alloc_id)?;
+    assert!(alloc.align >= align);
+    assert!(alloc.bytes.len() as u64 - ptr.offset.bytes() >= mplace.layout.size.bytes());
+    let mut alloc = alloc.clone();
+    alloc.align = align;
+    // FIXME shouldn't it be the case that `mark_static_initialized` has already
+    // interned this?  I thought that is the entire point of that `FinishStatic` stuff?
+    let alloc = ecx.tcx.intern_const_alloc(alloc);
+    let val = ConstValue::ByRef(ptr, alloc);
+    Ok(ty::Const { val, ty: mplace.layout.ty })
+}
+
+fn op_to_const<'tcx>(
     ecx: &CompileTimeEvalContext<'_, '_, 'tcx>,
     op: OpTy<'tcx>,
-    may_normalize: bool,
 ) -> EvalResult<'tcx, ty::Const<'tcx>> {
     // We do not normalize just any data.  Only scalar layout and slices.
-    let normalize = may_normalize
-        && match op.layout.abi {
-            layout::Abi::Scalar(..) => true,
-            layout::Abi::ScalarPair(..) => op.layout.ty.is_slice(),
-            _ => false,
-        };
+    let normalize = match op.layout.abi {
+        layout::Abi::Scalar(..) => true,
+        layout::Abi::ScalarPair(..) => op.layout.ty.is_slice(),
+        _ => false,
+    };
     let normalized_op = if normalize {
-        ecx.try_read_immediate(op)?
+        Err(*ecx.read_immediate(op).expect("normalization works on validated constants"))
     } else {
-        match op.op {
-            Operand::Indirect(mplace) => Err(mplace),
-            Operand::Immediate(val) => Ok(val)
-        }
+        op.try_as_mplace()
     };
     let val = match normalized_op {
-        Err(MemPlace { ptr, align, meta }) => {
-            // extract alloc-offset pair
-            assert!(meta.is_none());
-            let ptr = ptr.to_ptr()?;
-            let alloc = ecx.memory.get(ptr.alloc_id)?;
-            assert!(alloc.align >= align);
-            assert!(alloc.bytes.len() as u64 - ptr.offset.bytes() >= op.layout.size.bytes());
-            let mut alloc = alloc.clone();
-            alloc.align = align;
-            // FIXME shouldn't it be the case that `mark_static_initialized` has already
-            // interned this?  I thought that is the entire point of that `FinishStatic` stuff?
-            let alloc = ecx.tcx.intern_const_alloc(alloc);
-            ConstValue::ByRef(ptr.alloc_id, alloc, ptr.offset)
-        },
-        Ok(Immediate::Scalar(x)) =>
+        Ok(mplace) => return mplace_to_const(ecx, mplace),
+        Err(Immediate::Scalar(x)) =>
             ConstValue::Scalar(x.not_undef()?),
-        Ok(Immediate::ScalarPair(a, b)) =>
+        Err(Immediate::ScalarPair(a, b)) =>
             ConstValue::Slice(a.not_undef()?, b.to_usize(ecx)?),
     };
     Ok(ty::Const { val, ty: op.layout.ty })
 }
 
-pub fn lazy_const_to_op<'tcx>(
-    ecx: &CompileTimeEvalContext<'_, '_, 'tcx>,
-    cnst: ty::LazyConst<'tcx>,
-    ty: ty::Ty<'tcx>,
-) -> EvalResult<'tcx, OpTy<'tcx>> {
-    let op = ecx.const_value_to_op(cnst)?;
-    Ok(OpTy { op, layout: ecx.layout_of(ty)? })
-}
-
 fn eval_body_and_ecx<'a, 'mir, 'tcx>(
     tcx: TyCtxt<'a, 'tcx, 'tcx>,
     cid: GlobalId<'tcx>,
@@ -190,7 +183,7 @@ enum ConstEvalError {
 }
 
 impl fmt::Display for ConstEvalError {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         use self::ConstEvalError::*;
         match *self {
             NeedsRfc(ref msg) => {
@@ -388,10 +381,8 @@ fn call_intrinsic(
     fn ptr_op(
         _ecx: &EvalContext<'a, 'mir, 'tcx, Self>,
         _bin_op: mir::BinOp,
-        _left: Scalar,
-        _left_layout: TyLayout<'tcx>,
-        _right: Scalar,
-        _right_layout: TyLayout<'tcx>,
+        _left: ImmTy<'tcx>,
+        _right: ImmTy<'tcx>,
     ) -> EvalResult<'tcx, (Scalar, bool)> {
         Err(
             ConstEvalError::NeedsRfc("pointer arithmetic or comparison".to_string()).into(),
@@ -464,7 +455,7 @@ fn stack_push(
         Ok(())
     }
 
-    /// Called immediately before a stack frame gets popped
+    /// Called immediately before a stack frame gets popped.
     #[inline(always)]
     fn stack_pop(
         _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
@@ -474,7 +465,7 @@ fn stack_pop(
     }
 }
 
-/// Project to a field of a (variant of a) const
+/// Projects to a field of a (variant of a) const.
 pub fn const_field<'a, 'tcx>(
     tcx: TyCtxt<'a, 'tcx, 'tcx>,
     param_env: ty::ParamEnv<'tcx>,
@@ -486,7 +477,7 @@ pub fn const_field<'a, 'tcx>(
     let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
     let result = (|| {
         // get the operand again
-        let op = lazy_const_to_op(&ecx, ty::LazyConst::Evaluated(value), value.ty)?;
+        let op = ecx.const_to_op(value, None)?;
         // downcast
         let down = match variant {
             None => op,
@@ -496,7 +487,7 @@ pub fn const_field<'a, 'tcx>(
         let field = ecx.operand_field(down, field.index() as u64)?;
         // and finally move back to the const world, always normalizing because
         // this is not called for statics.
-        op_to_const(&ecx, field, true)
+        op_to_const(&ecx, field)
     })();
     result.map_err(|error| {
         let err = error_to_const_error(&ecx, error);
@@ -512,7 +503,7 @@ pub fn const_variant_index<'a, 'tcx>(
 ) -> EvalResult<'tcx, VariantIdx> {
     trace!("const_variant_index: {:?}", val);
     let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
-    let op = lazy_const_to_op(&ecx, ty::LazyConst::Evaluated(val), val.ty)?;
+    let op = ecx.const_to_op(val, None)?;
     Ok(ecx.read_discriminant(op)?.1)
 }
 
@@ -533,22 +524,23 @@ fn validate_and_turn_into_const<'a, 'tcx>(
     let cid = key.value;
     let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env);
     let val = (|| {
-        let op = ecx.raw_const_to_mplace(constant)?.into();
-        // FIXME: Once the visitor infrastructure landed, change validation to
-        // work directly on `MPlaceTy`.
-        let mut ref_tracking = RefTracking::new(op);
-        while let Some((op, path)) = ref_tracking.todo.pop() {
+        let mplace = ecx.raw_const_to_mplace(constant)?;
+        let mut ref_tracking = RefTracking::new(mplace);
+        while let Some((mplace, path)) = ref_tracking.todo.pop() {
             ecx.validate_operand(
-                op,
+                mplace.into(),
                 path,
                 Some(&mut ref_tracking),
-                /* const_mode */ true,
+                true, // const mode
             )?;
         }
-        // Now that we validated, turn this into a proper constant
+        // Now that we validated, turn this into a proper constant.
         let def_id = cid.instance.def.def_id();
-        let normalize = tcx.is_static(def_id).is_none() && cid.promoted.is_none();
-        op_to_const(&ecx, op, normalize)
+        if tcx.is_static(def_id).is_some() || cid.promoted.is_some() {
+            mplace_to_const(&ecx, mplace)
+        } else {
+            op_to_const(&ecx, mplace.into())
+        }
     })();
 
     val.map_err(|error| {