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