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