]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/interpret/eval_context.rs
Auto merge of #74844 - asomers:freebsd-profiler, r=pietroalbini
[rust.git] / src / librustc_mir / interpret / eval_context.rs
1 use std::cell::Cell;
2 use std::mem;
3
4 use rustc_data_structures::fx::FxHashMap;
5 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
6 use rustc_hir::def::DefKind;
7 use rustc_hir::def_id::DefId;
8 use rustc_index::vec::IndexVec;
9 use rustc_macros::HashStable;
10 use rustc_middle::ich::StableHashingContext;
11 use rustc_middle::mir;
12 use rustc_middle::mir::interpret::{
13     sign_extend, truncate, FrameInfo, GlobalId, InterpResult, Pointer, Scalar,
14 };
15 use rustc_middle::ty::layout::{self, TyAndLayout};
16 use rustc_middle::ty::{
17     self, query::TyCtxtAt, subst::SubstsRef, ParamEnv, Ty, TyCtxt, TypeFoldable,
18 };
19 use rustc_span::{source_map::DUMMY_SP, Span};
20 use rustc_target::abi::{Align, HasDataLayout, LayoutOf, Size, TargetDataLayout};
21
22 use super::{
23     Immediate, MPlaceTy, Machine, MemPlace, MemPlaceMeta, Memory, OpTy, Operand, Place, PlaceTy,
24     ScalarMaybeUninit, StackPopJump,
25 };
26 use crate::transform::validate::equal_up_to_regions;
27 use crate::util::storage::AlwaysLiveLocals;
28
29 pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> {
30     /// Stores the `Machine` instance.
31     ///
32     /// Note: the stack is provided by the machine.
33     pub machine: M,
34
35     /// The results of the type checker, from rustc.
36     /// The span in this is the "root" of the evaluation, i.e., the const
37     /// we are evaluating (if this is CTFE).
38     pub tcx: TyCtxtAt<'tcx>,
39
40     /// Bounds in scope for polymorphic evaluations.
41     pub(crate) param_env: ty::ParamEnv<'tcx>,
42
43     /// The virtual memory system.
44     pub memory: Memory<'mir, 'tcx, M>,
45
46     /// A cache for deduplicating vtables
47     pub(super) vtables:
48         FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), Pointer<M::PointerTag>>,
49 }
50
51 /// A stack frame.
52 #[derive(Clone)]
53 pub struct Frame<'mir, 'tcx, Tag = (), Extra = ()> {
54     ////////////////////////////////////////////////////////////////////////////////
55     // Function and callsite information
56     ////////////////////////////////////////////////////////////////////////////////
57     /// The MIR for the function called on this frame.
58     pub body: &'mir mir::Body<'tcx>,
59
60     /// The def_id and substs of the current function.
61     pub instance: ty::Instance<'tcx>,
62
63     /// Extra data for the machine.
64     pub extra: Extra,
65
66     ////////////////////////////////////////////////////////////////////////////////
67     // Return place and locals
68     ////////////////////////////////////////////////////////////////////////////////
69     /// Work to perform when returning from this function.
70     pub return_to_block: StackPopCleanup,
71
72     /// The location where the result of the current stack frame should be written to,
73     /// and its layout in the caller.
74     pub return_place: Option<PlaceTy<'tcx, Tag>>,
75
76     /// The list of locals for this stack frame, stored in order as
77     /// `[return_ptr, arguments..., variables..., temporaries...]`.
78     /// The locals are stored as `Option<Value>`s.
79     /// `None` represents a local that is currently dead, while a live local
80     /// can either directly contain `Scalar` or refer to some part of an `Allocation`.
81     pub locals: IndexVec<mir::Local, LocalState<'tcx, Tag>>,
82
83     ////////////////////////////////////////////////////////////////////////////////
84     // Current position within the function
85     ////////////////////////////////////////////////////////////////////////////////
86     /// If this is `None`, we are unwinding and this function doesn't need any clean-up.
87     /// Just continue the same as with `Resume`.
88     pub loc: Option<mir::Location>,
89 }
90
91 #[derive(Clone, Eq, PartialEq, Debug, HashStable)] // Miri debug-prints these
92 pub enum StackPopCleanup {
93     /// Jump to the next block in the caller, or cause UB if None (that's a function
94     /// that may never return). Also store layout of return place so
95     /// we can validate it at that layout.
96     /// `ret` stores the block we jump to on a normal return, while `unwind`
97     /// stores the block used for cleanup during unwinding.
98     Goto { ret: Option<mir::BasicBlock>, unwind: Option<mir::BasicBlock> },
99     /// Just do nothing: Used by Main and for the `box_alloc` hook in miri.
100     /// `cleanup` says whether locals are deallocated. Static computation
101     /// wants them leaked to intern what they need (and just throw away
102     /// the entire `ecx` when it is done).
103     None { cleanup: bool },
104 }
105
106 /// State of a local variable including a memoized layout
107 #[derive(Clone, PartialEq, Eq, HashStable)]
108 pub struct LocalState<'tcx, Tag = ()> {
109     pub value: LocalValue<Tag>,
110     /// Don't modify if `Some`, this is only used to prevent computing the layout twice
111     #[stable_hasher(ignore)]
112     pub layout: Cell<Option<TyAndLayout<'tcx>>>,
113 }
114
115 /// Current value of a local variable
116 #[derive(Copy, Clone, PartialEq, Eq, Debug, HashStable)] // Miri debug-prints these
117 pub enum LocalValue<Tag = ()> {
118     /// This local is not currently alive, and cannot be used at all.
119     Dead,
120     /// This local is alive but not yet initialized. It can be written to
121     /// but not read from or its address taken. Locals get initialized on
122     /// first write because for unsized locals, we do not know their size
123     /// before that.
124     Uninitialized,
125     /// A normal, live local.
126     /// Mostly for convenience, we re-use the `Operand` type here.
127     /// This is an optimization over just always having a pointer here;
128     /// we can thus avoid doing an allocation when the local just stores
129     /// immediate values *and* never has its address taken.
130     Live(Operand<Tag>),
131 }
132
133 impl<'tcx, Tag: Copy + 'static> LocalState<'tcx, Tag> {
134     /// Read the local's value or error if the local is not yet live or not live anymore.
135     ///
136     /// Note: This may only be invoked from the `Machine::access_local` hook and not from
137     /// anywhere else. You may be invalidating machine invariants if you do!
138     pub fn access(&self) -> InterpResult<'tcx, Operand<Tag>> {
139         match self.value {
140             LocalValue::Dead => throw_ub!(DeadLocal),
141             LocalValue::Uninitialized => {
142                 bug!("The type checker should prevent reading from a never-written local")
143             }
144             LocalValue::Live(val) => Ok(val),
145         }
146     }
147
148     /// Overwrite the local.  If the local can be overwritten in place, return a reference
149     /// to do so; otherwise return the `MemPlace` to consult instead.
150     ///
151     /// Note: This may only be invoked from the `Machine::access_local_mut` hook and not from
152     /// anywhere else. You may be invalidating machine invariants if you do!
153     pub fn access_mut(
154         &mut self,
155     ) -> InterpResult<'tcx, Result<&mut LocalValue<Tag>, MemPlace<Tag>>> {
156         match self.value {
157             LocalValue::Dead => throw_ub!(DeadLocal),
158             LocalValue::Live(Operand::Indirect(mplace)) => Ok(Err(mplace)),
159             ref mut
160             local @ (LocalValue::Live(Operand::Immediate(_)) | LocalValue::Uninitialized) => {
161                 Ok(Ok(local))
162             }
163         }
164     }
165 }
166
167 impl<'mir, 'tcx, Tag> Frame<'mir, 'tcx, Tag> {
168     pub fn with_extra<Extra>(self, extra: Extra) -> Frame<'mir, 'tcx, Tag, Extra> {
169         Frame {
170             body: self.body,
171             instance: self.instance,
172             return_to_block: self.return_to_block,
173             return_place: self.return_place,
174             locals: self.locals,
175             loc: self.loc,
176             extra,
177         }
178     }
179 }
180
181 impl<'mir, 'tcx, Tag, Extra> Frame<'mir, 'tcx, Tag, Extra> {
182     /// Return the `SourceInfo` of the current instruction.
183     pub fn current_source_info(&self) -> Option<&mir::SourceInfo> {
184         self.loc.map(|loc| self.body.source_info(loc))
185     }
186 }
187
188 impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for InterpCx<'mir, 'tcx, M> {
189     #[inline]
190     fn data_layout(&self) -> &TargetDataLayout {
191         &self.tcx.data_layout
192     }
193 }
194
195 impl<'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for InterpCx<'mir, 'tcx, M>
196 where
197     M: Machine<'mir, 'tcx>,
198 {
199     #[inline]
200     fn tcx(&self) -> TyCtxt<'tcx> {
201         *self.tcx
202     }
203 }
204
205 impl<'mir, 'tcx, M> layout::HasParamEnv<'tcx> for InterpCx<'mir, 'tcx, M>
206 where
207     M: Machine<'mir, 'tcx>,
208 {
209     fn param_env(&self) -> ty::ParamEnv<'tcx> {
210         self.param_env
211     }
212 }
213
214 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> LayoutOf for InterpCx<'mir, 'tcx, M> {
215     type Ty = Ty<'tcx>;
216     type TyAndLayout = InterpResult<'tcx, TyAndLayout<'tcx>>;
217
218     #[inline]
219     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout {
220         self.tcx
221             .layout_of(self.param_env.and(ty))
222             .map_err(|layout| err_inval!(Layout(layout)).into())
223     }
224 }
225
226 /// Test if it is valid for a MIR assignment to assign `src`-typed place to `dest`-typed value.
227 /// This test should be symmetric, as it is primarily about layout compatibility.
228 pub(super) fn mir_assign_valid_types<'tcx>(
229     tcx: TyCtxt<'tcx>,
230     param_env: ParamEnv<'tcx>,
231     src: TyAndLayout<'tcx>,
232     dest: TyAndLayout<'tcx>,
233 ) -> bool {
234     // Type-changing assignments can happen when subtyping is used. While
235     // all normal lifetimes are erased, higher-ranked types with their
236     // late-bound lifetimes are still around and can lead to type
237     // differences. So we compare ignoring lifetimes.
238     if equal_up_to_regions(tcx, param_env, src.ty, dest.ty) {
239         // Make sure the layout is equal, too -- just to be safe. Miri really
240         // needs layout equality. For performance reason we skip this check when
241         // the types are equal. Equal types *can* have different layouts when
242         // enum downcast is involved (as enum variants carry the type of the
243         // enum), but those should never occur in assignments.
244         if cfg!(debug_assertions) || src.ty != dest.ty {
245             assert_eq!(src.layout, dest.layout);
246         }
247         true
248     } else {
249         false
250     }
251 }
252
253 /// Use the already known layout if given (but sanity check in debug mode),
254 /// or compute the layout.
255 #[cfg_attr(not(debug_assertions), inline(always))]
256 pub(super) fn from_known_layout<'tcx>(
257     tcx: TyCtxtAt<'tcx>,
258     param_env: ParamEnv<'tcx>,
259     known_layout: Option<TyAndLayout<'tcx>>,
260     compute: impl FnOnce() -> InterpResult<'tcx, TyAndLayout<'tcx>>,
261 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
262     match known_layout {
263         None => compute(),
264         Some(known_layout) => {
265             if cfg!(debug_assertions) {
266                 let check_layout = compute()?;
267                 if !mir_assign_valid_types(tcx.tcx, param_env, check_layout, known_layout) {
268                     span_bug!(
269                         tcx.span,
270                         "expected type differs from actual type.\nexpected: {:?}\nactual: {:?}",
271                         known_layout.ty,
272                         check_layout.ty,
273                     );
274                 }
275             }
276             Ok(known_layout)
277         }
278     }
279 }
280
281 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
282     pub fn new(
283         tcx: TyCtxt<'tcx>,
284         root_span: Span,
285         param_env: ty::ParamEnv<'tcx>,
286         machine: M,
287         memory_extra: M::MemoryExtra,
288     ) -> Self {
289         InterpCx {
290             machine,
291             tcx: tcx.at(root_span),
292             param_env,
293             memory: Memory::new(tcx, memory_extra),
294             vtables: FxHashMap::default(),
295         }
296     }
297
298     #[inline(always)]
299     pub fn cur_span(&self) -> Span {
300         self.stack()
301             .last()
302             .and_then(|f| f.current_source_info())
303             .map(|si| si.span)
304             .unwrap_or(self.tcx.span)
305     }
306
307     #[inline(always)]
308     pub fn force_ptr(
309         &self,
310         scalar: Scalar<M::PointerTag>,
311     ) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
312         self.memory.force_ptr(scalar)
313     }
314
315     #[inline(always)]
316     pub fn force_bits(
317         &self,
318         scalar: Scalar<M::PointerTag>,
319         size: Size,
320     ) -> InterpResult<'tcx, u128> {
321         self.memory.force_bits(scalar, size)
322     }
323
324     /// Call this to turn untagged "global" pointers (obtained via `tcx`) into
325     /// the machine pointer to the allocation.  Must never be used
326     /// for any other pointers, nor for TLS statics.
327     ///
328     /// Using the resulting pointer represents a *direct* access to that memory
329     /// (e.g. by directly using a `static`),
330     /// as opposed to access through a pointer that was created by the program.
331     ///
332     /// This function can fail only if `ptr` points to an `extern static`.
333     #[inline(always)]
334     pub fn global_base_pointer(&self, ptr: Pointer) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
335         self.memory.global_base_pointer(ptr)
336     }
337
338     #[inline(always)]
339     pub(crate) fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
340         M::stack(self)
341     }
342
343     #[inline(always)]
344     pub(crate) fn stack_mut(
345         &mut self,
346     ) -> &mut Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>> {
347         M::stack_mut(self)
348     }
349
350     #[inline(always)]
351     pub fn frame_idx(&self) -> usize {
352         let stack = self.stack();
353         assert!(!stack.is_empty());
354         stack.len() - 1
355     }
356
357     #[inline(always)]
358     pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
359         self.stack().last().expect("no call frames exist")
360     }
361
362     #[inline(always)]
363     pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
364         self.stack_mut().last_mut().expect("no call frames exist")
365     }
366
367     #[inline(always)]
368     pub(super) fn body(&self) -> &'mir mir::Body<'tcx> {
369         self.frame().body
370     }
371
372     #[inline(always)]
373     pub fn sign_extend(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
374         assert!(ty.abi.is_signed());
375         sign_extend(value, ty.size)
376     }
377
378     #[inline(always)]
379     pub fn truncate(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
380         truncate(value, ty.size)
381     }
382
383     #[inline]
384     pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
385         ty.is_sized(self.tcx, self.param_env)
386     }
387
388     #[inline]
389     pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
390         ty.is_freeze(self.tcx, self.param_env)
391     }
392
393     pub fn load_mir(
394         &self,
395         instance: ty::InstanceDef<'tcx>,
396         promoted: Option<mir::Promoted>,
397     ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
398         // do not continue if typeck errors occurred (can only occur in local crate)
399         let def = instance.with_opt_param();
400         if let Some(def) = def.as_local() {
401             if self.tcx.has_typeck_results(def.did) {
402                 if let Some(error_reported) = self.tcx.typeck_opt_const_arg(def).tainted_by_errors {
403                     throw_inval!(TypeckError(error_reported))
404                 }
405             }
406         }
407         trace!("load mir(instance={:?}, promoted={:?})", instance, promoted);
408         if let Some(promoted) = promoted {
409             return Ok(&self.tcx.promoted_mir_of_opt_const_arg(def)[promoted]);
410         }
411         match instance {
412             ty::InstanceDef::Item(def) => {
413                 if self.tcx.is_mir_available(def.did) {
414                     if let Some((did, param_did)) = def.as_const_arg() {
415                         Ok(self.tcx.optimized_mir_of_const_arg((did, param_did)))
416                     } else {
417                         Ok(self.tcx.optimized_mir(def.did))
418                     }
419                 } else {
420                     throw_unsup!(NoMirFor(def.did))
421                 }
422             }
423             _ => Ok(self.tcx.instance_mir(instance)),
424         }
425     }
426
427     /// Call this on things you got out of the MIR (so it is as generic as the current
428     /// stack frame), to bring it into the proper environment for this interpreter.
429     pub(super) fn subst_from_current_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
430         &self,
431         value: T,
432     ) -> T {
433         self.subst_from_frame_and_normalize_erasing_regions(self.frame(), value)
434     }
435
436     /// Call this on things you got out of the MIR (so it is as generic as the provided
437     /// stack frame), to bring it into the proper environment for this interpreter.
438     pub(super) fn subst_from_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
439         &self,
440         frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
441         value: T,
442     ) -> T {
443         if let Some(substs) = frame.instance.substs_for_mir_body() {
444             self.tcx.subst_and_normalize_erasing_regions(substs, self.param_env, &value)
445         } else {
446             self.tcx.normalize_erasing_regions(self.param_env, value)
447         }
448     }
449
450     /// The `substs` are assumed to already be in our interpreter "universe" (param_env).
451     pub(super) fn resolve(
452         &self,
453         def_id: DefId,
454         substs: SubstsRef<'tcx>,
455     ) -> InterpResult<'tcx, ty::Instance<'tcx>> {
456         trace!("resolve: {:?}, {:#?}", def_id, substs);
457         trace!("param_env: {:#?}", self.param_env);
458         trace!("substs: {:#?}", substs);
459         match ty::Instance::resolve(*self.tcx, self.param_env, def_id, substs) {
460             Ok(Some(instance)) => Ok(instance),
461             Ok(None) => throw_inval!(TooGeneric),
462
463             // FIXME(eddyb) this could be a bit more specific than `TypeckError`.
464             Err(error_reported) => throw_inval!(TypeckError(error_reported)),
465         }
466     }
467
468     pub fn layout_of_local(
469         &self,
470         frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
471         local: mir::Local,
472         layout: Option<TyAndLayout<'tcx>>,
473     ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
474         // `const_prop` runs into this with an invalid (empty) frame, so we
475         // have to support that case (mostly by skipping all caching).
476         match frame.locals.get(local).and_then(|state| state.layout.get()) {
477             None => {
478                 let layout = from_known_layout(self.tcx, self.param_env, layout, || {
479                     let local_ty = frame.body.local_decls[local].ty;
480                     let local_ty =
481                         self.subst_from_frame_and_normalize_erasing_regions(frame, local_ty);
482                     self.layout_of(local_ty)
483                 })?;
484                 if let Some(state) = frame.locals.get(local) {
485                     // Layouts of locals are requested a lot, so we cache them.
486                     state.layout.set(Some(layout));
487                 }
488                 Ok(layout)
489             }
490             Some(layout) => Ok(layout),
491         }
492     }
493
494     /// Returns the actual dynamic size and alignment of the place at the given type.
495     /// Only the "meta" (metadata) part of the place matters.
496     /// This can fail to provide an answer for extern types.
497     pub(super) fn size_and_align_of(
498         &self,
499         metadata: MemPlaceMeta<M::PointerTag>,
500         layout: TyAndLayout<'tcx>,
501     ) -> InterpResult<'tcx, Option<(Size, Align)>> {
502         if !layout.is_unsized() {
503             return Ok(Some((layout.size, layout.align.abi)));
504         }
505         match layout.ty.kind {
506             ty::Adt(..) | ty::Tuple(..) => {
507                 // First get the size of all statically known fields.
508                 // Don't use type_of::sizing_type_of because that expects t to be sized,
509                 // and it also rounds up to alignment, which we want to avoid,
510                 // as the unsized field's alignment could be smaller.
511                 assert!(!layout.ty.is_simd());
512                 assert!(layout.fields.count() > 0);
513                 trace!("DST layout: {:?}", layout);
514
515                 let sized_size = layout.fields.offset(layout.fields.count() - 1);
516                 let sized_align = layout.align.abi;
517                 trace!(
518                     "DST {} statically sized prefix size: {:?} align: {:?}",
519                     layout.ty,
520                     sized_size,
521                     sized_align
522                 );
523
524                 // Recurse to get the size of the dynamically sized field (must be
525                 // the last field).  Can't have foreign types here, how would we
526                 // adjust alignment and size for them?
527                 let field = layout.field(self, layout.fields.count() - 1)?;
528                 let (unsized_size, unsized_align) = match self.size_and_align_of(metadata, field)? {
529                     Some(size_and_align) => size_and_align,
530                     None => {
531                         // A field with extern type.  If this field is at offset 0, we behave
532                         // like the underlying extern type.
533                         // FIXME: Once we have made decisions for how to handle size and alignment
534                         // of `extern type`, this should be adapted.  It is just a temporary hack
535                         // to get some code to work that probably ought to work.
536                         if sized_size == Size::ZERO {
537                             return Ok(None);
538                         } else {
539                             span_bug!(
540                                 self.cur_span(),
541                                 "Fields cannot be extern types, unless they are at offset 0"
542                             )
543                         }
544                     }
545                 };
546
547                 // FIXME (#26403, #27023): We should be adding padding
548                 // to `sized_size` (to accommodate the `unsized_align`
549                 // required of the unsized field that follows) before
550                 // summing it with `sized_size`. (Note that since #26403
551                 // is unfixed, we do not yet add the necessary padding
552                 // here. But this is where the add would go.)
553
554                 // Return the sum of sizes and max of aligns.
555                 let size = sized_size + unsized_size; // `Size` addition
556
557                 // Choose max of two known alignments (combined value must
558                 // be aligned according to more restrictive of the two).
559                 let align = sized_align.max(unsized_align);
560
561                 // Issue #27023: must add any necessary padding to `size`
562                 // (to make it a multiple of `align`) before returning it.
563                 let size = size.align_to(align);
564
565                 // Check if this brought us over the size limit.
566                 if size.bytes() >= self.tcx.data_layout.obj_size_bound() {
567                     throw_ub!(InvalidMeta("total size is bigger than largest supported object"));
568                 }
569                 Ok(Some((size, align)))
570             }
571             ty::Dynamic(..) => {
572                 let vtable = metadata.unwrap_meta();
573                 // Read size and align from vtable (already checks size).
574                 Ok(Some(self.read_size_and_align_from_vtable(vtable)?))
575             }
576
577             ty::Slice(_) | ty::Str => {
578                 let len = metadata.unwrap_meta().to_machine_usize(self)?;
579                 let elem = layout.field(self, 0)?;
580
581                 // Make sure the slice is not too big.
582                 let size = elem.size.checked_mul(len, self).ok_or_else(|| {
583                     err_ub!(InvalidMeta("slice is bigger than largest supported object"))
584                 })?;
585                 Ok(Some((size, elem.align.abi)))
586             }
587
588             ty::Foreign(_) => Ok(None),
589
590             _ => span_bug!(self.cur_span(), "size_and_align_of::<{:?}> not supported", layout.ty),
591         }
592     }
593     #[inline]
594     pub fn size_and_align_of_mplace(
595         &self,
596         mplace: MPlaceTy<'tcx, M::PointerTag>,
597     ) -> InterpResult<'tcx, Option<(Size, Align)>> {
598         self.size_and_align_of(mplace.meta, mplace.layout)
599     }
600
601     pub fn push_stack_frame(
602         &mut self,
603         instance: ty::Instance<'tcx>,
604         body: &'mir mir::Body<'tcx>,
605         return_place: Option<PlaceTy<'tcx, M::PointerTag>>,
606         return_to_block: StackPopCleanup,
607     ) -> InterpResult<'tcx> {
608         if !self.stack().is_empty() {
609             info!("PAUSING({}) {}", self.frame_idx(), self.frame().instance);
610         }
611         ::log_settings::settings().indentation += 1;
612
613         // first push a stack frame so we have access to the local substs
614         let pre_frame = Frame {
615             body,
616             loc: Some(mir::Location::START),
617             return_to_block,
618             return_place,
619             // empty local array, we fill it in below, after we are inside the stack frame and
620             // all methods actually know about the frame
621             locals: IndexVec::new(),
622             instance,
623             extra: (),
624         };
625         let frame = M::init_frame_extra(self, pre_frame)?;
626         self.stack_mut().push(frame);
627
628         // Locals are initially uninitialized.
629         let dummy = LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
630         let mut locals = IndexVec::from_elem(dummy, &body.local_decls);
631
632         // Now mark those locals as dead that we do not want to initialize
633         match self.tcx.def_kind(instance.def_id()) {
634             // statics and constants don't have `Storage*` statements, no need to look for them
635             //
636             // FIXME: The above is likely untrue. See
637             // <https://github.com/rust-lang/rust/pull/70004#issuecomment-602022110>. Is it
638             // okay to ignore `StorageDead`/`StorageLive` annotations during CTFE?
639             DefKind::Static | DefKind::Const | DefKind::AssocConst => {}
640             _ => {
641                 // Mark locals that use `Storage*` annotations as dead on function entry.
642                 let always_live = AlwaysLiveLocals::new(self.body());
643                 for local in locals.indices() {
644                     if !always_live.contains(local) {
645                         locals[local].value = LocalValue::Dead;
646                     }
647                 }
648             }
649         }
650         // done
651         self.frame_mut().locals = locals;
652
653         M::after_stack_push(self)?;
654         info!("ENTERING({}) {}", self.frame_idx(), self.frame().instance);
655
656         if !self.tcx.sess.recursion_limit().value_within_limit(self.stack().len()) {
657             throw_exhaust!(StackFrameLimitReached)
658         } else {
659             Ok(())
660         }
661     }
662
663     /// Jump to the given block.
664     #[inline]
665     pub fn go_to_block(&mut self, target: mir::BasicBlock) {
666         self.frame_mut().loc = Some(mir::Location { block: target, statement_index: 0 });
667     }
668
669     /// *Return* to the given `target` basic block.
670     /// Do *not* use for unwinding! Use `unwind_to_block` instead.
671     ///
672     /// If `target` is `None`, that indicates the function cannot return, so we raise UB.
673     pub fn return_to_block(&mut self, target: Option<mir::BasicBlock>) -> InterpResult<'tcx> {
674         if let Some(target) = target {
675             self.go_to_block(target);
676             Ok(())
677         } else {
678             throw_ub!(Unreachable)
679         }
680     }
681
682     /// *Unwind* to the given `target` basic block.
683     /// Do *not* use for returning! Use `return_to_block` instead.
684     ///
685     /// If `target` is `None`, that indicates the function does not need cleanup during
686     /// unwinding, and we will just keep propagating that upwards.
687     pub fn unwind_to_block(&mut self, target: Option<mir::BasicBlock>) {
688         self.frame_mut().loc = target.map(|block| mir::Location { block, statement_index: 0 });
689     }
690
691     /// Pops the current frame from the stack, deallocating the
692     /// memory for allocated locals.
693     ///
694     /// If `unwinding` is `false`, then we are performing a normal return
695     /// from a function. In this case, we jump back into the frame of the caller,
696     /// and continue execution as normal.
697     ///
698     /// If `unwinding` is `true`, then we are in the middle of a panic,
699     /// and need to unwind this frame. In this case, we jump to the
700     /// `cleanup` block for the function, which is responsible for running
701     /// `Drop` impls for any locals that have been initialized at this point.
702     /// The cleanup block ends with a special `Resume` terminator, which will
703     /// cause us to continue unwinding.
704     pub(super) fn pop_stack_frame(&mut self, unwinding: bool) -> InterpResult<'tcx> {
705         info!(
706             "LEAVING({}) {} (unwinding = {})",
707             self.frame_idx(),
708             self.frame().instance,
709             unwinding
710         );
711
712         // Sanity check `unwinding`.
713         assert_eq!(
714             unwinding,
715             match self.frame().loc {
716                 None => true,
717                 Some(loc) => self.body().basic_blocks()[loc.block].is_cleanup,
718             }
719         );
720
721         ::log_settings::settings().indentation -= 1;
722         let frame =
723             self.stack_mut().pop().expect("tried to pop a stack frame, but there were none");
724
725         if !unwinding {
726             // Copy the return value to the caller's stack frame.
727             if let Some(return_place) = frame.return_place {
728                 let op = self.access_local(&frame, mir::RETURN_PLACE, None)?;
729                 self.copy_op_transmute(op, return_place)?;
730                 trace!("{:?}", self.dump_place(*return_place));
731             } else {
732                 throw_ub!(Unreachable);
733             }
734         }
735
736         // Now where do we jump next?
737
738         // Usually we want to clean up (deallocate locals), but in a few rare cases we don't.
739         // In that case, we return early. We also avoid validation in that case,
740         // because this is CTFE and the final value will be thoroughly validated anyway.
741         let (cleanup, next_block) = match frame.return_to_block {
742             StackPopCleanup::Goto { ret, unwind } => {
743                 (true, Some(if unwinding { unwind } else { ret }))
744             }
745             StackPopCleanup::None { cleanup, .. } => (cleanup, None),
746         };
747
748         if !cleanup {
749             assert!(self.stack().is_empty(), "only the topmost frame should ever be leaked");
750             assert!(next_block.is_none(), "tried to skip cleanup when we have a next block!");
751             assert!(!unwinding, "tried to skip cleanup during unwinding");
752             // Leak the locals, skip validation, skip machine hook.
753             return Ok(());
754         }
755
756         // Cleanup: deallocate all locals that are backed by an allocation.
757         for local in &frame.locals {
758             self.deallocate_local(local.value)?;
759         }
760
761         if M::after_stack_pop(self, frame, unwinding)? == StackPopJump::NoJump {
762             // The hook already did everything.
763             // We want to skip the `info!` below, hence early return.
764             return Ok(());
765         }
766         // Normal return, figure out where to jump.
767         if unwinding {
768             // Follow the unwind edge.
769             let unwind = next_block.expect("Encountered StackPopCleanup::None when unwinding!");
770             self.unwind_to_block(unwind);
771         } else {
772             // Follow the normal return edge.
773             if let Some(ret) = next_block {
774                 self.return_to_block(ret)?;
775             }
776         }
777
778         if !self.stack().is_empty() {
779             info!(
780                 "CONTINUING({}) {} (unwinding = {})",
781                 self.frame_idx(),
782                 self.frame().instance,
783                 unwinding
784             );
785         }
786
787         Ok(())
788     }
789
790     /// Mark a storage as live, killing the previous content and returning it.
791     /// Remember to deallocate that!
792     pub fn storage_live(
793         &mut self,
794         local: mir::Local,
795     ) -> InterpResult<'tcx, LocalValue<M::PointerTag>> {
796         assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
797         trace!("{:?} is now live", local);
798
799         let local_val = LocalValue::Uninitialized;
800         // StorageLive *always* kills the value that's currently stored.
801         // However, we do not error if the variable already is live;
802         // see <https://github.com/rust-lang/rust/issues/42371>.
803         Ok(mem::replace(&mut self.frame_mut().locals[local].value, local_val))
804     }
805
806     /// Returns the old value of the local.
807     /// Remember to deallocate that!
808     pub fn storage_dead(&mut self, local: mir::Local) -> LocalValue<M::PointerTag> {
809         assert!(local != mir::RETURN_PLACE, "Cannot make return place dead");
810         trace!("{:?} is now dead", local);
811
812         mem::replace(&mut self.frame_mut().locals[local].value, LocalValue::Dead)
813     }
814
815     pub(super) fn deallocate_local(
816         &mut self,
817         local: LocalValue<M::PointerTag>,
818     ) -> InterpResult<'tcx> {
819         // FIXME: should we tell the user that there was a local which was never written to?
820         if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local {
821             trace!("deallocating local");
822             // All locals have a backing allocation, even if the allocation is empty
823             // due to the local having ZST type.
824             let ptr = ptr.assert_ptr();
825             trace!("{:?}", self.memory.dump_alloc(ptr.alloc_id));
826             self.memory.deallocate_local(ptr)?;
827         };
828         Ok(())
829     }
830
831     pub(super) fn const_eval(
832         &self,
833         gid: GlobalId<'tcx>,
834         ty: Ty<'tcx>,
835     ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
836         // For statics we pick `ParamEnv::reveal_all`, because statics don't have generics
837         // and thus don't care about the parameter environment. While we could just use
838         // `self.param_env`, that would mean we invoke the query to evaluate the static
839         // with different parameter environments, thus causing the static to be evaluated
840         // multiple times.
841         let param_env = if self.tcx.is_static(gid.instance.def_id()) {
842             ty::ParamEnv::reveal_all()
843         } else {
844             self.param_env
845         };
846         let val = self.tcx.const_eval_global_id(param_env, gid, Some(self.tcx.span))?;
847
848         // Even though `ecx.const_eval` is called from `const_to_op` we can never have a
849         // recursion deeper than one level, because the `tcx.const_eval` above is guaranteed to not
850         // return `ConstValue::Unevaluated`, which is the only way that `const_to_op` will call
851         // `ecx.const_eval`.
852         let const_ = ty::Const { val: ty::ConstKind::Value(val), ty };
853         self.const_to_op(&const_, None)
854     }
855
856     pub fn const_eval_raw(
857         &self,
858         gid: GlobalId<'tcx>,
859     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
860         // For statics we pick `ParamEnv::reveal_all`, because statics don't have generics
861         // and thus don't care about the parameter environment. While we could just use
862         // `self.param_env`, that would mean we invoke the query to evaluate the static
863         // with different parameter environments, thus causing the static to be evaluated
864         // multiple times.
865         let param_env = if self.tcx.is_static(gid.instance.def_id()) {
866             ty::ParamEnv::reveal_all()
867         } else {
868             self.param_env
869         };
870         // We use `const_eval_raw` here, and get an unvalidated result.  That is okay:
871         // Our result will later be validated anyway, and there seems no good reason
872         // to have to fail early here.  This is also more consistent with
873         // `Memory::get_static_alloc` which has to use `const_eval_raw` to avoid cycles.
874         // FIXME: We can hit delay_span_bug if this is an invalid const, interning finds
875         // that problem, but we never run validation to show an error. Can we ensure
876         // this does not happen?
877         let val = self.tcx.const_eval_raw(param_env.and(gid))?;
878         self.raw_const_to_mplace(val)
879     }
880
881     #[must_use]
882     pub fn dump_place(&'a self, place: Place<M::PointerTag>) -> PlacePrinter<'a, 'mir, 'tcx, M> {
883         PlacePrinter { ecx: self, place }
884     }
885
886     #[must_use]
887     pub fn generate_stacktrace(&self) -> Vec<FrameInfo<'tcx>> {
888         let mut frames = Vec::new();
889         for frame in self.stack().iter().rev() {
890             let source_info = frame.current_source_info();
891             let lint_root = source_info.and_then(|source_info| {
892                 match &frame.body.source_scopes[source_info.scope].local_data {
893                     mir::ClearCrossCrate::Set(data) => Some(data.lint_root),
894                     mir::ClearCrossCrate::Clear => None,
895                 }
896             });
897             let span = source_info.map_or(DUMMY_SP, |source_info| source_info.span);
898
899             frames.push(FrameInfo { span, instance: frame.instance, lint_root });
900         }
901         trace!("generate stacktrace: {:#?}", frames);
902         frames
903     }
904 }
905
906 #[doc(hidden)]
907 /// Helper struct for the `dump_place` function.
908 pub struct PlacePrinter<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
909     ecx: &'a InterpCx<'mir, 'tcx, M>,
910     place: Place<M::PointerTag>,
911 }
912
913 impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug
914     for PlacePrinter<'a, 'mir, 'tcx, M>
915 {
916     fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
917         match self.place {
918             Place::Local { frame, local } => {
919                 let mut allocs = Vec::new();
920                 write!(fmt, "{:?}", local)?;
921                 if frame != self.ecx.frame_idx() {
922                     write!(fmt, " ({} frames up)", self.ecx.frame_idx() - frame)?;
923                 }
924                 write!(fmt, ":")?;
925
926                 match self.ecx.stack()[frame].locals[local].value {
927                     LocalValue::Dead => write!(fmt, " is dead")?,
928                     LocalValue::Uninitialized => write!(fmt, " is uninitialized")?,
929                     LocalValue::Live(Operand::Indirect(mplace)) => match mplace.ptr {
930                         Scalar::Ptr(ptr) => {
931                             write!(
932                                 fmt,
933                                 " by align({}){} ref:",
934                                 mplace.align.bytes(),
935                                 match mplace.meta {
936                                     MemPlaceMeta::Meta(meta) => format!(" meta({:?})", meta),
937                                     MemPlaceMeta::Poison | MemPlaceMeta::None => String::new(),
938                                 }
939                             )?;
940                             allocs.push(ptr.alloc_id);
941                         }
942                         ptr => write!(fmt, " by integral ref: {:?}", ptr)?,
943                     },
944                     LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => {
945                         write!(fmt, " {:?}", val)?;
946                         if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr)) = val {
947                             allocs.push(ptr.alloc_id);
948                         }
949                     }
950                     LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
951                         write!(fmt, " ({:?}, {:?})", val1, val2)?;
952                         if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr)) = val1 {
953                             allocs.push(ptr.alloc_id);
954                         }
955                         if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr)) = val2 {
956                             allocs.push(ptr.alloc_id);
957                         }
958                     }
959                 }
960
961                 write!(fmt, ": {:?}", self.ecx.memory.dump_allocs(allocs))
962             }
963             Place::Ptr(mplace) => match mplace.ptr {
964                 Scalar::Ptr(ptr) => write!(
965                     fmt,
966                     "by align({}) ref: {:?}",
967                     mplace.align.bytes(),
968                     self.ecx.memory.dump_alloc(ptr.alloc_id)
969                 ),
970                 ptr => write!(fmt, " integral by ref: {:?}", ptr),
971             },
972         }
973     }
974 }
975
976 impl<'ctx, 'mir, 'tcx, Tag, Extra> HashStable<StableHashingContext<'ctx>>
977     for Frame<'mir, 'tcx, Tag, Extra>
978 where
979     Extra: HashStable<StableHashingContext<'ctx>>,
980     Tag: HashStable<StableHashingContext<'ctx>>,
981 {
982     fn hash_stable(&self, hcx: &mut StableHashingContext<'ctx>, hasher: &mut StableHasher) {
983         // Exhaustive match on fields to make sure we forget no field.
984         let Frame { body, instance, return_to_block, return_place, locals, loc, extra } = self;
985         body.hash_stable(hcx, hasher);
986         instance.hash_stable(hcx, hasher);
987         return_to_block.hash_stable(hcx, hasher);
988         return_place.as_ref().map(|r| &**r).hash_stable(hcx, hasher);
989         locals.hash_stable(hcx, hasher);
990         loc.hash_stable(hcx, hasher);
991         extra.hash_stable(hcx, hasher);
992     }
993 }