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