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