1 use rustc_hir::def::DefKind;
2 use rustc_hir::{LangItem, CRATE_HIR_ID};
4 use rustc_middle::mir::interpret::PointerArithmetic;
5 use rustc_middle::ty::layout::FnAbiOf;
6 use rustc_middle::ty::{self, Ty, TyCtxt};
7 use rustc_session::lint::builtin::INVALID_ALIGNMENT;
8 use std::borrow::Borrow;
10 use std::ops::ControlFlow;
12 use rustc_data_structures::fx::FxIndexMap;
13 use rustc_data_structures::fx::IndexEntry;
16 use rustc_ast::Mutability;
17 use rustc_hir::def_id::DefId;
18 use rustc_middle::mir::AssertMessage;
19 use rustc_session::Limit;
20 use rustc_span::symbol::{sym, Symbol};
21 use rustc_target::abi::{Align, Size};
22 use rustc_target::spec::abi::Abi as CallAbi;
24 use crate::interpret::{
25 self, compile_time_machine, AllocId, ConstAllocation, FnVal, Frame, ImmTy, InterpCx,
26 InterpResult, OpTy, PlaceTy, Pointer, Scalar, StackPopUnwind,
31 /// Extra machine state for CTFE, and the Machine instance
32 pub struct CompileTimeInterpreter<'mir, 'tcx> {
33 /// For now, the number of terminators that can be evaluated before we throw a resource
36 /// Setting this to `0` disables the limit and allows the interpreter to run forever.
37 pub(super) steps_remaining: usize,
39 /// The virtual call stack.
40 pub(super) stack: Vec<Frame<'mir, 'tcx, AllocId, ()>>,
42 /// We need to make sure consts never point to anything mutable, even recursively. That is
43 /// relied on for pattern matching on consts with references.
44 /// To achieve this, two pieces have to work together:
45 /// * Interning makes everything outside of statics immutable.
46 /// * Pointers to allocations inside of statics can never leak outside, to a non-static global.
47 /// This boolean here controls the second part.
48 pub(super) can_access_statics: bool,
50 /// Whether to check alignment during evaluation.
51 pub(super) check_alignment: CheckAlignment,
54 #[derive(Copy, Clone)]
55 pub enum CheckAlignment {
56 /// Ignore alignment when following relocations.
57 /// This is mainly used in interning.
59 /// Hard error when dereferencing a misaligned pointer.
61 /// Emit a future incompat lint when dereferencing a misaligned pointer.
66 pub fn should_check(&self) -> bool {
68 CheckAlignment::No => false,
69 CheckAlignment::Error | CheckAlignment::FutureIncompat => true,
74 impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> {
76 const_eval_limit: Limit,
77 can_access_statics: bool,
78 check_alignment: CheckAlignment,
80 CompileTimeInterpreter {
81 steps_remaining: const_eval_limit.0,
89 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxIndexMap<K, V> {
91 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
95 FxIndexMap::contains_key(self, k)
99 fn insert(&mut self, k: K, v: V) -> Option<V> {
100 FxIndexMap::insert(self, k, v)
104 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
108 FxIndexMap::remove(self, k)
112 fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
113 self.iter().filter_map(move |(k, v)| f(k, &*v)).collect()
117 fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
122 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
128 fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
129 match self.entry(k) {
130 IndexEntry::Occupied(e) => Ok(e.into_mut()),
131 IndexEntry::Vacant(e) => {
139 pub(crate) type CompileTimeEvalContext<'mir, 'tcx> =
140 InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>;
142 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
143 pub enum MemoryKind {
147 impl fmt::Display for MemoryKind {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150 MemoryKind::Heap => write!(f, "heap allocation"),
155 impl interpret::MayLeak for MemoryKind {
157 fn may_leak(self) -> bool {
159 MemoryKind::Heap => false,
164 impl interpret::MayLeak for ! {
166 fn may_leak(self) -> bool {
167 // `self` is uninhabited
172 impl<'mir, 'tcx: 'mir> CompileTimeEvalContext<'mir, 'tcx> {
173 /// "Intercept" a function call, because we have something special to do for it.
174 /// All `#[rustc_do_not_const_check]` functions should be hooked here.
175 /// If this returns `Some` function, which may be `instance` or a different function with
176 /// compatible arguments, then evaluation should continue with that function.
177 /// If this returns `None`, the function call has been handled and the function has returned.
178 fn hook_special_const_fn(
180 instance: ty::Instance<'tcx>,
182 dest: &PlaceTy<'tcx>,
183 ret: Option<mir::BasicBlock>,
184 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
185 let def_id = instance.def_id();
187 if Some(def_id) == self.tcx.lang_items().panic_display()
188 || Some(def_id) == self.tcx.lang_items().begin_panic_fn()
191 assert!(args.len() == 1);
193 let mut msg_place = self.deref_operand(&args[0])?;
194 while msg_place.layout.ty.is_ref() {
195 msg_place = self.deref_operand(&msg_place.into())?;
198 let msg = Symbol::intern(self.read_str(&msg_place)?);
199 let span = self.find_closest_untracked_caller_location();
200 let (file, line, col) = self.location_triple_for_span(span);
201 return Err(ConstEvalErrKind::Panic { msg, file, line, col }.into());
202 } else if Some(def_id) == self.tcx.lang_items().panic_fmt() {
203 // For panic_fmt, call const_panic_fmt instead.
204 let const_def_id = self.tcx.require_lang_item(LangItem::ConstPanicFmt, None);
205 let new_instance = ty::Instance::resolve(
207 ty::ParamEnv::reveal_all(),
214 return Ok(Some(new_instance));
215 } else if Some(def_id) == self.tcx.lang_items().align_offset_fn() {
216 // For align_offset, we replace the function call if the pointer has no address.
217 match self.align_offset(instance, args, dest, ret)? {
218 ControlFlow::Continue(()) => return Ok(Some(instance)),
219 ControlFlow::Break(()) => return Ok(None),
225 /// `align_offset(ptr, target_align)` needs special handling in const eval, because the pointer
226 /// may not have an address.
228 /// If `ptr` does have a known address, then we return `Continue(())` and the function call should
229 /// proceed as normal.
231 /// If `ptr` doesn't have an address, but its underlying allocation's alignment is at most
232 /// `target_align`, then we call the function again with an dummy address relative to the
235 /// If `ptr` doesn't have an address and `target_align` is stricter than the underlying
236 /// allocation's alignment, then we return `usize::MAX` immediately.
239 instance: ty::Instance<'tcx>,
241 dest: &PlaceTy<'tcx>,
242 ret: Option<mir::BasicBlock>,
243 ) -> InterpResult<'tcx, ControlFlow<()>> {
244 assert_eq!(args.len(), 2);
246 let ptr = self.read_pointer(&args[0])?;
247 let target_align = self.read_scalar(&args[1])?.to_machine_usize(self)?;
249 if !target_align.is_power_of_two() {
250 throw_ub_format!("`align_offset` called with non-power-of-two align: {}", target_align);
253 match self.ptr_try_get_alloc_id(ptr) {
254 Ok((alloc_id, offset, _extra)) => {
255 let (_size, alloc_align, _kind) = self.get_alloc_info(alloc_id);
257 if target_align <= alloc_align.bytes() {
258 // Extract the address relative to the allocation base that is definitely
259 // sufficiently aligned and call `align_offset` again.
260 let addr = ImmTy::from_uint(offset.bytes(), args[0].layout).into();
261 let align = ImmTy::from_uint(target_align, args[1].layout).into();
262 let fn_abi = self.fn_abi_of_instance(instance, ty::List::empty())?;
264 // We replace the entire function call with a "tail call".
265 // Note that this happens before the frame of the original function
266 // is pushed on the stack.
268 FnVal::Instance(instance),
269 (CallAbi::Rust, fn_abi),
271 /* with_caller_location = */ false,
274 StackPopUnwind::NotAllowed,
276 Ok(ControlFlow::Break(()))
278 // Not alignable in const, return `usize::MAX`.
279 let usize_max = Scalar::from_machine_usize(self.machine_usize_max(), self);
280 self.write_scalar(usize_max, dest)?;
281 self.return_to_block(ret)?;
282 Ok(ControlFlow::Break(()))
286 // The pointer has an address, continue with function call.
287 Ok(ControlFlow::Continue(()))
292 /// See documentation on the `ptr_guaranteed_cmp` intrinsic.
293 fn guaranteed_cmp(&mut self, a: Scalar, b: Scalar) -> InterpResult<'tcx, u8> {
295 // Comparisons between integers are always known.
296 (Scalar::Int { .. }, Scalar::Int { .. }) => {
303 // Comparisons of abstract pointers with null pointers are known if the pointer
304 // is in bounds, because if they are in bounds, the pointer can't be null.
305 // Inequality with integers other than null can never be known for sure.
306 (Scalar::Int(int), ptr @ Scalar::Ptr(..))
307 | (ptr @ Scalar::Ptr(..), Scalar::Int(int))
308 if int.is_null() && !self.scalar_may_be_null(ptr)? =>
312 // Equality with integers can never be known for sure.
313 (Scalar::Int { .. }, Scalar::Ptr(..)) | (Scalar::Ptr(..), Scalar::Int { .. }) => 2,
314 // FIXME: return a `1` for when both sides are the same pointer, *except* that
315 // some things (like functions and vtables) do not have stable addresses
316 // so we need to be careful around them (see e.g. #73722).
317 // FIXME: return `0` for at least some comparisons where we can reliably
318 // determine the result of runtime inequality tests at compile-time.
319 // Examples include comparison of addresses in different static items.
320 (Scalar::Ptr(..), Scalar::Ptr(..)) => 2,
325 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> {
326 compile_time_machine!(<'mir, 'tcx>);
328 type MemoryKind = MemoryKind;
330 const PANIC_ON_ALLOC_FAIL: bool = false; // will be raised as a proper error
333 fn enforce_alignment(ecx: &InterpCx<'mir, 'tcx, Self>) -> CheckAlignment {
334 ecx.machine.check_alignment
338 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
339 ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks
342 fn alignment_check_failed(
343 ecx: &InterpCx<'mir, 'tcx, Self>,
346 check: CheckAlignment,
347 ) -> InterpResult<'tcx, ()> {
348 let err = err_ub!(AlignmentCheckFailed { has, required }).into();
350 CheckAlignment::Error => Err(err),
351 CheckAlignment::No => span_bug!(
353 "`alignment_check_failed` called when no alignment check requested"
355 CheckAlignment::FutureIncompat => {
356 let err = ConstEvalErr::new(ecx, err, None);
357 ecx.tcx.struct_span_lint_hir(
359 ecx.stack().iter().find_map(|frame| frame.lint_root()).unwrap_or(CRATE_HIR_ID),
361 err.error.to_string(),
363 err.decorate(db, |_| {});
373 ecx: &InterpCx<'mir, 'tcx, Self>,
374 instance: ty::InstanceDef<'tcx>,
375 ) -> InterpResult<'tcx, &'tcx mir::Body<'tcx>> {
377 ty::InstanceDef::Item(def) => {
378 if ecx.tcx.is_ctfe_mir_available(def.did) {
379 Ok(ecx.tcx.mir_for_ctfe_opt_const_arg(def))
380 } else if ecx.tcx.def_kind(def.did) == DefKind::AssocConst {
381 let guar = ecx.tcx.sess.delay_span_bug(
382 rustc_span::DUMMY_SP,
383 "This is likely a const item that is missing from its impl",
385 throw_inval!(AlreadyReported(guar));
387 // `find_mir_or_eval_fn` checks that this is a const fn before even calling us,
388 // so this should be unreachable.
389 let path = ecx.tcx.def_path_str(def.did);
390 bug!("trying to call extern function `{path}` at compile-time");
393 _ => Ok(ecx.tcx.instance_mir(instance)),
397 fn find_mir_or_eval_fn(
398 ecx: &mut InterpCx<'mir, 'tcx, Self>,
399 instance: ty::Instance<'tcx>,
402 dest: &PlaceTy<'tcx>,
403 ret: Option<mir::BasicBlock>,
404 _unwind: StackPopUnwind, // unwinding is not supported in consts
405 ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
406 debug!("find_mir_or_eval_fn: {:?}", instance);
408 // Only check non-glue functions
409 if let ty::InstanceDef::Item(def) = instance.def {
410 // Execution might have wandered off into other crates, so we cannot do a stability-
411 // sensitive check here. But we can at least rule out functions that are not const
413 if !ecx.tcx.is_const_fn_raw(def.did) {
414 // allow calling functions inside a trait marked with #[const_trait].
415 if !ecx.tcx.is_const_default_method(def.did) {
416 // We certainly do *not* want to actually call the fn
417 // though, so be sure we return here.
418 throw_unsup_format!("calling non-const function `{}`", instance)
422 let Some(new_instance) = ecx.hook_special_const_fn(instance, args, dest, ret)? else {
426 if new_instance != instance {
427 // We call another const fn instead.
428 // However, we return the *original* instance to make backtraces work out
429 // (and we hope this does not confuse the FnAbi checks too much).
430 return Ok(Self::find_mir_or_eval_fn(
439 .map(|(body, _instance)| (body, instance)));
443 // This is a const fn. Call it.
444 Ok(Some((ecx.load_mir(instance.def, None)?, instance)))
448 ecx: &mut InterpCx<'mir, 'tcx, Self>,
449 instance: ty::Instance<'tcx>,
451 dest: &PlaceTy<'tcx, Self::Provenance>,
452 target: Option<mir::BasicBlock>,
453 _unwind: StackPopUnwind,
454 ) -> InterpResult<'tcx> {
455 // Shared intrinsics.
456 if ecx.emulate_intrinsic(instance, args, dest, target)? {
459 let intrinsic_name = ecx.tcx.item_name(instance.def_id());
461 // CTFE-specific intrinsics.
462 let Some(ret) = target else {
463 throw_unsup_format!("intrinsic `{intrinsic_name}` is not supported at compile-time");
465 match intrinsic_name {
466 sym::ptr_guaranteed_cmp => {
467 let a = ecx.read_scalar(&args[0])?;
468 let b = ecx.read_scalar(&args[1])?;
469 let cmp = ecx.guaranteed_cmp(a, b)?;
470 ecx.write_scalar(Scalar::from_u8(cmp), dest)?;
472 sym::const_allocate => {
473 let size = ecx.read_scalar(&args[0])?.to_machine_usize(ecx)?;
474 let align = ecx.read_scalar(&args[1])?.to_machine_usize(ecx)?;
476 let align = match Align::from_bytes(align) {
478 Err(err) => throw_ub_format!("align has to be a power of 2, {}", err),
481 let ptr = ecx.allocate_ptr(
482 Size::from_bytes(size as u64),
484 interpret::MemoryKind::Machine(MemoryKind::Heap),
486 ecx.write_pointer(ptr, dest)?;
488 sym::const_deallocate => {
489 let ptr = ecx.read_pointer(&args[0])?;
490 let size = ecx.read_scalar(&args[1])?.to_machine_usize(ecx)?;
491 let align = ecx.read_scalar(&args[2])?.to_machine_usize(ecx)?;
493 let size = Size::from_bytes(size);
494 let align = match Align::from_bytes(align) {
496 Err(err) => throw_ub_format!("align has to be a power of 2, {}", err),
499 // If an allocation is created in an another const,
500 // we don't deallocate it.
501 let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr)?;
502 let is_allocated_in_another_const = matches!(
503 ecx.tcx.try_get_global_alloc(alloc_id),
504 Some(interpret::GlobalAlloc::Memory(_))
507 if !is_allocated_in_another_const {
511 interpret::MemoryKind::Machine(MemoryKind::Heap),
517 "intrinsic `{intrinsic_name}` is not supported at compile-time"
522 ecx.go_to_block(ret);
527 ecx: &mut InterpCx<'mir, 'tcx, Self>,
528 msg: &AssertMessage<'tcx>,
529 _unwind: Option<mir::BasicBlock>,
530 ) -> InterpResult<'tcx> {
531 use rustc_middle::mir::AssertKind::*;
532 // Convert `AssertKind<Operand>` to `AssertKind<Scalar>`.
534 |op| ecx.read_immediate(&ecx.eval_operand(op, None)?).map(|x| x.to_const_int());
535 let err = match msg {
536 BoundsCheck { len, index } => {
537 let len = eval_to_int(len)?;
538 let index = eval_to_int(index)?;
539 BoundsCheck { len, index }
541 Overflow(op, l, r) => Overflow(*op, eval_to_int(l)?, eval_to_int(r)?),
542 OverflowNeg(op) => OverflowNeg(eval_to_int(op)?),
543 DivisionByZero(op) => DivisionByZero(eval_to_int(op)?),
544 RemainderByZero(op) => RemainderByZero(eval_to_int(op)?),
545 ResumedAfterReturn(generator_kind) => ResumedAfterReturn(*generator_kind),
546 ResumedAfterPanic(generator_kind) => ResumedAfterPanic(*generator_kind),
548 Err(ConstEvalErrKind::AssertFailure(err).into())
551 fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, msg: String) -> InterpResult<'tcx, !> {
552 Err(ConstEvalErrKind::Abort(msg).into())
556 _ecx: &InterpCx<'mir, 'tcx, Self>,
559 _right: &ImmTy<'tcx>,
560 ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
561 throw_unsup_format!("pointer arithmetic or comparison is not supported at compile-time");
564 fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
565 // The step limit has already been hit in a previous call to `before_terminator`.
566 if ecx.machine.steps_remaining == 0 {
570 ecx.machine.steps_remaining -= 1;
571 if ecx.machine.steps_remaining == 0 {
572 throw_exhaust!(StepLimitReached)
580 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
581 _ptr: Pointer<AllocId>,
582 ) -> InterpResult<'tcx> {
583 // This is only reachable with -Zunleash-the-miri-inside-of-you.
584 throw_unsup_format!("exposing pointers is not possible at compile-time")
589 ecx: &mut InterpCx<'mir, 'tcx, Self>,
590 frame: Frame<'mir, 'tcx>,
591 ) -> InterpResult<'tcx, Frame<'mir, 'tcx>> {
592 // Enforce stack size limit. Add 1 because this is run before the new frame is pushed.
593 if !ecx.recursion_limit.value_within_limit(ecx.stack().len() + 1) {
594 throw_exhaust!(StackFrameLimitReached)
602 ecx: &'a InterpCx<'mir, 'tcx, Self>,
603 ) -> &'a [Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>] {
609 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
610 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>> {
611 &mut ecx.machine.stack
614 fn before_access_global(
618 alloc: ConstAllocation<'tcx>,
619 static_def_id: Option<DefId>,
621 ) -> InterpResult<'tcx> {
622 let alloc = alloc.inner();
624 // Write access. These are never allowed, but we give a targeted error message.
625 if alloc.mutability == Mutability::Not {
626 Err(err_ub!(WriteToReadOnly(alloc_id)).into())
628 Err(ConstEvalErrKind::ModifiedGlobal.into())
631 // Read access. These are usually allowed, with some exceptions.
632 if machine.can_access_statics {
633 // Machine configuration allows us read from anything (e.g., `static` initializer).
635 } else if static_def_id.is_some() {
636 // Machine configuration does not allow us to read statics
637 // (e.g., `const` initializer).
638 // See const_eval::machine::MemoryExtra::can_access_statics for why
639 // this check is so important: if we could read statics, we could read pointers
640 // to mutable allocations *inside* statics. These allocations are not themselves
641 // statics, so pointers to them can get around the check in `validity.rs`.
642 Err(ConstEvalErrKind::ConstAccessesStatic.into())
644 // Immutable global, this read is fine.
645 // But make sure we never accept a read from something mutable, that would be
646 // unsound. The reason is that as the content of this allocation may be different
647 // now and at run-time, so if we permit reading now we might return the wrong value.
648 assert_eq!(alloc.mutability, Mutability::Not);
655 // Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups
656 // so we can end up having a file with just that impl, but for now, let's keep the impl discoverable
657 // at the bottom of this file.