]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/interpret/eval_context.rs
Rollup merge of #94274 - djkoloski:unknown_unstable_lints, r=tmandry
[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::AlwaysLiveLocals;
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     AllocCheck, AllocId, GlobalId, Immediate, InterpErrorInfo, InterpResult, MPlaceTy, Machine,
26     MemPlace, MemPlaceMeta, Memory, MemoryKind, Operand, Place, PlaceTy, Pointer, 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: Option<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     pub(super) loc: Result<mir::Location, Span>,
130 }
131
132 /// What we store about a frame in an interpreter backtrace.
133 #[derive(Debug)]
134 pub struct FrameInfo<'tcx> {
135     pub instance: ty::Instance<'tcx>,
136     pub span: Span,
137     pub lint_root: Option<hir::HirId>,
138 }
139
140 /// Unwind information.
141 #[derive(Clone, Copy, Eq, PartialEq, Debug, HashStable)]
142 pub enum StackPopUnwind {
143     /// The cleanup block.
144     Cleanup(mir::BasicBlock),
145     /// No cleanup needs to be done.
146     Skip,
147     /// Unwinding is not allowed (UB).
148     NotAllowed,
149 }
150
151 #[derive(Clone, Copy, Eq, PartialEq, Debug, HashStable)] // Miri debug-prints these
152 pub enum StackPopCleanup {
153     /// Jump to the next block in the caller, or cause UB if None (that's a function
154     /// that may never return). Also store layout of return place so
155     /// we can validate it at that layout.
156     /// `ret` stores the block we jump to on a normal return, while `unwind`
157     /// stores the block used for cleanup during unwinding.
158     Goto { ret: Option<mir::BasicBlock>, unwind: StackPopUnwind },
159     /// The root frame of the stack: nowhere else to jump to.
160     /// `cleanup` says whether locals are deallocated. Static computation
161     /// wants them leaked to intern what they need (and just throw away
162     /// the entire `ecx` when it is done).
163     Root { cleanup: bool },
164 }
165
166 /// State of a local variable including a memoized layout
167 #[derive(Clone, Debug, PartialEq, Eq, HashStable)]
168 pub struct LocalState<'tcx, Tag: Provenance = AllocId> {
169     pub value: LocalValue<Tag>,
170     /// Don't modify if `Some`, this is only used to prevent computing the layout twice
171     #[stable_hasher(ignore)]
172     pub layout: Cell<Option<TyAndLayout<'tcx>>>,
173 }
174
175 /// Current value of a local variable
176 #[derive(Copy, Clone, PartialEq, Eq, HashStable, Debug)] // Miri debug-prints these
177 pub enum LocalValue<Tag: Provenance = AllocId> {
178     /// This local is not currently alive, and cannot be used at all.
179     Dead,
180     /// This local is alive but not yet initialized. It can be written to
181     /// but not read from or its address taken. Locals get initialized on
182     /// first write because for unsized locals, we do not know their size
183     /// before that.
184     Uninitialized,
185     /// A normal, live local.
186     /// Mostly for convenience, we re-use the `Operand` type here.
187     /// This is an optimization over just always having a pointer here;
188     /// we can thus avoid doing an allocation when the local just stores
189     /// immediate values *and* never has its address taken.
190     Live(Operand<Tag>),
191 }
192
193 impl<'tcx, Tag: Provenance + 'static> LocalState<'tcx, Tag> {
194     /// Read the local's value or error if the local is not yet live or not live anymore.
195     ///
196     /// Note: This may only be invoked from the `Machine::access_local` hook and not from
197     /// anywhere else. You may be invalidating machine invariants if you do!
198     pub fn access(&self) -> InterpResult<'tcx, Operand<Tag>> {
199         match self.value {
200             LocalValue::Dead => throw_ub!(DeadLocal),
201             LocalValue::Uninitialized => {
202                 bug!("The type checker should prevent reading from a never-written local")
203             }
204             LocalValue::Live(val) => Ok(val),
205         }
206     }
207
208     /// Overwrite the local.  If the local can be overwritten in place, return a reference
209     /// to do so; otherwise return the `MemPlace` to consult instead.
210     ///
211     /// Note: This may only be invoked from the `Machine::access_local_mut` hook and not from
212     /// anywhere else. You may be invalidating machine invariants if you do!
213     pub fn access_mut(
214         &mut self,
215     ) -> InterpResult<'tcx, Result<&mut LocalValue<Tag>, MemPlace<Tag>>> {
216         match self.value {
217             LocalValue::Dead => throw_ub!(DeadLocal),
218             LocalValue::Live(Operand::Indirect(mplace)) => Ok(Err(mplace)),
219             ref mut
220             local @ (LocalValue::Live(Operand::Immediate(_)) | LocalValue::Uninitialized) => {
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         self.tcx.span
326     }
327
328     #[inline]
329     fn handle_layout_err(
330         &self,
331         err: LayoutError<'tcx>,
332         _: Span,
333         _: Ty<'tcx>,
334     ) -> InterpErrorInfo<'tcx> {
335         err_inval!(Layout(err)).into()
336     }
337 }
338
339 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> FnAbiOfHelpers<'tcx> for InterpCx<'mir, 'tcx, M> {
340     type FnAbiOfResult = InterpResult<'tcx, &'tcx FnAbi<'tcx, Ty<'tcx>>>;
341
342     fn handle_fn_abi_err(
343         &self,
344         err: FnAbiError<'tcx>,
345         _span: Span,
346         _fn_abi_request: FnAbiRequest<'tcx>,
347     ) -> InterpErrorInfo<'tcx> {
348         match err {
349             FnAbiError::Layout(err) => err_inval!(Layout(err)).into(),
350             FnAbiError::AdjustForForeignAbi(err) => {
351                 err_inval!(FnAbiAdjustForForeignAbi(err)).into()
352             }
353         }
354     }
355 }
356
357 /// Test if it is valid for a MIR assignment to assign `src`-typed place to `dest`-typed value.
358 /// This test should be symmetric, as it is primarily about layout compatibility.
359 pub(super) fn mir_assign_valid_types<'tcx>(
360     tcx: TyCtxt<'tcx>,
361     param_env: ParamEnv<'tcx>,
362     src: TyAndLayout<'tcx>,
363     dest: TyAndLayout<'tcx>,
364 ) -> bool {
365     // Type-changing assignments can happen when subtyping is used. While
366     // all normal lifetimes are erased, higher-ranked types with their
367     // late-bound lifetimes are still around and can lead to type
368     // differences. So we compare ignoring lifetimes.
369     if equal_up_to_regions(tcx, param_env, src.ty, dest.ty) {
370         // Make sure the layout is equal, too -- just to be safe. Miri really
371         // needs layout equality. For performance reason we skip this check when
372         // the types are equal. Equal types *can* have different layouts when
373         // enum downcast is involved (as enum variants carry the type of the
374         // enum), but those should never occur in assignments.
375         if cfg!(debug_assertions) || src.ty != dest.ty {
376             assert_eq!(src.layout, dest.layout);
377         }
378         true
379     } else {
380         false
381     }
382 }
383
384 /// Use the already known layout if given (but sanity check in debug mode),
385 /// or compute the layout.
386 #[cfg_attr(not(debug_assertions), inline(always))]
387 pub(super) fn from_known_layout<'tcx>(
388     tcx: TyCtxtAt<'tcx>,
389     param_env: ParamEnv<'tcx>,
390     known_layout: Option<TyAndLayout<'tcx>>,
391     compute: impl FnOnce() -> InterpResult<'tcx, TyAndLayout<'tcx>>,
392 ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
393     match known_layout {
394         None => compute(),
395         Some(known_layout) => {
396             if cfg!(debug_assertions) {
397                 let check_layout = compute()?;
398                 if !mir_assign_valid_types(tcx.tcx, param_env, check_layout, known_layout) {
399                     span_bug!(
400                         tcx.span,
401                         "expected type differs from actual type.\nexpected: {:?}\nactual: {:?}",
402                         known_layout.ty,
403                         check_layout.ty,
404                     );
405                 }
406             }
407             Ok(known_layout)
408         }
409     }
410 }
411
412 impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
413     pub fn new(
414         tcx: TyCtxt<'tcx>,
415         root_span: Span,
416         param_env: ty::ParamEnv<'tcx>,
417         machine: M,
418         memory_extra: M::MemoryExtra,
419     ) -> Self {
420         InterpCx {
421             machine,
422             tcx: tcx.at(root_span),
423             param_env,
424             memory: Memory::new(tcx, memory_extra),
425             recursion_limit: tcx.recursion_limit(),
426         }
427     }
428
429     #[inline(always)]
430     pub fn cur_span(&self) -> Span {
431         self.stack()
432             .iter()
433             .rev()
434             .find(|frame| !frame.instance.def.requires_caller_location(*self.tcx))
435             .map_or(self.tcx.span, |f| f.current_span())
436     }
437
438     #[inline(always)]
439     pub fn scalar_to_ptr(&self, scalar: Scalar<M::PointerTag>) -> Pointer<Option<M::PointerTag>> {
440         self.memory.scalar_to_ptr(scalar)
441     }
442
443     /// Test if this value might be null.
444     /// If the machine does not support ptr-to-int casts, this is conservative.
445     pub fn scalar_may_be_null(&self, scalar: Scalar<M::PointerTag>) -> bool {
446         match scalar.try_to_int() {
447             Ok(int) => int.is_null(),
448             Err(_) => {
449                 let ptr = self.scalar_to_ptr(scalar);
450                 match self.memory.ptr_try_get_alloc(ptr) {
451                     Ok((alloc_id, offset, _)) => {
452                         let (size, _align) = self
453                             .memory
454                             .get_size_and_align(alloc_id, AllocCheck::MaybeDead)
455                             .expect("alloc info with MaybeDead cannot fail");
456                         // If the pointer is out-of-bounds, it may be null.
457                         // Note that one-past-the-end (offset == size) is still inbounds, and never null.
458                         offset > size
459                     }
460                     Err(offset) => offset == 0,
461                 }
462             }
463         }
464     }
465
466     /// Call this to turn untagged "global" pointers (obtained via `tcx`) into
467     /// the machine pointer to the allocation.  Must never be used
468     /// for any other pointers, nor for TLS statics.
469     ///
470     /// Using the resulting pointer represents a *direct* access to that memory
471     /// (e.g. by directly using a `static`),
472     /// as opposed to access through a pointer that was created by the program.
473     ///
474     /// This function can fail only if `ptr` points to an `extern static`.
475     #[inline(always)]
476     pub fn global_base_pointer(&self, ptr: Pointer) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
477         self.memory.global_base_pointer(ptr)
478     }
479
480     #[inline(always)]
481     pub(crate) fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
482         M::stack(self)
483     }
484
485     #[inline(always)]
486     pub(crate) fn stack_mut(
487         &mut self,
488     ) -> &mut Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>> {
489         M::stack_mut(self)
490     }
491
492     #[inline(always)]
493     pub fn frame_idx(&self) -> usize {
494         let stack = self.stack();
495         assert!(!stack.is_empty());
496         stack.len() - 1
497     }
498
499     #[inline(always)]
500     pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
501         self.stack().last().expect("no call frames exist")
502     }
503
504     #[inline(always)]
505     pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
506         self.stack_mut().last_mut().expect("no call frames exist")
507     }
508
509     #[inline(always)]
510     pub(super) fn body(&self) -> &'mir mir::Body<'tcx> {
511         self.frame().body
512     }
513
514     #[inline(always)]
515     pub fn sign_extend(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
516         assert!(ty.abi.is_signed());
517         ty.size.sign_extend(value)
518     }
519
520     #[inline(always)]
521     pub fn truncate(&self, value: u128, ty: TyAndLayout<'_>) -> u128 {
522         ty.size.truncate(value)
523     }
524
525     #[inline]
526     pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
527         ty.is_freeze(self.tcx, self.param_env)
528     }
529
530     pub fn load_mir(
531         &self,
532         instance: ty::InstanceDef<'tcx>,
533         promoted: Option<mir::Promoted>,
534     ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
535         let def = instance.with_opt_param();
536         trace!("load mir(instance={:?}, promoted={:?})", instance, promoted);
537         let body = if let Some(promoted) = promoted {
538             &self.tcx.promoted_mir_opt_const_arg(def)[promoted]
539         } else {
540             M::load_mir(self, instance)?
541         };
542         // do not continue if typeck errors occurred (can only occur in local crate)
543         if let Some(err) = body.tainted_by_errors {
544             throw_inval!(AlreadyReported(err));
545         }
546         Ok(body)
547     }
548
549     /// Call this on things you got out of the MIR (so it is as generic as the current
550     /// stack frame), to bring it into the proper environment for this interpreter.
551     pub(super) fn subst_from_current_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
552         &self,
553         value: T,
554     ) -> Result<T, InterpError<'tcx>> {
555         self.subst_from_frame_and_normalize_erasing_regions(self.frame(), value)
556     }
557
558     /// Call this on things you got out of the MIR (so it is as generic as the provided
559     /// stack frame), to bring it into the proper environment for this interpreter.
560     pub(super) fn subst_from_frame_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
561         &self,
562         frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
563         value: T,
564     ) -> Result<T, InterpError<'tcx>> {
565         frame
566             .instance
567             .try_subst_mir_and_normalize_erasing_regions(*self.tcx, self.param_env, value)
568             .or_else(|e| {
569                 self.tcx.sess.delay_span_bug(
570                     self.cur_span(),
571                     format!("failed to normalize {}", e.get_type_for_failure()).as_str(),
572                 );
573
574                 Err(InterpError::InvalidProgram(InvalidProgramInfo::TooGeneric))
575             })
576     }
577
578     /// The `substs` are assumed to already be in our interpreter "universe" (param_env).
579     pub(super) fn resolve(
580         &self,
581         def: ty::WithOptConstParam<DefId>,
582         substs: SubstsRef<'tcx>,
583     ) -> InterpResult<'tcx, ty::Instance<'tcx>> {
584         trace!("resolve: {:?}, {:#?}", def, substs);
585         trace!("param_env: {:#?}", self.param_env);
586         trace!("substs: {:#?}", substs);
587         match ty::Instance::resolve_opt_const_arg(*self.tcx, self.param_env, def, substs) {
588             Ok(Some(instance)) => Ok(instance),
589             Ok(None) => throw_inval!(TooGeneric),
590
591             // FIXME(eddyb) this could be a bit more specific than `AlreadyReported`.
592             Err(error_reported) => throw_inval!(AlreadyReported(error_reported)),
593         }
594     }
595
596     #[inline(always)]
597     pub fn layout_of_local(
598         &self,
599         frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
600         local: mir::Local,
601         layout: Option<TyAndLayout<'tcx>>,
602     ) -> InterpResult<'tcx, TyAndLayout<'tcx>> {
603         // `const_prop` runs into this with an invalid (empty) frame, so we
604         // have to support that case (mostly by skipping all caching).
605         match frame.locals.get(local).and_then(|state| state.layout.get()) {
606             None => {
607                 let layout = from_known_layout(self.tcx, self.param_env, layout, || {
608                     let local_ty = frame.body.local_decls[local].ty;
609                     let local_ty =
610                         self.subst_from_frame_and_normalize_erasing_regions(frame, local_ty)?;
611                     self.layout_of(local_ty)
612                 })?;
613                 if let Some(state) = frame.locals.get(local) {
614                     // Layouts of locals are requested a lot, so we cache them.
615                     state.layout.set(Some(layout));
616                 }
617                 Ok(layout)
618             }
619             Some(layout) => Ok(layout),
620         }
621     }
622
623     /// Returns the actual dynamic size and alignment of the place at the given type.
624     /// Only the "meta" (metadata) part of the place matters.
625     /// This can fail to provide an answer for extern types.
626     pub(super) fn size_and_align_of(
627         &self,
628         metadata: &MemPlaceMeta<M::PointerTag>,
629         layout: &TyAndLayout<'tcx>,
630     ) -> InterpResult<'tcx, Option<(Size, Align)>> {
631         if !layout.is_unsized() {
632             return Ok(Some((layout.size, layout.align.abi)));
633         }
634         match layout.ty.kind() {
635             ty::Adt(..) | ty::Tuple(..) => {
636                 // First get the size of all statically known fields.
637                 // Don't use type_of::sizing_type_of because that expects t to be sized,
638                 // and it also rounds up to alignment, which we want to avoid,
639                 // as the unsized field's alignment could be smaller.
640                 assert!(!layout.ty.is_simd());
641                 assert!(layout.fields.count() > 0);
642                 trace!("DST layout: {:?}", layout);
643
644                 let sized_size = layout.fields.offset(layout.fields.count() - 1);
645                 let sized_align = layout.align.abi;
646                 trace!(
647                     "DST {} statically sized prefix size: {:?} align: {:?}",
648                     layout.ty,
649                     sized_size,
650                     sized_align
651                 );
652
653                 // Recurse to get the size of the dynamically sized field (must be
654                 // the last field).  Can't have foreign types here, how would we
655                 // adjust alignment and size for them?
656                 let field = layout.field(self, layout.fields.count() - 1);
657                 let Some((unsized_size, unsized_align)) = self.size_and_align_of(metadata, &field)? else {
658                     // A field with an extern type. We don't know the actual dynamic size
659                     // or the alignment.
660                     return Ok(None);
661                 };
662
663                 // FIXME (#26403, #27023): We should be adding padding
664                 // to `sized_size` (to accommodate the `unsized_align`
665                 // required of the unsized field that follows) before
666                 // summing it with `sized_size`. (Note that since #26403
667                 // is unfixed, we do not yet add the necessary padding
668                 // here. But this is where the add would go.)
669
670                 // Return the sum of sizes and max of aligns.
671                 let size = sized_size + unsized_size; // `Size` addition
672
673                 // Choose max of two known alignments (combined value must
674                 // be aligned according to more restrictive of the two).
675                 let align = sized_align.max(unsized_align);
676
677                 // Issue #27023: must add any necessary padding to `size`
678                 // (to make it a multiple of `align`) before returning it.
679                 let size = size.align_to(align);
680
681                 // Check if this brought us over the size limit.
682                 if size.bytes() >= self.tcx.data_layout.obj_size_bound() {
683                     throw_ub!(InvalidMeta("total size is bigger than largest supported object"));
684                 }
685                 Ok(Some((size, align)))
686             }
687             ty::Dynamic(..) => {
688                 let vtable = self.scalar_to_ptr(metadata.unwrap_meta());
689                 // Read size and align from vtable (already checks size).
690                 Ok(Some(self.read_size_and_align_from_vtable(vtable)?))
691             }
692
693             ty::Slice(_) | ty::Str => {
694                 let len = metadata.unwrap_meta().to_machine_usize(self)?;
695                 let elem = layout.field(self, 0);
696
697                 // Make sure the slice is not too big.
698                 let size = elem.size.checked_mul(len, self).ok_or_else(|| {
699                     err_ub!(InvalidMeta("slice is bigger than largest supported object"))
700                 })?;
701                 Ok(Some((size, elem.align.abi)))
702             }
703
704             ty::Foreign(_) => Ok(None),
705
706             _ => span_bug!(self.cur_span(), "size_and_align_of::<{:?}> not supported", layout.ty),
707         }
708     }
709     #[inline]
710     pub fn size_and_align_of_mplace(
711         &self,
712         mplace: &MPlaceTy<'tcx, M::PointerTag>,
713     ) -> InterpResult<'tcx, Option<(Size, Align)>> {
714         self.size_and_align_of(&mplace.meta, &mplace.layout)
715     }
716
717     #[instrument(skip(self, body, return_place, return_to_block), level = "debug")]
718     pub fn push_stack_frame(
719         &mut self,
720         instance: ty::Instance<'tcx>,
721         body: &'mir mir::Body<'tcx>,
722         return_place: Option<&PlaceTy<'tcx, M::PointerTag>>,
723         return_to_block: StackPopCleanup,
724     ) -> InterpResult<'tcx> {
725         debug!("body: {:#?}", body);
726         // first push a stack frame so we have access to the local substs
727         let pre_frame = Frame {
728             body,
729             loc: Err(body.span), // Span used for errors caused during preamble.
730             return_to_block,
731             return_place: return_place.copied(),
732             // empty local array, we fill it in below, after we are inside the stack frame and
733             // all methods actually know about the frame
734             locals: IndexVec::new(),
735             instance,
736             tracing_span: SpanGuard::new(),
737             extra: (),
738         };
739         let frame = M::init_frame_extra(self, pre_frame)?;
740         self.stack_mut().push(frame);
741
742         // Make sure all the constants required by this frame evaluate successfully (post-monomorphization check).
743         for const_ in &body.required_consts {
744             let span = const_.span;
745             let const_ =
746                 self.subst_from_current_frame_and_normalize_erasing_regions(const_.literal)?;
747             self.mir_const_to_op(&const_, None).map_err(|err| {
748                 // If there was an error, set the span of the current frame to this constant.
749                 // Avoiding doing this when evaluation succeeds.
750                 self.frame_mut().loc = Err(span);
751                 err
752             })?;
753         }
754
755         // Locals are initially uninitialized.
756         let dummy = LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
757         let mut locals = IndexVec::from_elem(dummy, &body.local_decls);
758
759         // Now mark those locals as dead that we do not want to initialize
760         // Mark locals that use `Storage*` annotations as dead on function entry.
761         let always_live = AlwaysLiveLocals::new(self.body());
762         for local in locals.indices() {
763             if !always_live.contains(local) {
764                 locals[local].value = LocalValue::Dead;
765             }
766         }
767         // done
768         self.frame_mut().locals = locals;
769         M::after_stack_push(self)?;
770         self.frame_mut().loc = Ok(mir::Location::START);
771
772         let span = info_span!("frame", "{}", instance);
773         self.frame_mut().tracing_span.enter(span);
774
775         Ok(())
776     }
777
778     /// Jump to the given block.
779     #[inline]
780     pub fn go_to_block(&mut self, target: mir::BasicBlock) {
781         self.frame_mut().loc = Ok(mir::Location { block: target, statement_index: 0 });
782     }
783
784     /// *Return* to the given `target` basic block.
785     /// Do *not* use for unwinding! Use `unwind_to_block` instead.
786     ///
787     /// If `target` is `None`, that indicates the function cannot return, so we raise UB.
788     pub fn return_to_block(&mut self, target: Option<mir::BasicBlock>) -> InterpResult<'tcx> {
789         if let Some(target) = target {
790             self.go_to_block(target);
791             Ok(())
792         } else {
793             throw_ub!(Unreachable)
794         }
795     }
796
797     /// *Unwind* to the given `target` basic block.
798     /// Do *not* use for returning! Use `return_to_block` instead.
799     ///
800     /// If `target` is `StackPopUnwind::Skip`, that indicates the function does not need cleanup
801     /// during unwinding, and we will just keep propagating that upwards.
802     ///
803     /// If `target` is `StackPopUnwind::NotAllowed`, that indicates the function does not allow
804     /// unwinding, and doing so is UB.
805     pub fn unwind_to_block(&mut self, target: StackPopUnwind) -> InterpResult<'tcx> {
806         self.frame_mut().loc = match target {
807             StackPopUnwind::Cleanup(block) => Ok(mir::Location { block, statement_index: 0 }),
808             StackPopUnwind::Skip => Err(self.frame_mut().body.span),
809             StackPopUnwind::NotAllowed => {
810                 throw_ub_format!("unwinding past a stack frame that does not allow unwinding")
811             }
812         };
813         Ok(())
814     }
815
816     /// Pops the current frame from the stack, deallocating the
817     /// memory for allocated locals.
818     ///
819     /// If `unwinding` is `false`, then we are performing a normal return
820     /// from a function. In this case, we jump back into the frame of the caller,
821     /// and continue execution as normal.
822     ///
823     /// If `unwinding` is `true`, then we are in the middle of a panic,
824     /// and need to unwind this frame. In this case, we jump to the
825     /// `cleanup` block for the function, which is responsible for running
826     /// `Drop` impls for any locals that have been initialized at this point.
827     /// The cleanup block ends with a special `Resume` terminator, which will
828     /// cause us to continue unwinding.
829     #[instrument(skip(self), level = "debug")]
830     pub(super) fn pop_stack_frame(&mut self, unwinding: bool) -> InterpResult<'tcx> {
831         info!(
832             "popping stack frame ({})",
833             if unwinding { "during unwinding" } else { "returning from function" }
834         );
835
836         // Sanity check `unwinding`.
837         assert_eq!(
838             unwinding,
839             match self.frame().loc {
840                 Ok(loc) => self.body().basic_blocks()[loc.block].is_cleanup,
841                 Err(_) => true,
842             }
843         );
844
845         if unwinding && self.frame_idx() == 0 {
846             throw_ub_format!("unwinding past the topmost frame of the stack");
847         }
848
849         let frame =
850             self.stack_mut().pop().expect("tried to pop a stack frame, but there were none");
851
852         if !unwinding {
853             // Copy the return value to the caller's stack frame.
854             if let Some(ref return_place) = frame.return_place {
855                 let op = self.access_local(&frame, mir::RETURN_PLACE, None)?;
856                 self.copy_op_transmute(&op, return_place)?;
857                 trace!("{:?}", self.dump_place(**return_place));
858             } else {
859                 throw_ub!(Unreachable);
860             }
861         }
862
863         let return_to_block = frame.return_to_block;
864
865         // Now where do we jump next?
866
867         // Usually we want to clean up (deallocate locals), but in a few rare cases we don't.
868         // In that case, we return early. We also avoid validation in that case,
869         // because this is CTFE and the final value will be thoroughly validated anyway.
870         let cleanup = match return_to_block {
871             StackPopCleanup::Goto { .. } => true,
872             StackPopCleanup::Root { cleanup, .. } => cleanup,
873         };
874
875         if !cleanup {
876             assert!(self.stack().is_empty(), "only the topmost frame should ever be leaked");
877             assert!(!unwinding, "tried to skip cleanup during unwinding");
878             // Leak the locals, skip validation, skip machine hook.
879             return Ok(());
880         }
881
882         debug!("locals: {:#?}", frame.locals);
883
884         // Cleanup: deallocate all locals that are backed by an allocation.
885         for local in &frame.locals {
886             self.deallocate_local(local.value)?;
887         }
888
889         if M::after_stack_pop(self, frame, unwinding)? == StackPopJump::NoJump {
890             // The hook already did everything.
891             // We want to skip the `info!` below, hence early return.
892             return Ok(());
893         }
894         // Normal return, figure out where to jump.
895         if unwinding {
896             // Follow the unwind edge.
897             let unwind = match return_to_block {
898                 StackPopCleanup::Goto { unwind, .. } => unwind,
899                 StackPopCleanup::Root { .. } => {
900                     panic!("encountered StackPopCleanup::Root when unwinding!")
901                 }
902             };
903             self.unwind_to_block(unwind)
904         } else {
905             // Follow the normal return edge.
906             match return_to_block {
907                 StackPopCleanup::Goto { ret, .. } => self.return_to_block(ret),
908                 StackPopCleanup::Root { .. } => {
909                     assert!(
910                         self.stack().is_empty(),
911                         "only the topmost frame can have StackPopCleanup::Root"
912                     );
913                     Ok(())
914                 }
915             }
916         }
917     }
918
919     /// Mark a storage as live, killing the previous content.
920     pub fn storage_live(&mut self, local: mir::Local) -> InterpResult<'tcx> {
921         assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
922         trace!("{:?} is now live", local);
923
924         let local_val = LocalValue::Uninitialized;
925         // StorageLive expects the local to be dead, and marks it live.
926         let old = mem::replace(&mut self.frame_mut().locals[local].value, local_val);
927         if !matches!(old, LocalValue::Dead) {
928             throw_ub_format!("StorageLive on a local that was already live");
929         }
930         Ok(())
931     }
932
933     pub fn storage_dead(&mut self, local: mir::Local) -> InterpResult<'tcx> {
934         assert!(local != mir::RETURN_PLACE, "Cannot make return place dead");
935         trace!("{:?} is now dead", local);
936
937         // It is entirely okay for this local to be already dead (at least that's how we currently generate MIR)
938         let old = mem::replace(&mut self.frame_mut().locals[local].value, LocalValue::Dead);
939         self.deallocate_local(old)?;
940         Ok(())
941     }
942
943     #[instrument(skip(self), level = "debug")]
944     fn deallocate_local(&mut self, local: LocalValue<M::PointerTag>) -> InterpResult<'tcx> {
945         if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local {
946             // All locals have a backing allocation, even if the allocation is empty
947             // due to the local having ZST type. Hence we can `unwrap`.
948             trace!(
949                 "deallocating local {:?}: {:?}",
950                 local,
951                 self.memory.dump_alloc(ptr.provenance.unwrap().get_alloc_id())
952             );
953             self.memory.deallocate(ptr, None, MemoryKind::Stack)?;
954         };
955         Ok(())
956     }
957
958     pub fn eval_to_allocation(
959         &self,
960         gid: GlobalId<'tcx>,
961     ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
962         // For statics we pick `ParamEnv::reveal_all`, because statics don't have generics
963         // and thus don't care about the parameter environment. While we could just use
964         // `self.param_env`, that would mean we invoke the query to evaluate the static
965         // with different parameter environments, thus causing the static to be evaluated
966         // multiple times.
967         let param_env = if self.tcx.is_static(gid.instance.def_id()) {
968             ty::ParamEnv::reveal_all()
969         } else {
970             self.param_env
971         };
972         let param_env = param_env.with_const();
973         let val = self.tcx.eval_to_allocation_raw(param_env.and(gid))?;
974         self.raw_const_to_mplace(val)
975     }
976
977     #[must_use]
978     pub fn dump_place(&self, place: Place<M::PointerTag>) -> PlacePrinter<'_, 'mir, 'tcx, M> {
979         PlacePrinter { ecx: self, place }
980     }
981
982     #[must_use]
983     pub fn generate_stacktrace(&self) -> Vec<FrameInfo<'tcx>> {
984         let mut frames = Vec::new();
985         for frame in self
986             .stack()
987             .iter()
988             .rev()
989             .skip_while(|frame| frame.instance.def.requires_caller_location(*self.tcx))
990         {
991             let lint_root = frame.current_source_info().and_then(|source_info| {
992                 match &frame.body.source_scopes[source_info.scope].local_data {
993                     mir::ClearCrossCrate::Set(data) => Some(data.lint_root),
994                     mir::ClearCrossCrate::Clear => None,
995                 }
996             });
997             let span = frame.current_span();
998
999             frames.push(FrameInfo { span, instance: frame.instance, lint_root });
1000         }
1001         trace!("generate stacktrace: {:#?}", frames);
1002         frames
1003     }
1004 }
1005
1006 #[doc(hidden)]
1007 /// Helper struct for the `dump_place` function.
1008 pub struct PlacePrinter<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> {
1009     ecx: &'a InterpCx<'mir, 'tcx, M>,
1010     place: Place<M::PointerTag>,
1011 }
1012
1013 impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug
1014     for PlacePrinter<'a, 'mir, 'tcx, M>
1015 {
1016     fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1017         match self.place {
1018             Place::Local { frame, local } => {
1019                 let mut allocs = Vec::new();
1020                 write!(fmt, "{:?}", local)?;
1021                 if frame != self.ecx.frame_idx() {
1022                     write!(fmt, " ({} frames up)", self.ecx.frame_idx() - frame)?;
1023                 }
1024                 write!(fmt, ":")?;
1025
1026                 match self.ecx.stack()[frame].locals[local].value {
1027                     LocalValue::Dead => write!(fmt, " is dead")?,
1028                     LocalValue::Uninitialized => write!(fmt, " is uninitialized")?,
1029                     LocalValue::Live(Operand::Indirect(mplace)) => {
1030                         write!(
1031                             fmt,
1032                             " by align({}){} ref {:?}:",
1033                             mplace.align.bytes(),
1034                             match mplace.meta {
1035                                 MemPlaceMeta::Meta(meta) => format!(" meta({:?})", meta),
1036                                 MemPlaceMeta::Poison | MemPlaceMeta::None => String::new(),
1037                             },
1038                             mplace.ptr,
1039                         )?;
1040                         allocs.extend(mplace.ptr.provenance.map(Provenance::get_alloc_id));
1041                     }
1042                     LocalValue::Live(Operand::Immediate(Immediate::Scalar(val))) => {
1043                         write!(fmt, " {:?}", val)?;
1044                         if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr, _size)) = val {
1045                             allocs.push(ptr.provenance.get_alloc_id());
1046                         }
1047                     }
1048                     LocalValue::Live(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
1049                         write!(fmt, " ({:?}, {:?})", val1, val2)?;
1050                         if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr, _size)) = val1 {
1051                             allocs.push(ptr.provenance.get_alloc_id());
1052                         }
1053                         if let ScalarMaybeUninit::Scalar(Scalar::Ptr(ptr, _size)) = val2 {
1054                             allocs.push(ptr.provenance.get_alloc_id());
1055                         }
1056                     }
1057                 }
1058
1059                 write!(fmt, ": {:?}", self.ecx.memory.dump_allocs(allocs))
1060             }
1061             Place::Ptr(mplace) => match mplace.ptr.provenance.map(Provenance::get_alloc_id) {
1062                 Some(alloc_id) => write!(
1063                     fmt,
1064                     "by align({}) ref {:?}: {:?}",
1065                     mplace.align.bytes(),
1066                     mplace.ptr,
1067                     self.ecx.memory.dump_alloc(alloc_id)
1068                 ),
1069                 ptr => write!(fmt, " integral by ref: {:?}", ptr),
1070             },
1071         }
1072     }
1073 }
1074
1075 impl<'ctx, 'mir, 'tcx, Tag: Provenance, Extra> HashStable<StableHashingContext<'ctx>>
1076     for Frame<'mir, 'tcx, Tag, Extra>
1077 where
1078     Extra: HashStable<StableHashingContext<'ctx>>,
1079     Tag: HashStable<StableHashingContext<'ctx>>,
1080 {
1081     fn hash_stable(&self, hcx: &mut StableHashingContext<'ctx>, hasher: &mut StableHasher) {
1082         // Exhaustive match on fields to make sure we forget no field.
1083         let Frame {
1084             body,
1085             instance,
1086             return_to_block,
1087             return_place,
1088             locals,
1089             loc,
1090             extra,
1091             tracing_span: _,
1092         } = self;
1093         body.hash_stable(hcx, hasher);
1094         instance.hash_stable(hcx, hasher);
1095         return_to_block.hash_stable(hcx, hasher);
1096         return_place.as_ref().map(|r| &**r).hash_stable(hcx, hasher);
1097         locals.hash_stable(hcx, hasher);
1098         loc.hash_stable(hcx, hasher);
1099         extra.hash_stable(hcx, hasher);
1100     }
1101 }