1 use rustc_hir::def::DefKind;
2 use rustc_hir::LangItem;
4 use rustc_middle::mir::interpret::PointerArithmetic;
5 use rustc_middle::ty::layout::FnAbiOf;
6 use rustc_middle::ty::{self, Ty, TyCtxt};
7 use std::borrow::Borrow;
9 use std::ops::ControlFlow;
11 use rustc_data_structures::fx::FxIndexMap;
12 use rustc_data_structures::fx::IndexEntry;
15 use rustc_ast::Mutability;
16 use rustc_hir::def_id::DefId;
17 use rustc_middle::mir::AssertMessage;
18 use rustc_session::Limit;
19 use rustc_span::symbol::{sym, Symbol};
20 use rustc_target::abi::{Align, Size};
21 use rustc_target::spec::abi::Abi as CallAbi;
23 use crate::interpret::{
24 self, compile_time_machine, AllocId, ConstAllocation, FnVal, Frame, ImmTy, InterpCx,
25 InterpResult, OpTy, PlaceTy, Pointer, Scalar, StackPopUnwind,
30 /// Extra machine state for CTFE, and the Machine instance
31 pub struct CompileTimeInterpreter<'mir, 'tcx> {
32 /// For now, the number of terminators that can be evaluated before we throw a resource
35 /// Setting this to `0` disables the limit and allows the interpreter to run forever.
36 pub(super) steps_remaining: usize,
38 /// The virtual call stack.
39 pub(super) stack: Vec<Frame<'mir, 'tcx, AllocId, ()>>,
41 /// We need to make sure consts never point to anything mutable, even recursively. That is
42 /// relied on for pattern matching on consts with references.
43 /// To achieve this, two pieces have to work together:
44 /// * Interning makes everything outside of statics immutable.
45 /// * Pointers to allocations inside of statics can never leak outside, to a non-static global.
46 /// This boolean here controls the second part.
47 pub(super) can_access_statics: bool,
49 /// Whether to check alignment during evaluation.
50 pub(super) check_alignment: bool,
53 impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> {
55 const_eval_limit: Limit,
56 can_access_statics: bool,
57 check_alignment: bool,
59 CompileTimeInterpreter {
60 steps_remaining: const_eval_limit.0,
68 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxIndexMap<K, V> {
70 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
74 FxIndexMap::contains_key(self, k)
78 fn insert(&mut self, k: K, v: V) -> Option<V> {
79 FxIndexMap::insert(self, k, v)
83 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
87 FxIndexMap::remove(self, k)
91 fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
92 self.iter().filter_map(move |(k, v)| f(k, &*v)).collect()
96 fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
101 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
107 fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
108 match self.entry(k) {
109 IndexEntry::Occupied(e) => Ok(e.into_mut()),
110 IndexEntry::Vacant(e) => {
118 pub(crate) type CompileTimeEvalContext<'mir, 'tcx> =
119 InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>;
121 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
122 pub enum MemoryKind {
126 impl fmt::Display for MemoryKind {
127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129 MemoryKind::Heap => write!(f, "heap allocation"),
134 impl interpret::MayLeak for MemoryKind {
136 fn may_leak(self) -> bool {
138 MemoryKind::Heap => false,
143 impl interpret::MayLeak for ! {
145 fn may_leak(self) -> bool {
146 // `self` is uninhabited
151 impl<'mir, 'tcx: 'mir> CompileTimeEvalContext<'mir, 'tcx> {
152 /// "Intercept" a function call, because we have something special to do for it.
153 /// All `#[rustc_do_not_const_check]` functions should be hooked here.
154 /// If this returns `Some` function, which may be `instance` or a different function with
155 /// compatible arguments, then evaluation should continue with that function.
156 /// If this returns `None`, the function call has been handled and the function has returned.
157 fn hook_special_const_fn(
159 instance: ty::Instance<'tcx>,
161 dest: &PlaceTy<'tcx>,
162 ret: Option<mir::BasicBlock>,
163 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
164 let def_id = instance.def_id();
166 if Some(def_id) == self.tcx.lang_items().panic_display()
167 || Some(def_id) == self.tcx.lang_items().begin_panic_fn()
170 assert!(args.len() == 1);
172 let mut msg_place = self.deref_operand(&args[0])?;
173 while msg_place.layout.ty.is_ref() {
174 msg_place = self.deref_operand(&msg_place.into())?;
177 let msg = Symbol::intern(self.read_str(&msg_place)?);
178 let span = self.find_closest_untracked_caller_location();
179 let (file, line, col) = self.location_triple_for_span(span);
180 return Err(ConstEvalErrKind::Panic { msg, file, line, col }.into());
181 } else if Some(def_id) == self.tcx.lang_items().panic_fmt() {
182 // For panic_fmt, call const_panic_fmt instead.
183 let const_def_id = self.tcx.require_lang_item(LangItem::ConstPanicFmt, None);
184 let new_instance = ty::Instance::resolve(
186 ty::ParamEnv::reveal_all(),
193 return Ok(Some(new_instance));
194 } else if Some(def_id) == self.tcx.lang_items().align_offset_fn() {
195 // For align_offset, we replace the function call if the pointer has no address.
196 match self.align_offset(instance, args, dest, ret)? {
197 ControlFlow::Continue(()) => return Ok(Some(instance)),
198 ControlFlow::Break(()) => return Ok(None),
204 /// `align_offset(ptr, target_align)` needs special handling in const eval, because the pointer
205 /// may not have an address.
207 /// If `ptr` does have a known address, then we return `CONTINUE` and the function call should
208 /// proceed as normal.
210 /// If `ptr` doesn't have an address, but its underlying allocation's alignment is at most
211 /// `target_align`, then we call the function again with an dummy address relative to the
214 /// If `ptr` doesn't have an address and `target_align` is stricter than the underlying
215 /// allocation's alignment, then we return `usize::MAX` immediately.
218 instance: ty::Instance<'tcx>,
220 dest: &PlaceTy<'tcx>,
221 ret: Option<mir::BasicBlock>,
222 ) -> InterpResult<'tcx, ControlFlow<()>> {
223 assert_eq!(args.len(), 2);
225 let ptr = self.read_pointer(&args[0])?;
226 let target_align = self.read_scalar(&args[1])?.to_machine_usize(self)?;
228 if !target_align.is_power_of_two() {
229 throw_ub_format!("`align_offset` called with non-power-of-two align: {}", target_align);
232 match self.ptr_try_get_alloc_id(ptr) {
233 Ok((alloc_id, offset, _extra)) => {
234 let (_size, alloc_align, _kind) = self.get_alloc_info(alloc_id);
236 if target_align <= alloc_align.bytes() {
237 // Extract the address relative to the allocation base that is definitely
238 // sufficiently aligned and call `align_offset` again.
239 let addr = ImmTy::from_uint(offset.bytes(), args[0].layout).into();
240 let align = ImmTy::from_uint(target_align, args[1].layout).into();
241 let fn_abi = self.fn_abi_of_instance(instance, ty::List::empty())?;
243 // We replace the entire entire function call with a "tail call".
244 // Note that this happens before the frame of the original function
245 // is pushed on the stack.
247 FnVal::Instance(instance),
248 (CallAbi::Rust, fn_abi),
250 /* with_caller_location = */ false,
253 StackPopUnwind::NotAllowed,
255 Ok(ControlFlow::BREAK)
257 // Not alignable in const, return `usize::MAX`.
258 let usize_max = Scalar::from_machine_usize(self.machine_usize_max(), self);
259 self.write_scalar(usize_max, dest)?;
260 self.return_to_block(ret)?;
261 Ok(ControlFlow::BREAK)
265 // The pointer has an address, continue with function call.
266 Ok(ControlFlow::CONTINUE)
271 /// See documentation on the `ptr_guaranteed_cmp` intrinsic.
272 fn guaranteed_cmp(&mut self, a: Scalar, b: Scalar) -> InterpResult<'tcx, u8> {
274 // Comparisons between integers are always known.
275 (Scalar::Int { .. }, Scalar::Int { .. }) => {
282 // Comparisons of abstract pointers with null pointers are known if the pointer
283 // is in bounds, because if they are in bounds, the pointer can't be null.
284 // Inequality with integers other than null can never be known for sure.
285 (Scalar::Int(int), ptr @ Scalar::Ptr(..))
286 | (ptr @ Scalar::Ptr(..), Scalar::Int(int))
287 if int.is_null() && !self.scalar_may_be_null(ptr)? =>
291 // Equality with integers can never be known for sure.
292 (Scalar::Int { .. }, Scalar::Ptr(..)) | (Scalar::Ptr(..), Scalar::Int { .. }) => 2,
293 // FIXME: return a `1` for when both sides are the same pointer, *except* that
294 // some things (like functions and vtables) do not have stable addresses
295 // so we need to be careful around them (see e.g. #73722).
296 // FIXME: return `0` for at least some comparisons where we can reliably
297 // determine the result of runtime inequality tests at compile-time.
298 // Examples include comparison of addresses in different static items.
299 (Scalar::Ptr(..), Scalar::Ptr(..)) => 2,
304 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> {
305 compile_time_machine!(<'mir, 'tcx>);
307 type MemoryKind = MemoryKind;
309 const PANIC_ON_ALLOC_FAIL: bool = false; // will be raised as a proper error
312 fn enforce_alignment(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
313 ecx.machine.check_alignment
317 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
318 ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks
322 ecx: &InterpCx<'mir, 'tcx, Self>,
323 instance: ty::InstanceDef<'tcx>,
324 ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
326 ty::InstanceDef::Item(def) => {
327 if ecx.tcx.is_ctfe_mir_available(def.did) {
328 Ok(ecx.tcx.mir_for_ctfe_opt_const_arg(def))
329 } else if ecx.tcx.def_kind(def.did) == DefKind::AssocConst {
330 let guar = ecx.tcx.sess.delay_span_bug(
331 rustc_span::DUMMY_SP,
332 "This is likely a const item that is missing from its impl",
334 throw_inval!(AlreadyReported(guar));
336 // `find_mir_or_eval_fn` checks that this is a const fn before even calling us,
337 // so this should be unreachable.
338 let path = ecx.tcx.def_path_str(def.did);
339 bug!("trying to call extern function `{path}` at compile-time");
342 _ => Ok(ecx.tcx.instance_mir(instance)),
346 fn find_mir_or_eval_fn(
347 ecx: &mut InterpCx<'mir, 'tcx, Self>,
348 instance: ty::Instance<'tcx>,
351 dest: &PlaceTy<'tcx>,
352 ret: Option<mir::BasicBlock>,
353 _unwind: StackPopUnwind, // unwinding is not supported in consts
354 ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
355 debug!("find_mir_or_eval_fn: {:?}", instance);
357 // Only check non-glue functions
358 if let ty::InstanceDef::Item(def) = instance.def {
359 // Execution might have wandered off into other crates, so we cannot do a stability-
360 // sensitive check here. But we can at least rule out functions that are not const
362 if !ecx.tcx.is_const_fn_raw(def.did) {
363 // allow calling functions inside a trait marked with #[const_trait].
364 if !ecx.tcx.is_const_default_method(def.did) {
365 // We certainly do *not* want to actually call the fn
366 // though, so be sure we return here.
367 throw_unsup_format!("calling non-const function `{}`", instance)
371 let Some(new_instance) = ecx.hook_special_const_fn(instance, args, dest, ret)? else {
375 if new_instance != instance {
376 // We call another const fn instead.
377 // However, we return the *original* instance to make backtraces work out
378 // (and we hope this does not confuse the FnAbi checks too much).
379 return Ok(Self::find_mir_or_eval_fn(
388 .map(|(body, _instance)| (body, instance)));
392 // This is a const fn. Call it.
393 Ok(Some((ecx.load_mir(instance.def, None)?, instance)))
397 ecx: &mut InterpCx<'mir, 'tcx, Self>,
398 instance: ty::Instance<'tcx>,
400 dest: &PlaceTy<'tcx, Self::Provenance>,
401 target: Option<mir::BasicBlock>,
402 _unwind: StackPopUnwind,
403 ) -> InterpResult<'tcx> {
404 // Shared intrinsics.
405 if ecx.emulate_intrinsic(instance, args, dest, target)? {
408 let intrinsic_name = ecx.tcx.item_name(instance.def_id());
410 // CTFE-specific intrinsics.
411 let Some(ret) = target else {
412 throw_unsup_format!("intrinsic `{intrinsic_name}` is not supported at compile-time");
414 match intrinsic_name {
415 sym::ptr_guaranteed_cmp => {
416 let a = ecx.read_scalar(&args[0])?;
417 let b = ecx.read_scalar(&args[1])?;
418 let cmp = ecx.guaranteed_cmp(a, b)?;
419 ecx.write_scalar(Scalar::from_u8(cmp), dest)?;
421 sym::const_allocate => {
422 let size = ecx.read_scalar(&args[0])?.to_machine_usize(ecx)?;
423 let align = ecx.read_scalar(&args[1])?.to_machine_usize(ecx)?;
425 let align = match Align::from_bytes(align) {
427 Err(err) => throw_ub_format!("align has to be a power of 2, {}", err),
430 let ptr = ecx.allocate_ptr(
431 Size::from_bytes(size as u64),
433 interpret::MemoryKind::Machine(MemoryKind::Heap),
435 ecx.write_pointer(ptr, dest)?;
437 sym::const_deallocate => {
438 let ptr = ecx.read_pointer(&args[0])?;
439 let size = ecx.read_scalar(&args[1])?.to_machine_usize(ecx)?;
440 let align = ecx.read_scalar(&args[2])?.to_machine_usize(ecx)?;
442 let size = Size::from_bytes(size);
443 let align = match Align::from_bytes(align) {
445 Err(err) => throw_ub_format!("align has to be a power of 2, {}", err),
448 // If an allocation is created in an another const,
449 // we don't deallocate it.
450 let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr)?;
451 let is_allocated_in_another_const = matches!(
452 ecx.tcx.try_get_global_alloc(alloc_id),
453 Some(interpret::GlobalAlloc::Memory(_))
456 if !is_allocated_in_another_const {
460 interpret::MemoryKind::Machine(MemoryKind::Heap),
466 "intrinsic `{intrinsic_name}` is not supported at compile-time"
471 ecx.go_to_block(ret);
476 ecx: &mut InterpCx<'mir, 'tcx, Self>,
477 msg: &AssertMessage<'tcx>,
478 _unwind: Option<mir::BasicBlock>,
479 ) -> InterpResult<'tcx> {
480 use rustc_middle::mir::AssertKind::*;
481 // Convert `AssertKind<Operand>` to `AssertKind<Scalar>`.
483 |op| ecx.read_immediate(&ecx.eval_operand(op, None)?).map(|x| x.to_const_int());
484 let err = match msg {
485 BoundsCheck { ref len, ref index } => {
486 let len = eval_to_int(len)?;
487 let index = eval_to_int(index)?;
488 BoundsCheck { len, index }
490 Overflow(op, l, r) => Overflow(*op, eval_to_int(l)?, eval_to_int(r)?),
491 OverflowNeg(op) => OverflowNeg(eval_to_int(op)?),
492 DivisionByZero(op) => DivisionByZero(eval_to_int(op)?),
493 RemainderByZero(op) => RemainderByZero(eval_to_int(op)?),
494 ResumedAfterReturn(generator_kind) => ResumedAfterReturn(*generator_kind),
495 ResumedAfterPanic(generator_kind) => ResumedAfterPanic(*generator_kind),
497 Err(ConstEvalErrKind::AssertFailure(err).into())
500 fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, msg: String) -> InterpResult<'tcx, !> {
501 Err(ConstEvalErrKind::Abort(msg).into())
505 _ecx: &InterpCx<'mir, 'tcx, Self>,
508 _right: &ImmTy<'tcx>,
509 ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
510 throw_unsup_format!("pointer arithmetic or comparison is not supported at compile-time");
513 fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
514 // The step limit has already been hit in a previous call to `before_terminator`.
515 if ecx.machine.steps_remaining == 0 {
519 ecx.machine.steps_remaining -= 1;
520 if ecx.machine.steps_remaining == 0 {
521 throw_exhaust!(StepLimitReached)
529 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
530 _ptr: Pointer<AllocId>,
531 ) -> InterpResult<'tcx> {
532 // This is only reachable with -Zunleash-the-miri-inside-of-you.
533 throw_unsup_format!("exposing pointers is not possible at compile-time")
538 ecx: &mut InterpCx<'mir, 'tcx, Self>,
539 frame: Frame<'mir, 'tcx>,
540 ) -> InterpResult<'tcx, Frame<'mir, 'tcx>> {
541 // Enforce stack size limit. Add 1 because this is run before the new frame is pushed.
542 if !ecx.recursion_limit.value_within_limit(ecx.stack().len() + 1) {
543 throw_exhaust!(StackFrameLimitReached)
551 ecx: &'a InterpCx<'mir, 'tcx, Self>,
552 ) -> &'a [Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>] {
558 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
559 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>> {
560 &mut ecx.machine.stack
563 fn before_access_global(
567 alloc: ConstAllocation<'tcx>,
568 static_def_id: Option<DefId>,
570 ) -> InterpResult<'tcx> {
571 let alloc = alloc.inner();
573 // Write access. These are never allowed, but we give a targeted error message.
574 if alloc.mutability == Mutability::Not {
575 Err(err_ub!(WriteToReadOnly(alloc_id)).into())
577 Err(ConstEvalErrKind::ModifiedGlobal.into())
580 // Read access. These are usually allowed, with some exceptions.
581 if machine.can_access_statics {
582 // Machine configuration allows us read from anything (e.g., `static` initializer).
584 } else if static_def_id.is_some() {
585 // Machine configuration does not allow us to read statics
586 // (e.g., `const` initializer).
587 // See const_eval::machine::MemoryExtra::can_access_statics for why
588 // this check is so important: if we could read statics, we could read pointers
589 // to mutable allocations *inside* statics. These allocations are not themselves
590 // statics, so pointers to them can get around the check in `validity.rs`.
591 Err(ConstEvalErrKind::ConstAccessesStatic.into())
593 // Immutable global, this read is fine.
594 // But make sure we never accept a read from something mutable, that would be
595 // unsound. The reason is that as the content of this allocation may be different
596 // now and at run-time, so if we permit reading now we might return the wrong value.
597 assert_eq!(alloc.mutability, Mutability::Not);
604 // Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups
605 // so we can end up having a file with just that impl, but for now, let's keep the impl discoverable
606 // at the bottom of this file.