1 use std::collections::HashSet;
4 use rustc::hir::def_id::DefId;
5 use rustc::hir::map::definitions::DefPathData;
6 use rustc::middle::const_val::{ConstVal, ErrKind};
8 use rustc::ty::layout::{self, Size, Align, HasDataLayout, LayoutOf, TyLayout};
9 use rustc::ty::subst::{Subst, Substs};
10 use rustc::ty::{self, Ty, TyCtxt};
11 use rustc::ty::maps::TyCtxtAt;
12 use rustc_data_structures::indexed_vec::Idx;
13 use rustc::middle::const_val::FrameInfo;
14 use syntax::codemap::{self, Span};
15 use syntax::ast::Mutability;
16 use rustc::mir::interpret::{
17 GlobalId, Value, Pointer, PrimVal, PrimValKind,
18 EvalError, EvalResult, EvalErrorKind, MemoryPointer,
21 use super::{Place, PlaceExtra, Memory,
22 HasMemory, MemoryKind,
25 pub struct EvalContext<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'mir, 'tcx>> {
26 /// Stores the `Machine` instance.
29 /// The results of the type checker, from rustc.
30 pub tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
32 /// Bounds in scope for polymorphic evaluations.
33 pub param_env: ty::ParamEnv<'tcx>,
35 /// The virtual memory system.
36 pub memory: Memory<'a, 'mir, 'tcx, M>,
38 /// The virtual call stack.
39 pub(crate) stack: Vec<Frame<'mir, 'tcx>>,
41 /// The maximum number of stack frames allowed
42 pub(crate) stack_limit: usize,
44 /// The maximum number of terminators that may be evaluated.
45 /// This prevents infinite loops and huge computations from freezing up const eval.
46 /// Remove once halting problem is solved.
47 pub(crate) steps_remaining: usize,
51 pub struct Frame<'mir, 'tcx: 'mir> {
52 ////////////////////////////////////////////////////////////////////////////////
53 // Function and callsite information
54 ////////////////////////////////////////////////////////////////////////////////
55 /// The MIR for the function called on this frame.
56 pub mir: &'mir mir::Mir<'tcx>,
58 /// The def_id and substs of the current function
59 pub instance: ty::Instance<'tcx>,
61 /// The span of the call site.
62 pub span: codemap::Span,
64 ////////////////////////////////////////////////////////////////////////////////
65 // Return place and locals
66 ////////////////////////////////////////////////////////////////////////////////
67 /// The block to return to when returning from the current stack frame
68 pub return_to_block: StackPopCleanup,
70 /// The location where the result of the current stack frame should be written to.
71 pub return_place: Place,
73 /// The list of locals for this stack frame, stored in order as
74 /// `[arguments..., variables..., temporaries...]`. The locals are stored as `Option<Value>`s.
75 /// `None` represents a local that is currently dead, while a live local
76 /// can either directly contain `PrimVal` or refer to some part of an `Allocation`.
78 /// Before being initialized, arguments are `Value::ByVal(PrimVal::Undef)` and other locals are `None`.
79 pub locals: Vec<Option<Value>>,
81 ////////////////////////////////////////////////////////////////////////////////
82 // Current position within the function
83 ////////////////////////////////////////////////////////////////////////////////
84 /// The block that is currently executed (or will be executed after the above call stacks
86 pub block: mir::BasicBlock,
88 /// The index of the currently evaluated statement.
92 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
93 pub enum StackPopCleanup {
94 /// The stackframe existed to compute the initial value of a static/constant, make sure it
95 /// isn't modifyable afterwards in case of constants.
96 /// In case of `static mut`, mark the memory to ensure it's never marked as immutable through
97 /// references or deallocated
98 MarkStatic(Mutability),
99 /// A regular stackframe added due to a function call will need to get forwarded to the next
101 Goto(mir::BasicBlock),
102 /// The main function and diverging functions have nowhere to return to
106 #[derive(Copy, Clone, Debug)]
107 pub struct TyAndPacked<'tcx> {
112 #[derive(Copy, Clone, Debug)]
113 pub struct ValTy<'tcx> {
118 impl<'tcx> ValTy<'tcx> {
119 pub fn from(val: &ty::Const<'tcx>) -> Option<Self> {
121 ConstVal::Value(value) => Some(ValTy { value, ty: val.ty }),
122 ConstVal::Unevaluated { .. } => None,
127 impl<'tcx> ::std::ops::Deref for ValTy<'tcx> {
129 fn deref(&self) -> &Value {
134 impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for &'a EvalContext<'a, 'mir, 'tcx, M> {
136 fn data_layout(&self) -> &layout::TargetDataLayout {
137 &self.tcx.data_layout
141 impl<'c, 'b, 'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout
142 for &'c &'b mut EvalContext<'a, 'mir, 'tcx, M> {
144 fn data_layout(&self) -> &layout::TargetDataLayout {
145 &self.tcx.data_layout
149 impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> layout::HasTyCtxt<'tcx> for &'a EvalContext<'a, 'mir, 'tcx, M> {
151 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> {
156 impl<'c, 'b, 'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> layout::HasTyCtxt<'tcx>
157 for &'c &'b mut EvalContext<'a, 'mir, 'tcx, M> {
159 fn tcx<'d>(&'d self) -> TyCtxt<'d, 'tcx, 'tcx> {
164 impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> LayoutOf<Ty<'tcx>> for &'a EvalContext<'a, 'mir, 'tcx, M> {
165 type TyLayout = EvalResult<'tcx, TyLayout<'tcx>>;
167 fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
168 self.tcx.layout_of(self.param_env.and(ty))
169 .map_err(|layout| EvalErrorKind::Layout(layout).into())
173 impl<'c, 'b, 'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> LayoutOf<Ty<'tcx>>
174 for &'c &'b mut EvalContext<'a, 'mir, 'tcx, M> {
175 type TyLayout = EvalResult<'tcx, TyLayout<'tcx>>;
178 fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout {
179 (&**self).layout_of(ty)
183 impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
185 tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
186 param_env: ty::ParamEnv<'tcx>,
188 memory_data: M::MemoryData,
194 memory: Memory::new(tcx, memory_data),
196 stack_limit: tcx.sess.const_eval_stack_frame_limit.get(),
197 steps_remaining: tcx.sess.const_eval_step_limit.get(),
201 pub fn alloc_ptr(&mut self, ty: Ty<'tcx>) -> EvalResult<'tcx, MemoryPointer> {
202 let layout = self.layout_of(ty)?;
203 assert!(!layout.is_unsized(), "cannot alloc memory for unsized type");
205 let size = layout.size.bytes();
206 self.memory.allocate(size, layout.align, Some(MemoryKind::Stack))
209 pub fn memory(&self) -> &Memory<'a, 'mir, 'tcx, M> {
213 pub fn memory_mut(&mut self) -> &mut Memory<'a, 'mir, 'tcx, M> {
217 pub fn stack(&self) -> &[Frame<'mir, 'tcx>] {
222 pub fn cur_frame(&self) -> usize {
223 assert!(self.stack.len() > 0);
227 pub fn str_to_value(&mut self, s: &str) -> EvalResult<'tcx, Value> {
228 let ptr = self.memory.allocate_cached(s.as_bytes());
231 PrimVal::from_u128(s.len() as u128),
235 pub(super) fn const_to_value(&self, const_val: &ConstVal<'tcx>, ty: Ty<'tcx>) -> EvalResult<'tcx, Value> {
237 ConstVal::Unevaluated(def_id, substs) => {
238 let instance = self.resolve(def_id, substs)?;
239 self.read_global_as_value(GlobalId {
244 ConstVal::Value(val) => Ok(val),
248 pub(super) fn resolve(&self, def_id: DefId, substs: &'tcx Substs<'tcx>) -> EvalResult<'tcx, ty::Instance<'tcx>> {
249 trace!("resolve: {:?}, {:#?}", def_id, substs);
250 trace!("substs: {:#?}", self.substs());
251 trace!("param_env: {:#?}", self.param_env);
252 let substs = self.tcx.trans_apply_param_substs_env(self.substs(), self.param_env, &substs);
253 ty::Instance::resolve(
258 ).ok_or(EvalErrorKind::TypeckError.into()) // turn error prop into a panic to expose associated type in const issue
261 pub(super) fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
262 ty.is_sized(self.tcx, self.param_env)
267 instance: ty::InstanceDef<'tcx>,
268 ) -> EvalResult<'tcx, &'tcx mir::Mir<'tcx>> {
269 // do not continue if typeck errors occurred (can only occur in local crate)
270 let did = instance.def_id();
271 if did.is_local() && self.tcx.has_typeck_tables(did) && self.tcx.typeck_tables_of(did).tainted_by_errors {
272 return err!(TypeckError);
274 trace!("load mir {:?}", instance);
276 ty::InstanceDef::Item(def_id) => {
277 self.tcx.maybe_optimized_mir(def_id).ok_or_else(|| {
278 EvalErrorKind::NoMirFor(self.tcx.item_path_str(def_id)).into()
281 _ => Ok(self.tcx.instance_mir(instance)),
285 pub fn monomorphize(&self, ty: Ty<'tcx>, substs: &'tcx Substs<'tcx>) -> Ty<'tcx> {
286 // miri doesn't care about lifetimes, and will choke on some crazy ones
287 // let's simply get rid of them
288 let without_lifetimes = self.tcx.erase_regions(&ty);
289 let substituted = without_lifetimes.subst(*self.tcx, substs);
290 let substituted = self.tcx.fully_normalize_monormophic_ty(&substituted);
294 /// Return the size and aligment of the value at the given type.
295 /// Note that the value does not matter if the type is sized. For unsized types,
296 /// the value has to be a fat pointer, and we only care about the "extra" data in it.
297 pub fn size_and_align_of_dst(
301 ) -> EvalResult<'tcx, (Size, Align)> {
302 let layout = self.layout_of(ty)?;
303 if !layout.is_unsized() {
304 Ok(layout.size_and_align())
307 ty::TyAdt(..) | ty::TyTuple(..) => {
308 // First get the size of all statically known fields.
309 // Don't use type_of::sizing_type_of because that expects t to be sized,
310 // and it also rounds up to alignment, which we want to avoid,
311 // as the unsized field's alignment could be smaller.
312 assert!(!ty.is_simd());
313 debug!("DST {} layout: {:?}", ty, layout);
315 let sized_size = layout.fields.offset(layout.fields.count() - 1);
316 let sized_align = layout.align;
318 "DST {} statically sized prefix size: {:?} align: {:?}",
324 // Recurse to get the size of the dynamically sized field (must be
326 let field_ty = layout.field(&self, layout.fields.count() - 1)?.ty;
327 let (unsized_size, unsized_align) =
328 self.size_and_align_of_dst(field_ty, value)?;
330 // FIXME (#26403, #27023): We should be adding padding
331 // to `sized_size` (to accommodate the `unsized_align`
332 // required of the unsized field that follows) before
333 // summing it with `sized_size`. (Note that since #26403
334 // is unfixed, we do not yet add the necessary padding
335 // here. But this is where the add would go.)
337 // Return the sum of sizes and max of aligns.
338 let size = sized_size + unsized_size;
340 // Choose max of two known alignments (combined value must
341 // be aligned according to more restrictive of the two).
342 let align = sized_align.max(unsized_align);
344 // Issue #27023: must add any necessary padding to `size`
345 // (to make it a multiple of `align`) before returning it.
347 // Namely, the returned size should be, in C notation:
349 // `size + ((size & (align-1)) ? align : 0)`
351 // emulated via the semi-standard fast bit trick:
353 // `(size + (align-1)) & -align`
355 Ok((size.abi_align(align), align))
357 ty::TyDynamic(..) => {
358 let (_, vtable) = self.into_ptr_vtable_pair(value)?;
359 // the second entry in the vtable is the dynamic size of the object.
360 self.read_size_and_align_from_vtable(vtable)
363 ty::TySlice(_) | ty::TyStr => {
364 let (elem_size, align) = layout.field(&self, 0)?.size_and_align();
365 let (_, len) = self.into_slice(value)?;
366 Ok((elem_size * len, align))
369 _ => bug!("size_of_val::<{:?}>", ty),
374 pub fn push_stack_frame(
376 instance: ty::Instance<'tcx>,
378 mir: &'mir mir::Mir<'tcx>,
380 return_to_block: StackPopCleanup,
381 ) -> EvalResult<'tcx> {
382 ::log_settings::settings().indentation += 1;
384 /// Return the set of locals that have a storage annotation anywhere
385 fn collect_storage_annotations<'mir, 'tcx>(mir: &'mir mir::Mir<'tcx>) -> HashSet<mir::Local> {
386 use rustc::mir::StatementKind::*;
388 let mut set = HashSet::new();
389 for block in mir.basic_blocks() {
390 for stmt in block.statements.iter() {
393 StorageDead(local) => {
403 // Subtract 1 because `local_decls` includes the ReturnMemoryPointer, but we don't store a local
405 let num_locals = mir.local_decls.len() - 1;
408 let annotated_locals = collect_storage_annotations(mir);
409 let mut locals = vec![None; num_locals];
410 for i in 0..num_locals {
411 let local = mir::Local::new(i + 1);
412 if !annotated_locals.contains(&local) {
413 locals[i] = Some(Value::ByVal(PrimVal::Undef));
419 self.stack.push(Frame {
421 block: mir::START_BLOCK,
430 self.memory.cur_frame = self.cur_frame();
432 if self.stack.len() > self.stack_limit {
433 err!(StackFrameLimitReached)
439 pub(super) fn pop_stack_frame(&mut self) -> EvalResult<'tcx> {
440 ::log_settings::settings().indentation -= 1;
441 M::end_region(self, None)?;
442 let frame = self.stack.pop().expect(
443 "tried to pop a stack frame, but there were none",
445 if !self.stack.is_empty() {
446 // TODO: Is this the correct time to start considering these accesses as originating from the returned-to stack frame?
447 self.memory.cur_frame = self.cur_frame();
449 match frame.return_to_block {
450 StackPopCleanup::MarkStatic(mutable) => {
451 if let Place::Ptr { ptr, .. } = frame.return_place {
452 // FIXME: to_ptr()? might be too extreme here, static zsts might reach this under certain conditions
453 self.memory.mark_static_initialized(
454 ptr.to_ptr()?.alloc_id,
458 bug!("StackPopCleanup::MarkStatic on: {:?}", frame.return_place);
461 StackPopCleanup::Goto(target) => self.goto_block(target),
462 StackPopCleanup::None => {}
464 // deallocate all locals that are backed by an allocation
465 for local in frame.locals {
466 self.deallocate_local(local)?;
472 pub fn deallocate_local(&mut self, local: Option<Value>) -> EvalResult<'tcx> {
473 if let Some(Value::ByRef(ptr, _align)) = local {
474 trace!("deallocating local");
475 let ptr = ptr.to_ptr()?;
476 self.memory.dump_alloc(ptr.alloc_id);
477 self.memory.deallocate_local(ptr)?;
482 /// Evaluate an assignment statement.
484 /// There is no separate `eval_rvalue` function. Instead, the code for handling each rvalue
485 /// type writes its results directly into the memory specified by the place.
486 pub(super) fn eval_rvalue_into_place(
488 rvalue: &mir::Rvalue<'tcx>,
489 place: &mir::Place<'tcx>,
490 ) -> EvalResult<'tcx> {
491 let dest = self.eval_place(place)?;
492 let dest_ty = self.place_ty(place);
494 use rustc::mir::Rvalue::*;
496 Use(ref operand) => {
497 let value = self.eval_operand(operand)?.value;
502 self.write_value(valty, dest)?;
505 BinaryOp(bin_op, ref left, ref right) => {
506 let left = self.eval_operand(left)?;
507 let right = self.eval_operand(right)?;
508 if self.intrinsic_overflowing(
516 // There was an overflow in an unchecked binop. Right now, we consider this an error and bail out.
517 // The rationale is that the reason rustc emits unchecked binops in release mode (vs. the checked binops
518 // it emits in debug mode) is performance, but it doesn't cost us any performance in miri.
519 // If, however, the compiler ever starts transforming unchecked intrinsics into unchecked binops,
520 // we have to go back to just ignoring the overflow here.
521 return err!(OverflowingMath);
525 CheckedBinaryOp(bin_op, ref left, ref right) => {
526 let left = self.eval_operand(left)?;
527 let right = self.eval_operand(right)?;
528 self.intrinsic_with_overflow(
537 UnaryOp(un_op, ref operand) => {
538 let val = self.eval_operand_to_primval(operand)?;
539 let val = self.unary_op(un_op, val, dest_ty)?;
547 Aggregate(ref kind, ref operands) => {
548 self.inc_step_counter_and_check_limit(operands.len())?;
550 let (dest, active_field_index) = match **kind {
551 mir::AggregateKind::Adt(adt_def, variant_index, _, active_field_index) => {
552 self.write_discriminant_value(dest_ty, dest, variant_index)?;
553 if adt_def.is_enum() {
554 (self.place_downcast(dest, variant_index)?, active_field_index)
556 (dest, active_field_index)
562 let layout = self.layout_of(dest_ty)?;
563 for (i, operand) in operands.iter().enumerate() {
564 let value = self.eval_operand(operand)?;
565 // Ignore zero-sized fields.
566 if !self.layout_of(value.ty)?.is_zst() {
567 let field_index = active_field_index.unwrap_or(i);
568 let (field_dest, _) = self.place_field(dest, mir::Field::new(field_index), layout)?;
569 self.write_value(value, field_dest)?;
574 Repeat(ref operand, _) => {
575 let (elem_ty, length) = match dest_ty.sty {
576 ty::TyArray(elem_ty, n) => (elem_ty, n.val.unwrap_u64()),
579 "tried to assign array-repeat to non-array type {:?}",
584 let elem_size = self.layout_of(elem_ty)?.size.bytes();
585 let value = self.eval_operand(operand)?.value;
587 let (dest, dest_align) = self.force_allocation(dest)?.to_ptr_align();
589 // FIXME: speed up repeat filling
591 let elem_dest = dest.offset(i * elem_size, &self)?;
592 self.write_value_to_ptr(value, elem_dest, dest_align, elem_ty)?;
597 // FIXME(CTFE): don't allow computing the length of arrays in const eval
598 let src = self.eval_place(place)?;
599 let ty = self.place_ty(place);
600 let (_, len) = src.elem_ty_and_len(ty);
603 PrimVal::from_u128(len as u128),
608 Ref(_, _, ref place) => {
609 let src = self.eval_place(place)?;
610 // We ignore the alignment of the place here -- special handling for packed structs ends
611 // at the `&` operator.
612 let (ptr, _align, extra) = self.force_allocation(src)?.to_ptr_align_extra();
614 let val = match extra {
615 PlaceExtra::None => ptr.to_value(),
616 PlaceExtra::Length(len) => ptr.to_value_with_len(len),
617 PlaceExtra::Vtable(vtable) => ptr.to_value_with_vtable(vtable),
618 PlaceExtra::DowncastVariant(..) => {
619 bug!("attempted to take a reference to an enum downcast place")
626 self.write_value(valty, dest)?;
629 NullaryOp(mir::NullOp::Box, ty) => {
630 let ty = self.monomorphize(ty, self.substs());
631 M::box_alloc(self, ty, dest)?;
634 NullaryOp(mir::NullOp::SizeOf, ty) => {
635 let ty = self.monomorphize(ty, self.substs());
636 let layout = self.layout_of(ty)?;
637 assert!(!layout.is_unsized(),
638 "SizeOf nullary MIR operator called for unsized type");
641 PrimVal::from_u128(layout.size.bytes() as u128),
646 Cast(kind, ref operand, cast_ty) => {
647 debug_assert_eq!(self.monomorphize(cast_ty, self.substs()), dest_ty);
648 use rustc::mir::CastKind::*;
651 let src = self.eval_operand(operand)?;
652 let src_layout = self.layout_of(src.ty)?;
653 let dst_layout = self.layout_of(dest_ty)?;
654 self.unsize_into(src.value, src_layout, dest, dst_layout)?;
658 let src = self.eval_operand(operand)?;
659 if self.type_is_fat_ptr(src.ty) {
660 match (src.value, self.type_is_fat_ptr(dest_ty)) {
661 (Value::ByRef { .. }, _) |
662 (Value::ByValPair(..), true) => {
667 self.write_value(valty, dest)?;
669 (Value::ByValPair(data, _), false) => {
671 value: Value::ByVal(data),
674 self.write_value(valty, dest)?;
676 (Value::ByVal(_), _) => bug!("expected fat ptr"),
679 let src_val = self.value_to_primval(src)?;
680 let dest_val = self.cast_primval(src_val, src.ty, dest_ty)?;
682 value: Value::ByVal(dest_val),
685 self.write_value(valty, dest)?;
690 match self.eval_operand(operand)?.ty.sty {
691 ty::TyFnDef(def_id, substs) => {
692 if self.tcx.has_attr(def_id, "rustc_args_required_const") {
693 bug!("reifying a fn ptr that requires \
696 let instance: EvalResult<'tcx, _> = ty::Instance::resolve(
701 ).ok_or(EvalErrorKind::TypeckError.into());
702 let fn_ptr = self.memory.create_fn_alloc(instance?);
704 value: Value::ByVal(PrimVal::Ptr(fn_ptr)),
707 self.write_value(valty, dest)?;
709 ref other => bug!("reify fn pointer on {:?}", other),
716 let mut src = self.eval_operand(operand)?;
718 self.write_value(src, dest)?;
720 ref other => bug!("fn to unsafe fn cast on {:?}", other),
724 ClosureFnPointer => {
725 match self.eval_operand(operand)?.ty.sty {
726 ty::TyClosure(def_id, substs) => {
727 let substs = self.tcx.trans_apply_param_substs(self.substs(), &substs);
728 let instance = ty::Instance::resolve_closure(
732 ty::ClosureKind::FnOnce,
734 let fn_ptr = self.memory.create_fn_alloc(instance);
736 value: Value::ByVal(PrimVal::Ptr(fn_ptr)),
739 self.write_value(valty, dest)?;
741 ref other => bug!("closure fn pointer on {:?}", other),
747 Discriminant(ref place) => {
748 let ty = self.place_ty(place);
749 let place = self.eval_place(place)?;
750 let discr_val = self.read_discriminant_value(place, ty)?;
751 if let ty::TyAdt(adt_def, _) = ty.sty {
752 trace!("Read discriminant {}, valid discriminants {:?}", discr_val, adt_def.discriminants(*self.tcx).collect::<Vec<_>>());
753 if adt_def.discriminants(*self.tcx).all(|v| {
757 return err!(InvalidDiscriminant);
759 self.write_primval(dest, PrimVal::Bytes(discr_val), dest_ty)?;
761 bug!("rustc only generates Rvalue::Discriminant for enums");
766 if log_enabled!(::log::Level::Trace) {
767 self.dump_local(dest);
773 pub(super) fn type_is_fat_ptr(&self, ty: Ty<'tcx>) -> bool {
775 ty::TyRawPtr(ref tam) |
776 ty::TyRef(_, ref tam) => !self.type_is_sized(tam.ty),
777 ty::TyAdt(def, _) if def.is_box() => !self.type_is_sized(ty.boxed_ty()),
782 pub(super) fn eval_operand_to_primval(
784 op: &mir::Operand<'tcx>,
785 ) -> EvalResult<'tcx, PrimVal> {
786 let valty = self.eval_operand(op)?;
787 self.value_to_primval(valty)
790 pub(crate) fn operands_to_args(
792 ops: &[mir::Operand<'tcx>],
793 ) -> EvalResult<'tcx, Vec<ValTy<'tcx>>> {
795 .map(|op| self.eval_operand(op))
799 pub fn eval_operand(&mut self, op: &mir::Operand<'tcx>) -> EvalResult<'tcx, ValTy<'tcx>> {
800 use rustc::mir::Operand::*;
801 let ty = self.monomorphize(op.ty(self.mir(), *self.tcx), self.substs());
803 // FIXME: do some more logic on `move` to invalidate the old location
807 value: self.eval_and_read_place(place)?,
812 Constant(ref constant) => {
813 use rustc::mir::Literal;
814 let mir::Constant { ref literal, .. } = **constant;
815 let value = match *literal {
816 Literal::Value { ref value } => self.const_to_value(&value.val, ty)?,
818 Literal::Promoted { index } => {
819 self.read_global_as_value(GlobalId {
820 instance: self.frame().instance,
821 promoted: Some(index),
834 pub fn read_discriminant_value(
838 ) -> EvalResult<'tcx, u128> {
839 let layout = self.layout_of(ty)?;
840 //trace!("read_discriminant_value {:#?}", layout);
842 match layout.variants {
843 layout::Variants::Single { index } => {
844 return Ok(index as u128);
846 layout::Variants::Tagged { .. } |
847 layout::Variants::NicheFilling { .. } => {},
850 let (discr_place, discr) = self.place_field(place, mir::Field::new(0), layout)?;
851 let raw_discr = self.value_to_primval(ValTy {
852 value: self.read_place(discr_place)?,
855 let discr_val = match layout.variants {
856 layout::Variants::Single { .. } => bug!(),
857 layout::Variants::Tagged { .. } => raw_discr.to_bytes()?,
858 layout::Variants::NicheFilling {
864 let variants_start = niche_variants.start as u128;
865 let variants_end = niche_variants.end as u128;
868 assert!(niche_start == 0);
869 assert!(variants_start == variants_end);
870 dataful_variant as u128
872 PrimVal::Bytes(raw_discr) => {
873 let discr = raw_discr.wrapping_sub(niche_start)
874 .wrapping_add(variants_start);
875 if variants_start <= discr && discr <= variants_end {
878 dataful_variant as u128
881 PrimVal::Undef => return err!(ReadUndefBytes),
890 pub(crate) fn write_discriminant_value(
894 variant_index: usize,
895 ) -> EvalResult<'tcx> {
896 let layout = self.layout_of(dest_ty)?;
898 match layout.variants {
899 layout::Variants::Single { index } => {
900 if index != variant_index {
901 // If the layout of an enum is `Single`, all
902 // other variants are necessarily uninhabited.
903 assert_eq!(layout.for_variant(&self, variant_index).abi,
904 layout::Abi::Uninhabited);
907 layout::Variants::Tagged { .. } => {
908 let discr_val = dest_ty.ty_adt_def().unwrap()
909 .discriminant_for_variant(*self.tcx, variant_index)
912 let (discr_dest, discr) = self.place_field(dest, mir::Field::new(0), layout)?;
913 self.write_primval(discr_dest, PrimVal::Bytes(discr_val), discr.ty)?;
915 layout::Variants::NicheFilling {
921 if variant_index != dataful_variant {
922 let (niche_dest, niche) =
923 self.place_field(dest, mir::Field::new(0), layout)?;
924 let niche_value = ((variant_index - niche_variants.start) as u128)
925 .wrapping_add(niche_start);
926 self.write_primval(niche_dest, PrimVal::Bytes(niche_value), niche.ty)?;
934 pub fn read_global_as_value(&self, gid: GlobalId<'tcx>, ty: Ty<'tcx>) -> EvalResult<'tcx, Value> {
935 if gid.promoted.is_none() {
939 .get_cached(gid.instance.def_id());
940 if let Some(alloc_id) = cached {
941 let layout = self.layout_of(ty)?;
942 let ptr = MemoryPointer::new(alloc_id, 0);
943 return Ok(Value::ByRef(ptr.into(), layout.align))
946 let cv = self.const_eval(gid)?;
947 self.const_to_value(&cv.val, ty)
950 pub fn const_eval(&self, gid: GlobalId<'tcx>) -> EvalResult<'tcx, &'tcx ty::Const<'tcx>> {
951 let param_env = if self.tcx.is_static(gid.instance.def_id()).is_some() {
952 ty::ParamEnv::reveal_all()
956 self.tcx.const_eval(param_env.and(gid)).map_err(|err| match *err.kind {
957 ErrKind::Miri(ref err, _) => match err.kind {
958 EvalErrorKind::TypeckError |
959 EvalErrorKind::Layout(_) => EvalErrorKind::TypeckError.into(),
960 _ => EvalErrorKind::ReferencedConstant.into(),
962 ErrKind::TypeckError => EvalErrorKind::TypeckError.into(),
963 ref other => bug!("const eval returned {:?}", other),
967 pub fn force_allocation(&mut self, place: Place) -> EvalResult<'tcx, Place> {
968 let new_place = match place {
969 Place::Local { frame, local } => {
970 // -1 since we don't store the return value
971 match self.stack[frame].locals[local.index() - 1] {
972 None => return err!(DeadLocal),
973 Some(Value::ByRef(ptr, align)) => {
977 extra: PlaceExtra::None,
981 let ty = self.stack[frame].mir.local_decls[local].ty;
982 let ty = self.monomorphize(ty, self.stack[frame].instance.substs);
983 let layout = self.layout_of(ty)?;
984 let ptr = self.alloc_ptr(ty)?;
985 self.stack[frame].locals[local.index() - 1] =
986 Some(Value::ByRef(ptr.into(), layout.align)); // it stays live
987 let place = Place::from_ptr(ptr, layout.align);
988 self.write_value(ValTy { value: val, ty }, place)?;
993 Place::Ptr { .. } => place,
998 /// ensures this Value is not a ByRef
999 pub fn follow_by_ref_value(
1003 ) -> EvalResult<'tcx, Value> {
1005 Value::ByRef(ptr, align) => {
1006 self.read_value(ptr, align, ty)
1012 pub fn value_to_primval(
1014 ValTy { value, ty } : ValTy<'tcx>,
1015 ) -> EvalResult<'tcx, PrimVal> {
1016 match self.follow_by_ref_value(value, ty)? {
1017 Value::ByRef { .. } => bug!("follow_by_ref_value can't result in `ByRef`"),
1019 Value::ByVal(primval) => {
1020 // TODO: Do we really want insta-UB here?
1021 self.ensure_valid_value(primval, ty)?;
1025 Value::ByValPair(..) => bug!("value_to_primval can't work with fat pointers"),
1029 pub fn write_ptr(&mut self, dest: Place, val: Pointer, dest_ty: Ty<'tcx>) -> EvalResult<'tcx> {
1031 value: val.to_value(),
1034 self.write_value(valty, dest)
1037 pub fn write_primval(
1042 ) -> EvalResult<'tcx> {
1044 value: Value::ByVal(val),
1047 self.write_value(valty, dest)
1052 ValTy { value: src_val, ty: dest_ty } : ValTy<'tcx>,
1054 ) -> EvalResult<'tcx> {
1055 //trace!("Writing {:?} to {:?} at type {:?}", src_val, dest, dest_ty);
1056 // Note that it is really important that the type here is the right one, and matches the type things are read at.
1057 // In case `src_val` is a `ByValPair`, we don't do any magic here to handle padding properly, which is only
1058 // correct if we never look at this data with the wrong type.
1061 Place::Ptr { ptr, align, extra } => {
1062 assert_eq!(extra, PlaceExtra::None);
1063 self.write_value_to_ptr(src_val, ptr, align, dest_ty)
1066 Place::Local { frame, local } => {
1067 let dest = self.stack[frame].get_local(local)?;
1068 self.write_value_possibly_by_val(
1070 |this, val| this.stack[frame].set_local(local, val),
1078 // The cases here can be a bit subtle. Read carefully!
1079 fn write_value_possibly_by_val<F: FnOnce(&mut Self, Value) -> EvalResult<'tcx>>(
1083 old_dest_val: Value,
1085 ) -> EvalResult<'tcx> {
1086 if let Value::ByRef(dest_ptr, align) = old_dest_val {
1087 // If the value is already `ByRef` (that is, backed by an `Allocation`),
1088 // then we must write the new value into this allocation, because there may be
1089 // other pointers into the allocation. These other pointers are logically
1090 // pointers into the local variable, and must be able to observe the change.
1092 // Thus, it would be an error to replace the `ByRef` with a `ByVal`, unless we
1093 // knew for certain that there were no outstanding pointers to this allocation.
1094 self.write_value_to_ptr(src_val, dest_ptr, align, dest_ty)?;
1095 } else if let Value::ByRef(src_ptr, align) = src_val {
1096 // If the value is not `ByRef`, then we know there are no pointers to it
1097 // and we can simply overwrite the `Value` in the locals array directly.
1099 // In this specific case, where the source value is `ByRef`, we must duplicate
1100 // the allocation, because this is a by-value operation. It would be incorrect
1101 // if they referred to the same allocation, since then a change to one would
1102 // implicitly change the other.
1104 // It is a valid optimization to attempt reading a primitive value out of the
1105 // source and write that into the destination without making an allocation, so
1107 if let Ok(Some(src_val)) = self.try_read_value(src_ptr, align, dest_ty) {
1108 write_dest(self, src_val)?;
1110 let dest_ptr = self.alloc_ptr(dest_ty)?.into();
1111 let layout = self.layout_of(dest_ty)?;
1112 self.memory.copy(src_ptr, align.min(layout.align), dest_ptr, layout.align, layout.size.bytes(), false)?;
1113 write_dest(self, Value::ByRef(dest_ptr, layout.align))?;
1116 // Finally, we have the simple case where neither source nor destination are
1117 // `ByRef`. We may simply copy the source value over the the destintion.
1118 write_dest(self, src_val)?;
1123 pub fn write_value_to_ptr(
1129 ) -> EvalResult<'tcx> {
1130 let layout = self.layout_of(dest_ty)?;
1131 trace!("write_value_to_ptr: {:#?}, {}, {:#?}", value, dest_ty, layout);
1133 Value::ByRef(ptr, align) => {
1134 self.memory.copy(ptr, align.min(layout.align), dest, dest_align.min(layout.align), layout.size.bytes(), false)
1136 Value::ByVal(primval) => {
1137 let signed = match layout.abi {
1138 layout::Abi::Scalar(ref scal) => match scal.value {
1139 layout::Primitive::Int(_, signed) => signed,
1142 _ if primval.is_undef() => false,
1143 _ => bug!("write_value_to_ptr: invalid ByVal layout: {:#?}", layout)
1145 self.memory.write_primval(dest.to_ptr()?, dest_align, primval, layout.size.bytes(), signed)
1147 Value::ByValPair(a_val, b_val) => {
1148 let ptr = dest.to_ptr()?;
1149 trace!("write_value_to_ptr valpair: {:#?}", layout);
1150 let (a, b) = match layout.abi {
1151 layout::Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value),
1152 _ => bug!("write_value_to_ptr: invalid ByValPair layout: {:#?}", layout)
1154 let (a_size, b_size) = (a.size(&self), b.size(&self));
1156 let b_offset = a_size.abi_align(b.align(&self));
1157 let b_ptr = ptr.offset(b_offset.bytes(), &self)?.into();
1158 // TODO: What about signedess?
1159 self.memory.write_primval(a_ptr, dest_align, a_val, a_size.bytes(), false)?;
1160 self.memory.write_primval(b_ptr, dest_align, b_val, b_size.bytes(), false)
1165 pub fn ty_to_primval_kind(&self, ty: Ty<'tcx>) -> EvalResult<'tcx, PrimValKind> {
1166 use syntax::ast::FloatTy;
1168 let kind = match ty.sty {
1169 ty::TyBool => PrimValKind::Bool,
1170 ty::TyChar => PrimValKind::Char,
1172 ty::TyInt(int_ty) => {
1173 use syntax::ast::IntTy::*;
1174 let size = match int_ty {
1180 Isize => self.memory.pointer_size(),
1182 PrimValKind::from_int_size(size)
1185 ty::TyUint(uint_ty) => {
1186 use syntax::ast::UintTy::*;
1187 let size = match uint_ty {
1193 Usize => self.memory.pointer_size(),
1195 PrimValKind::from_uint_size(size)
1198 ty::TyFloat(FloatTy::F32) => PrimValKind::F32,
1199 ty::TyFloat(FloatTy::F64) => PrimValKind::F64,
1201 ty::TyFnPtr(_) => PrimValKind::FnPtr,
1203 ty::TyRef(_, ref tam) |
1204 ty::TyRawPtr(ref tam) if self.type_is_sized(tam.ty) => PrimValKind::Ptr,
1206 ty::TyAdt(def, _) if def.is_box() => PrimValKind::Ptr,
1209 match self.layout_of(ty)?.abi {
1210 layout::Abi::Scalar(ref scalar) => {
1211 use rustc::ty::layout::Primitive::*;
1212 match scalar.value {
1213 Int(i, false) => PrimValKind::from_uint_size(i.size().bytes()),
1214 Int(i, true) => PrimValKind::from_int_size(i.size().bytes()),
1215 F32 => PrimValKind::F32,
1216 F64 => PrimValKind::F64,
1217 Pointer => PrimValKind::Ptr,
1221 _ => return err!(TypeNotPrimitive(ty)),
1225 _ => return err!(TypeNotPrimitive(ty)),
1231 fn ensure_valid_value(&self, val: PrimVal, ty: Ty<'tcx>) -> EvalResult<'tcx> {
1233 ty::TyBool if val.to_bytes()? > 1 => err!(InvalidBool),
1235 ty::TyChar if ::std::char::from_u32(val.to_bytes()? as u32).is_none() => {
1236 err!(InvalidChar(val.to_bytes()? as u32 as u128))
1243 pub fn read_value(&self, ptr: Pointer, align: Align, ty: Ty<'tcx>) -> EvalResult<'tcx, Value> {
1244 if let Some(val) = self.try_read_value(ptr, align, ty)? {
1247 bug!("primitive read failed for type: {:?}", ty);
1251 pub(crate) fn read_ptr(
1255 pointee_ty: Ty<'tcx>,
1256 ) -> EvalResult<'tcx, Value> {
1257 let ptr_size = self.memory.pointer_size();
1258 let p: Pointer = self.memory.read_ptr_sized(ptr, ptr_align)?.into();
1259 if self.type_is_sized(pointee_ty) {
1262 trace!("reading fat pointer extra of type {}", pointee_ty);
1263 let extra = ptr.offset(ptr_size, self)?;
1264 match self.tcx.struct_tail(pointee_ty).sty {
1265 ty::TyDynamic(..) => Ok(p.to_value_with_vtable(
1266 self.memory.read_ptr_sized(extra, ptr_align)?.to_ptr()?,
1268 ty::TySlice(..) | ty::TyStr => {
1271 .read_ptr_sized(extra, ptr_align)?
1273 Ok(p.to_value_with_len(len as u64))
1275 _ => bug!("unsized primval ptr read from {:?}", pointee_ty),
1280 pub fn try_read_value(&self, ptr: Pointer, ptr_align: Align, ty: Ty<'tcx>) -> EvalResult<'tcx, Option<Value>> {
1281 use syntax::ast::FloatTy;
1283 let ptr = ptr.to_ptr()?;
1284 let val = match ty.sty {
1286 let val = self.memory.read_primval(ptr, ptr_align, 1)?;
1287 let val = match val {
1288 PrimVal::Bytes(0) => false,
1289 PrimVal::Bytes(1) => true,
1290 // TODO: This seems a little overeager, should reading at bool type already be insta-UB?
1291 _ => return err!(InvalidBool),
1293 PrimVal::from_bool(val)
1296 let c = self.memory.read_primval(ptr, ptr_align, 4)?.to_bytes()? as u32;
1297 match ::std::char::from_u32(c) {
1298 Some(ch) => PrimVal::from_char(ch),
1299 None => return err!(InvalidChar(c as u128)),
1303 ty::TyInt(int_ty) => {
1304 use syntax::ast::IntTy::*;
1305 let size = match int_ty {
1311 Isize => self.memory.pointer_size(),
1313 self.memory.read_primval(ptr, ptr_align, size)?
1316 ty::TyUint(uint_ty) => {
1317 use syntax::ast::UintTy::*;
1318 let size = match uint_ty {
1324 Usize => self.memory.pointer_size(),
1326 self.memory.read_primval(ptr, ptr_align, size)?
1329 ty::TyFloat(FloatTy::F32) => {
1330 PrimVal::Bytes(self.memory.read_primval(ptr, ptr_align, 4)?.to_bytes()?)
1332 ty::TyFloat(FloatTy::F64) => {
1333 PrimVal::Bytes(self.memory.read_primval(ptr, ptr_align, 8)?.to_bytes()?)
1336 ty::TyFnPtr(_) => self.memory.read_ptr_sized(ptr, ptr_align)?,
1337 ty::TyRef(_, ref tam) |
1338 ty::TyRawPtr(ref tam) => return self.read_ptr(ptr, ptr_align, tam.ty).map(Some),
1340 ty::TyAdt(def, _) => {
1342 return self.read_ptr(ptr, ptr_align, ty.boxed_ty()).map(Some);
1345 if let layout::Abi::Scalar(ref scalar) = self.layout_of(ty)?.abi {
1346 let size = scalar.value.size(self).bytes();
1347 self.memory.read_primval(ptr, ptr_align, size)?
1353 _ => return Ok(None),
1356 Ok(Some(Value::ByVal(val)))
1359 pub fn frame(&self) -> &Frame<'mir, 'tcx> {
1360 self.stack.last().expect("no call frames exist")
1363 pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx> {
1364 self.stack.last_mut().expect("no call frames exist")
1367 pub(super) fn mir(&self) -> &'mir mir::Mir<'tcx> {
1371 pub fn substs(&self) -> &'tcx Substs<'tcx> {
1372 if let Some(frame) = self.stack.last() {
1373 frame.instance.substs
1387 ) -> EvalResult<'tcx> {
1388 // A<Struct> -> A<Trait> conversion
1389 let (src_pointee_ty, dest_pointee_ty) = self.tcx.struct_lockstep_tails(sty, dty);
1391 match (&src_pointee_ty.sty, &dest_pointee_ty.sty) {
1392 (&ty::TyArray(_, length), &ty::TySlice(_)) => {
1393 let ptr = self.into_ptr(src)?;
1394 // u64 cast is from usize to u64, which is always good
1396 value: ptr.to_value_with_len(length.val.unwrap_u64() ),
1399 self.write_value(valty, dest)
1401 (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
1402 // For now, upcasts are limited to changes in marker
1403 // traits, and hence never actually require an actual
1404 // change to the vtable.
1409 self.write_value(valty, dest)
1411 (_, &ty::TyDynamic(ref data, _)) => {
1412 let trait_ref = data.principal().unwrap().with_self_ty(
1416 let trait_ref = self.tcx.erase_regions(&trait_ref);
1417 let vtable = self.get_vtable(src_pointee_ty, trait_ref)?;
1418 let ptr = self.into_ptr(src)?;
1420 value: ptr.to_value_with_vtable(vtable),
1423 self.write_value(valty, dest)
1426 _ => bug!("invalid unsizing {:?} -> {:?}", src_ty, dest_ty),
1433 src_layout: TyLayout<'tcx>,
1435 dst_layout: TyLayout<'tcx>,
1436 ) -> EvalResult<'tcx> {
1437 match (&src_layout.ty.sty, &dst_layout.ty.sty) {
1438 (&ty::TyRef(_, ref s), &ty::TyRef(_, ref d)) |
1439 (&ty::TyRef(_, ref s), &ty::TyRawPtr(ref d)) |
1440 (&ty::TyRawPtr(ref s), &ty::TyRawPtr(ref d)) => {
1441 self.unsize_into_ptr(src, src_layout.ty, dst, dst_layout.ty, s.ty, d.ty)
1443 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => {
1444 assert_eq!(def_a, def_b);
1445 if def_a.is_box() || def_b.is_box() {
1446 if !def_a.is_box() || !def_b.is_box() {
1447 bug!("invalid unsizing between {:?} -> {:?}", src_layout, dst_layout);
1449 return self.unsize_into_ptr(
1454 src_layout.ty.boxed_ty(),
1455 dst_layout.ty.boxed_ty(),
1459 // unsizing of generic struct with pointer fields
1460 // Example: `Arc<T>` -> `Arc<Trait>`
1461 // here we need to increase the size of every &T thin ptr field to a fat ptr
1462 for i in 0..src_layout.fields.count() {
1463 let (dst_f_place, dst_field) =
1464 self.place_field(dst, mir::Field::new(i), dst_layout)?;
1465 if dst_field.is_zst() {
1468 let (src_f_value, src_field) = match src {
1469 Value::ByRef(ptr, align) => {
1470 let src_place = Place::from_primval_ptr(ptr, align);
1471 let (src_f_place, src_field) =
1472 self.place_field(src_place, mir::Field::new(i), src_layout)?;
1473 (self.read_place(src_f_place)?, src_field)
1475 Value::ByVal(_) | Value::ByValPair(..) => {
1476 let src_field = src_layout.field(&self, i)?;
1477 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
1478 assert_eq!(src_field.size, src_layout.size);
1482 if src_field.ty == dst_field.ty {
1483 self.write_value(ValTy {
1488 self.unsize_into(src_f_value, src_field, dst_f_place, dst_field)?;
1495 "unsize_into: invalid conversion: {:?} -> {:?}",
1503 pub fn dump_local(&self, place: Place) {
1506 Place::Local { frame, local } => {
1507 let mut allocs = Vec::new();
1508 let mut msg = format!("{:?}", local);
1509 if frame != self.cur_frame() {
1510 write!(msg, " ({} frames up)", self.cur_frame() - frame).unwrap();
1512 write!(msg, ":").unwrap();
1514 match self.stack[frame].get_local(local) {
1516 if let EvalErrorKind::DeadLocal = err.kind {
1517 write!(msg, " is dead").unwrap();
1519 panic!("Failed to access local: {:?}", err);
1522 Ok(Value::ByRef(ptr, align)) => {
1523 match ptr.into_inner_primval() {
1524 PrimVal::Ptr(ptr) => {
1525 write!(msg, " by align({}) ref:", align.abi()).unwrap();
1526 allocs.push(ptr.alloc_id);
1528 ptr => write!(msg, " integral by ref: {:?}", ptr).unwrap(),
1531 Ok(Value::ByVal(val)) => {
1532 write!(msg, " {:?}", val).unwrap();
1533 if let PrimVal::Ptr(ptr) = val {
1534 allocs.push(ptr.alloc_id);
1537 Ok(Value::ByValPair(val1, val2)) => {
1538 write!(msg, " ({:?}, {:?})", val1, val2).unwrap();
1539 if let PrimVal::Ptr(ptr) = val1 {
1540 allocs.push(ptr.alloc_id);
1542 if let PrimVal::Ptr(ptr) = val2 {
1543 allocs.push(ptr.alloc_id);
1549 self.memory.dump_allocs(allocs);
1551 Place::Ptr { ptr, align, .. } => {
1552 match ptr.into_inner_primval() {
1553 PrimVal::Ptr(ptr) => {
1554 trace!("by align({}) ref:", align.abi());
1555 self.memory.dump_alloc(ptr.alloc_id);
1557 ptr => trace!(" integral by ref: {:?}", ptr),
1563 /// Convenience function to ensure correct usage of locals
1564 pub fn modify_local<F>(&mut self, frame: usize, local: mir::Local, f: F) -> EvalResult<'tcx>
1566 F: FnOnce(&mut Self, Value) -> EvalResult<'tcx, Value>,
1568 let val = self.stack[frame].get_local(local)?;
1569 let new_val = f(self, val)?;
1570 self.stack[frame].set_local(local, new_val)?;
1571 // FIXME(solson): Run this when setting to Undef? (See previous version of this code.)
1572 // if let Value::ByRef(ptr) = self.stack[frame].get_local(local) {
1573 // self.memory.deallocate(ptr)?;
1578 pub fn generate_stacktrace(&self, explicit_span: Option<Span>) -> (Vec<FrameInfo>, Span) {
1579 let mut last_span = None;
1580 let mut frames = Vec::new();
1581 // skip 1 because the last frame is just the environment of the constant
1582 for &Frame { instance, span, .. } in self.stack().iter().skip(1).rev() {
1583 // make sure we don't emit frames that are duplicates of the previous
1584 if explicit_span == Some(span) {
1585 last_span = Some(span);
1588 if let Some(last) = last_span {
1593 last_span = Some(span);
1595 let location = if self.tcx.def_key(instance.def_id()).disambiguated_data.data == DefPathData::ClosureExpr {
1596 "closure".to_owned()
1598 instance.to_string()
1600 frames.push(FrameInfo { span, location });
1602 trace!("generate stacktrace: {:#?}, {:?}", frames, explicit_span);
1603 (frames, self.tcx.span)
1606 pub fn report(&self, e: &mut EvalError, as_err: bool, explicit_span: Option<Span>) {
1608 EvalErrorKind::Layout(_) |
1609 EvalErrorKind::TypeckError => return,
1612 if let Some(ref mut backtrace) = e.backtrace {
1613 let mut trace_text = "\n\nAn error occurred in miri:\n".to_string();
1614 backtrace.resolve();
1615 write!(trace_text, "backtrace frames: {}\n", backtrace.frames().len()).unwrap();
1616 'frames: for (i, frame) in backtrace.frames().iter().enumerate() {
1617 if frame.symbols().is_empty() {
1618 write!(trace_text, "{}: no symbols\n", i).unwrap();
1620 for symbol in frame.symbols() {
1621 write!(trace_text, "{}: ", i).unwrap();
1622 if let Some(name) = symbol.name() {
1623 write!(trace_text, "{}\n", name).unwrap();
1625 write!(trace_text, "<unknown>\n").unwrap();
1627 write!(trace_text, "\tat ").unwrap();
1628 if let Some(file_path) = symbol.filename() {
1629 write!(trace_text, "{}", file_path.display()).unwrap();
1631 write!(trace_text, "<unknown_file>").unwrap();
1633 if let Some(line) = symbol.lineno() {
1634 write!(trace_text, ":{}\n", line).unwrap();
1636 write!(trace_text, "\n").unwrap();
1640 error!("{}", trace_text);
1642 if let Some(frame) = self.stack().last() {
1643 let block = &frame.mir.basic_blocks()[frame.block];
1644 let span = explicit_span.unwrap_or_else(|| if frame.stmt < block.statements.len() {
1645 block.statements[frame.stmt].source_info.span
1647 block.terminator().source_info.span
1649 trace!("reporting const eval failure at {:?}", span);
1650 let mut err = if as_err {
1651 ::rustc::middle::const_val::struct_error(*self.tcx, span, "constant evaluation error")
1657 .filter_map(|frame| self.tcx.hir.as_local_node_id(frame.instance.def_id()))
1659 .expect("some part of a failing const eval must be local");
1660 self.tcx.struct_span_lint_node(
1661 ::rustc::lint::builtin::CONST_ERR,
1664 "constant evaluation error",
1667 let (frames, span) = self.generate_stacktrace(explicit_span);
1668 err.span_label(span, e.to_string());
1669 for FrameInfo { span, location } in frames {
1670 err.span_note(span, &format!("inside call to `{}`", location));
1674 self.tcx.sess.err(&e.to_string());
1678 pub fn sign_extend(&self, value: u128, ty: Ty<'tcx>) -> EvalResult<'tcx, u128> {
1679 let layout = self.layout_of(ty)?;
1680 let size = layout.size.bits();
1681 assert!(layout.abi.is_signed());
1683 let amt = 128 - size;
1684 // shift the unsigned value to the left
1685 // and back to the right as signed (essentially fills with FF on the left)
1686 Ok((((value << amt) as i128) >> amt) as u128)
1689 pub fn truncate(&self, value: u128, ty: Ty<'tcx>) -> EvalResult<'tcx, u128> {
1690 let size = self.layout_of(ty)?.size.bits();
1691 let amt = 128 - size;
1692 // truncate (shift left to drop out leftover values, shift right to fill with zeroes)
1693 Ok((value << amt) >> amt)
1697 impl<'mir, 'tcx> Frame<'mir, 'tcx> {
1698 pub fn get_local(&self, local: mir::Local) -> EvalResult<'tcx, Value> {
1699 // Subtract 1 because we don't store a value for the ReturnPointer, the local with index 0.
1700 self.locals[local.index() - 1].ok_or(EvalErrorKind::DeadLocal.into())
1703 fn set_local(&mut self, local: mir::Local, value: Value) -> EvalResult<'tcx> {
1704 // Subtract 1 because we don't store a value for the ReturnPointer, the local with index 0.
1705 match self.locals[local.index() - 1] {
1706 None => err!(DeadLocal),
1707 Some(ref mut local) => {
1714 pub fn storage_live(&mut self, local: mir::Local) -> EvalResult<'tcx, Option<Value>> {
1715 trace!("{:?} is now live", local);
1717 let old = self.locals[local.index() - 1];
1718 self.locals[local.index() - 1] = Some(Value::ByVal(PrimVal::Undef)); // StorageLive *always* kills the value that's currently stored
1722 /// Returns the old value of the local
1723 pub fn storage_dead(&mut self, local: mir::Local) -> EvalResult<'tcx, Option<Value>> {
1724 trace!("{:?} is now dead", local);
1726 let old = self.locals[local.index() - 1];
1727 self.locals[local.index() - 1] = None;