1use std::borrow::{Borrow, Cow};
2use std::hash::Hash;
3use std::{fmt, mem};
4
5use rustc_abi::{Align, FIRST_VARIANT, FieldIdx, Size, VariantIdx};
6use rustc_ast::Mutability;
7use rustc_attr_ir::find_attr;
8use rustc_attr_ir::lang_items::LangItem;
9use rustc_data_structures::fx::{FxHashMap, FxIndexMap, IndexEntry};
10use rustc_hir::def_id::{DefId, LocalDefId};
11use rustc_hir::{CRATE_HIR_ID, HirId};
12use rustc_lint_defs::builtin::LONG_RUNNING_CONST_EVAL;
13use rustc_middle::mir;
14use rustc_middle::mir::AssertMessage;
15use rustc_middle::mir::interpret::ReportedErrorInfo;
16use rustc_middle::query::TyCtxtAt;
17use rustc_middle::ty::consts::ConstExt;
18use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, TyAndLayout, ValidityRequirement};
19use rustc_middle::ty::{self, FieldInfo, ScalarInt, Ty, TyCtxt};
20use rustc_span::{Span, Symbol, bug, span_bug, sym};
21use rustc_target::callconv::FnAbi;
22use tracing::debug;
23
24use super::error::*;
25use crate::diagnostics::{LongRunning, LongRunningWarn};
26use crate::interpret::{
27 self, AllocId, AllocInit, AllocRange, ConstAllocation, CtfeProvenance, FnArg, Frame,
28 GlobalAlloc, ImmTy, Immediate, InterpCx, InterpResult, OpTy, PlaceTy, Pointer, RangeSet,
29 RetagMode, Scalar, compile_time_machine, ensure_monomorphic_enough, err_inval, interp_ok,
30 throw_exhaust, throw_inval, throw_ub, throw_ub_format, throw_unsup, throw_unsup_format,
31 type_implements_dyn_trait,
32};
33
34const LINT_TERMINATOR_LIMIT: usize = 2_000_000;
38const TINY_LINT_TERMINATOR_LIMIT: usize = 20;
41const PROGRESS_INDICATOR_START: usize = 4_000_000;
44
45pub struct CompileTimeMachine<'tcx> {
50 pub(super) num_evaluated_steps: usize,
55
56 pub(super) stack: Vec<Frame<'tcx>>,
58
59 pub(super) can_access_mut_global: CanAccessMutGlobal,
63
64 pub(super) check_alignment: CheckAlignment,
66
67 pub(crate) static_root_ids: Option<(AllocId, LocalDefId)>,
71
72 union_data_ranges: FxHashMap<Ty<'tcx>, RangeSet>,
74
75 retag_mode: RetagMode,
77}
78
79#[derive(#[automatically_derived]
impl ::core::marker::Copy for CheckAlignment { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CheckAlignment { }
#[automatically_derived]
impl ::core::clone::Clone for CheckAlignment {
#[inline]
fn clone(&self) -> Self { *self }
}Clone)]
80pub enum CheckAlignment {
81 No,
84 Error,
86}
87
88#[derive(#[automatically_derived]
impl ::core::marker::Copy for CanAccessMutGlobal { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CanAccessMutGlobal { }
#[automatically_derived]
impl ::core::clone::Clone for CanAccessMutGlobal {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for CanAccessMutGlobal { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CanAccessMutGlobal {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
89pub(crate) enum CanAccessMutGlobal {
90 No,
91 Yes,
92}
93
94impl From<bool> for CanAccessMutGlobal {
95 fn from(value: bool) -> Self {
96 if value { Self::Yes } else { Self::No }
97 }
98}
99
100impl<'tcx> CompileTimeMachine<'tcx> {
101 pub(crate) fn new(
102 can_access_mut_global: CanAccessMutGlobal,
103 check_alignment: CheckAlignment,
104 ) -> Self {
105 CompileTimeMachine {
106 num_evaluated_steps: 0,
107 stack: Vec::new(),
108 can_access_mut_global,
109 check_alignment,
110 static_root_ids: None,
111 union_data_ranges: FxHashMap::default(),
112 retag_mode: RetagMode::Default,
113 }
114 }
115}
116
117impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxIndexMap<K, V> {
118 #[inline(always)]
119 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
120 where
121 K: Borrow<Q>,
122 {
123 FxIndexMap::contains_key(self, k)
124 }
125
126 #[inline(always)]
127 fn contains_key_ref<Q: ?Sized + Hash + Eq>(&self, k: &Q) -> bool
128 where
129 K: Borrow<Q>,
130 {
131 FxIndexMap::contains_key(self, k)
132 }
133
134 #[inline(always)]
135 fn insert(&mut self, k: K, v: V) -> Option<V> {
136 FxIndexMap::insert(self, k, v)
137 }
138
139 #[inline(always)]
140 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
141 where
142 K: Borrow<Q>,
143 {
144 FxIndexMap::swap_remove(self, k)
146 }
147
148 #[inline(always)]
149 fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
150 self.iter().filter_map(move |(k, v)| f(k, v)).collect()
151 }
152
153 #[inline(always)]
154 fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
155 match self.get(&k) {
156 Some(v) => Ok(v),
157 None => {
158 vacant()?;
159 ::rustc_span::macros::bug_impl(None,
format_args!("The CTFE machine shouldn\'t ever need to extend the alloc_map when reading"),
Location::caller())bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
160 }
161 }
162 }
163
164 #[inline(always)]
165 fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
166 match self.entry(k) {
167 IndexEntry::Occupied(e) => Ok(e.into_mut()),
168 IndexEntry::Vacant(e) => {
169 let v = vacant()?;
170 Ok(e.insert(v))
171 }
172 }
173 }
174}
175
176pub type CompileTimeInterpCx<'tcx> = InterpCx<'tcx, CompileTimeMachine<'tcx>>;
177
178#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MemoryKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::Heap { was_made_global: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Heap",
"was_made_global", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for MemoryKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for MemoryKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Heap { was_made_global: __self_0 }, Self::Heap {
was_made_global: __arg1_0 }) => __self_0 == __arg1_0,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MemoryKind {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<bool>;
}
}Eq, #[automatically_derived]
impl ::core::marker::Copy for MemoryKind { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for MemoryKind { }
#[automatically_derived]
impl ::core::clone::Clone for MemoryKind {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<bool>;
*self
}
}Clone)]
179pub enum MemoryKind {
180 Heap {
181 was_made_global: bool,
184 },
185}
186
187impl fmt::Display for MemoryKind {
188 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189 match self {
190 MemoryKind::Heap { was_made_global } => {
191 f.write_fmt(format_args!("heap allocation{0}",
if *was_made_global { " (made global)" } else { "" }))write!(f, "heap allocation{}", if *was_made_global { " (made global)" } else { "" })
192 }
193 }
194 }
195}
196
197impl interpret::MayLeak for MemoryKind {
198 #[inline(always)]
199 fn may_leak(self) -> bool {
200 match self {
201 MemoryKind::Heap { was_made_global } => was_made_global,
202 }
203 }
204}
205
206impl interpret::MayLeak for ! {
207 #[inline(always)]
208 fn may_leak(self) -> bool {
209 self
211 }
212}
213
214impl<'tcx> CompileTimeInterpCx<'tcx> {
215 fn location_triple_for_span(&self, span: Span) -> (Symbol, u32, u32) {
216 let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span);
217 let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo());
218
219 use rustc_span::RemapPathScopeComponents;
220 (
221 Symbol::intern(
222 &caller.file.name.display(RemapPathScopeComponents::DIAGNOSTICS).to_string_lossy(),
223 ),
224 u32::try_from(caller.line).unwrap(),
225 u32::try_from(caller.col_display).unwrap().checked_add(1).unwrap(),
226 )
227 }
228
229 fn hook_special_const_fn(
235 &mut self,
236 instance: ty::Instance<'tcx>,
237 args: &[FnArg<'tcx>],
238 _dest: &PlaceTy<'tcx>,
239 _ret: Option<mir::BasicBlock>,
240 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
241 let def_id = instance.def_id();
242
243 if self.tcx.is_lang_item(def_id, LangItem::PanicDisplay)
244 || self.tcx.is_lang_item(def_id, LangItem::BeginPanic)
245 {
246 let args = Self::copy_fn_args(args);
247 if !(args.len() == 1) {
::core::panicking::panic("assertion failed: args.len() == 1")
};assert!(args.len() == 1);
249
250 let mut msg_place = self.deref_pointer(&args[0])?;
251 while msg_place.layout.ty.is_ref() {
252 msg_place = self.deref_pointer(&msg_place)?;
253 }
254
255 let msg = Symbol::intern(self.read_str(&msg_place)?);
256 let span = self.find_closest_untracked_caller_location();
257 let (file, line, col) = self.location_triple_for_span(span);
258 return Err(ConstEvalErrKind::Panic { msg, file, line, col }).into();
259 } else if self.tcx.is_lang_item(def_id, LangItem::PanicFmt) {
260 let const_def_id = self.tcx.require_lang_item(LangItem::ConstPanicFmt, self.tcx.span);
262 let new_instance = ty::Instance::expect_resolve(
263 *self.tcx,
264 self.typing_env(),
265 const_def_id,
266 instance.args,
267 self.cur_span(),
268 );
269
270 return interp_ok(Some(new_instance));
271 }
272 interp_ok(Some(instance))
273 }
274
275 fn guaranteed_cmp(&mut self, a: Scalar, b: Scalar) -> InterpResult<'tcx, u8> {
283 interp_ok(match (a, b) {
284 (Scalar::Int(a), Scalar::Int(b)) => (a == b) as u8,
286 (Scalar::Int(int), Scalar::Ptr(ptr, _)) | (Scalar::Ptr(ptr, _), Scalar::Int(int)) => {
289 let int = int.to_target_usize(*self.tcx);
290 let offset_ptr = ptr.wrapping_offset(Size::from_bytes(int.wrapping_neg()), self);
293 if !self.scalar_may_be_null(Scalar::from_pointer(offset_ptr, self))? {
294 0
296 } else {
297 2
300 }
301 }
302 (Scalar::Ptr(a, _), Scalar::Ptr(b, _)) => {
303 let (a_prov, a_offset) = a.prov_and_relative_offset();
304 let (b_prov, b_offset) = b.prov_and_relative_offset();
305 let a_allocid = a_prov.alloc_id();
306 let b_allocid = b_prov.alloc_id();
307 let a_info = self.get_alloc_info(a_allocid);
308 let b_info = self.get_alloc_info(b_allocid);
309
310 if a_info.align > Align::ONE && b_info.align > Align::ONE {
312 let min_align = Ord::min(a_info.align.bytes(), b_info.align.bytes());
313 let a_residue = a_offset.bytes() % min_align;
314 let b_residue = b_offset.bytes() % min_align;
315 if a_residue != b_residue {
316 return interp_ok(0);
319 }
320 }
323
324 if let (Some(GlobalAlloc::Static(a_did)), Some(GlobalAlloc::Static(b_did))) = (
325 self.tcx.try_get_global_alloc(a_allocid),
326 self.tcx.try_get_global_alloc(b_allocid),
327 ) {
328 if a_allocid == b_allocid {
329 if true {
{
match (&a_did, &b_did) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("different static item DefIds had same AllocId? {0:?} == {1:?}, {2:?} != {3:?}",
a_allocid, b_allocid, a_did, b_did)));
}
}
}
};
};debug_assert_eq!(
330 a_did, b_did,
331 "different static item DefIds had same AllocId? {a_allocid:?} == {b_allocid:?}, {a_did:?} != {b_did:?}"
332 );
333 (a_offset == b_offset) as u8
338 } else {
339 if true {
{
match (&(a_did), &(b_did)) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("same static item DefId had two different AllocIds? {0:?} != {1:?}, {2:?} == {3:?}",
a_allocid, b_allocid, a_did, b_did)));
}
}
}
};
};debug_assert_ne!(
340 a_did, b_did,
341 "same static item DefId had two different AllocIds? {a_allocid:?} != {b_allocid:?}, {a_did:?} == {b_did:?}"
342 );
343 if a_offset < a_info.size && b_offset < b_info.size {
354 0
355 } else {
356 2
362 }
363 }
364 } else {
365 2
388 }
389 }
390 })
391 }
392}
393
394impl<'tcx> CompileTimeMachine<'tcx> {
395 #[inline(always)]
396 pub fn best_lint_scope(&self, tcx: TyCtxt<'tcx>) -> HirId {
399 self.stack.iter().find_map(|frame| frame.lint_root(tcx)).unwrap_or(CRATE_HIR_ID)
400 }
401}
402
403impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
404 type Provenance = CtfeProvenance;
type ProvenanceExtra = bool;
type ExtraFnVal = !;
type MemoryKind = crate::const_eval::MemoryKind;
type MemoryMap =
rustc_data_structures::fx::FxIndexMap<AllocId,
(MemoryKind<Self::MemoryKind>, Allocation)>;
const GLOBAL_KIND: Option<Self::MemoryKind> = None;
type AllocExtra = ();
type FrameExtra = ();
type Bytes = Box<[u8]>;
#[inline(always)]
fn ignore_optional_overflow_checks(_ecx: &InterpCx<'tcx, Self>) -> bool {
false
}
#[inline(always)]
fn unwind_terminate(_ecx: &mut InterpCx<'tcx, Self>,
_reason: mir::UnwindTerminateReason) -> InterpResult<'tcx> {
{
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("unwinding cannot happen during compile-time evaluation")));
}
}
#[inline(always)]
fn check_fn_target_features(_ecx: &InterpCx<'tcx, Self>,
_instance: ty::Instance<'tcx>) -> InterpResult<'tcx> {
interp_ok(())
}
#[inline(always)]
fn call_extra_fn(_ecx: &mut InterpCx<'tcx, Self>, fn_val: !,
_abi: &FnAbi<'tcx, Ty<'tcx>>, _args: &[FnArg<'tcx>],
_destination: &PlaceTy<'tcx, Self::Provenance>,
_target: Option<mir::BasicBlock>, _unwind: mir::UnwindAction)
-> InterpResult<'tcx> {
match fn_val {}
}
#[inline(always)]
fn float_fuse_mul_add(_ecx: &InterpCx<'tcx, Self>) -> bool { true }
#[inline(always)]
fn atomic_load(ecx: &InterpCx<'tcx, Self>,
place: &MPlaceTy<'tcx, Self::Provenance>, _ordering: AtomicOrdering)
-> InterpResult<'tcx, Scalar<Self::Provenance>> {
ecx.read_scalar(place)
}
#[inline(always)]
fn atomic_store(ecx: &mut InterpCx<'tcx, Self>,
place: &MPlaceTy<'tcx, Self::Provenance>,
val: &ImmTy<'tcx, Self::Provenance>, _ordering: AtomicOrdering)
-> InterpResult<'tcx> {
ecx.write_scalar(val.to_scalar(), place)
}
fn atomic_rmw(ecx: &mut InterpCx<'tcx, Self>,
place: &MPlaceTy<'tcx, Self::Provenance>, op: AtomicRmwOp,
operand: &ImmTy<'tcx, Self::Provenance>, _ordering: AtomicOrdering)
-> InterpResult<'tcx, Scalar<Self::Provenance>> {
let old_val = ecx.read_immediate(place)?;
let new_val = ecx.atomic_rmw_op(op, &old_val, operand)?;
ecx.write_immediate(*new_val, place)?;
interp_ok(old_val.to_scalar())
}
fn atomic_compare_exchange(ecx: &mut InterpCx<'tcx, Self>,
place: &MPlaceTy<'tcx, Self::Provenance>,
expected_old: &ImmTy<'tcx, Self::Provenance>,
new: &ImmTy<'tcx, Self::Provenance>, _can_fail_spuriously: bool,
_success_ordering: AtomicOrdering, _failure_ordering: AtomicOrdering)
-> InterpResult<'tcx, (Scalar<Self::Provenance>, bool)> {
let actual_old = ecx.read_immediate(place)?;
let eq =
ecx.binary_op(mir::BinOp::Eq, &actual_old,
expected_old)?.to_scalar().to_bool()?;
if eq { ecx.write_immediate(**new, place)?; }
interp_ok((actual_old.to_scalar(), eq))
}
#[inline(always)]
fn atomic_fence(_ecx: &InterpCx<'tcx, Self>, _ordering: AtomicOrdering,
_singlethread: bool) -> InterpResult<'tcx> {
interp_ok(())
}
#[inline(always)]
fn adjust_global_allocation<'b>(_ecx: &InterpCx<'tcx, Self>, _id: AllocId,
alloc: &'b Allocation)
-> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance>>> {
interp_ok(Cow::Borrowed(alloc))
}
fn init_local_allocation(_ecx: &InterpCx<'tcx, Self>, _id: AllocId,
_kind: MemoryKind<Self::MemoryKind>, _size: Size, _align: Align)
-> InterpResult<'tcx, Self::AllocExtra> {
interp_ok(())
}
fn extern_static_pointer(ecx: &InterpCx<'tcx, Self>, def_id: DefId)
-> InterpResult<'tcx, Pointer> {
interp_ok(Pointer::new(ecx.tcx.reserve_and_set_static_alloc(def_id).into(),
Size::ZERO))
}
#[inline(always)]
fn adjust_alloc_root_pointer(_ecx: &InterpCx<'tcx, Self>,
ptr: Pointer<CtfeProvenance>, _kind: Option<MemoryKind<Self::MemoryKind>>)
-> InterpResult<'tcx, Pointer<CtfeProvenance>> {
interp_ok(ptr)
}
#[inline(always)]
fn ptr_from_addr_cast(_ecx: &InterpCx<'tcx, Self>, addr: u64)
-> InterpResult<'tcx, Pointer<Option<CtfeProvenance>>> {
interp_ok(Pointer::without_provenance(addr))
}
#[inline(always)]
fn ptr_get_alloc(_ecx: &InterpCx<'tcx, Self>, ptr: Pointer<CtfeProvenance>,
_size: i64) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
let (prov, offset) = ptr.prov_and_relative_offset();
Some((prov.alloc_id(), offset, prov.immutable()))
}
#[inline(always)]
fn get_global_alloc_salt(_ecx: &InterpCx<'tcx, Self>,
_instance: Option<ty::Instance<'tcx>>) -> usize {
CTFE_ALLOC_SALT
}compile_time_machine!(<'tcx>);
405
406 const PANIC_ON_ALLOC_FAIL: bool = false; #[inline(always)]
409 fn enforce_alignment(ecx: &InterpCx<'tcx, Self>) -> bool {
410 #[allow(non_exhaustive_omitted_patterns)] match ecx.machine.check_alignment {
CheckAlignment::Error => true,
_ => false,
}matches!(ecx.machine.check_alignment, CheckAlignment::Error)
411 }
412
413 #[inline(always)]
414 fn enforce_validity(ecx: &InterpCx<'tcx, Self>, layout: TyAndLayout<'tcx>) -> bool {
415 ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks || layout.is_uninhabited()
416 }
417
418 fn load_mir(
419 ecx: &InterpCx<'tcx, Self>,
420 instance: ty::InstanceKind<'tcx>,
421 ) -> &'tcx mir::Body<'tcx> {
422 match instance {
423 ty::InstanceKind::Item(def) => ecx.tcx.mir_for_ctfe(def),
424 _ => ecx.tcx.instance_mir(instance),
425 }
426 }
427
428 fn find_mir_or_eval_fn(
429 ecx: &mut InterpCx<'tcx, Self>,
430 orig_instance: ty::Instance<'tcx>,
431 _abi: &FnAbi<'tcx, Ty<'tcx>>,
432 args: &[FnArg<'tcx>],
433 dest: &PlaceTy<'tcx>,
434 ret: Option<mir::BasicBlock>,
435 _unwind: mir::UnwindAction, ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
437 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_const_eval/src/const_eval/machine.rs:437",
"rustc_const_eval::const_eval::machine",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f7575a9da8e4a4fca3b5668d5a2ea7476db44b3f/compiler/rustc_const_eval/src/const_eval/machine.rs"),
::tracing_core::__macro_support::Option::Some(437u32),
::tracing_core::__macro_support::Option::Some("rustc_const_eval::const_eval::machine"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("find_mir_or_eval_fn: {0:?}",
orig_instance) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("find_mir_or_eval_fn: {:?}", orig_instance);
438
439 let Some(instance) = ecx.hook_special_const_fn(orig_instance, args, dest, ret)? else {
441 return interp_ok(None);
443 };
444
445 if let ty::InstanceKind::Item(def) = instance.def {
447 if !ecx.tcx.is_const_fn(def) || {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def, &ecx.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcDoNotConstCheck) =>
{
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(ecx.tcx, def, RustcDoNotConstCheck) {
452 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("calling non-const function `{0}`",
instance))
})))throw_unsup_format!("calling non-const function `{}`", instance)
455 }
456 }
457
458 interp_ok(Some((ecx.load_mir(instance.def, None)?, orig_instance)))
462 }
463
464 fn panic_nounwind(ecx: &mut InterpCx<'tcx, Self>, msg: &str) -> InterpResult<'tcx> {
465 let msg = Symbol::intern(msg);
466 let span = ecx.find_closest_untracked_caller_location();
467 let (file, line, col) = ecx.location_triple_for_span(span);
468 Err(ConstEvalErrKind::Panic { msg, file, line, col }).into()
469 }
470
471 fn call_intrinsic(
472 ecx: &mut InterpCx<'tcx, Self>,
473 instance: ty::Instance<'tcx>,
474 args: &[OpTy<'tcx>],
475 dest: &PlaceTy<'tcx, Self::Provenance>,
476 target: Option<mir::BasicBlock>,
477 _unwind: mir::UnwindAction,
478 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
479 if ecx.eval_intrinsic(instance, args, dest, target)? {
481 return interp_ok(None);
482 }
483 let intrinsic_name = ecx.tcx.item_name(instance.def_id());
484
485 match intrinsic_name {
487 sym::ptr_guaranteed_cmp => {
488 let a = ecx.read_scalar(&args[0])?;
489 let b = ecx.read_scalar(&args[1])?;
490 let cmp = ecx.guaranteed_cmp(a, b)?;
491 ecx.write_scalar(Scalar::from_u8(cmp), dest)?;
492 }
493 sym::const_allocate => {
494 let size = ecx.read_scalar(&args[0])?.to_target_usize(ecx)?;
495 let align = ecx.read_scalar(&args[1])?.to_target_usize(ecx)?;
496
497 let align = match Align::from_bytes(align) {
498 Ok(a) => a,
499 Err(err) => {
500 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid align passed to `const_allocate`: {0}",
err))
})))throw_ub_format!("invalid align passed to `const_allocate`: {err}")
501 }
502 };
503
504 let ptr = ecx.allocate_ptr(
505 Size::from_bytes(size),
506 align,
507 interpret::MemoryKind::Machine(MemoryKind::Heap { was_made_global: false }),
508 AllocInit::Uninit,
509 )?;
510 ecx.write_pointer(ptr, dest)?;
511 }
512 sym::const_deallocate => {
513 let ptr = ecx.read_pointer(&args[0])?;
514 let size = ecx.read_scalar(&args[1])?.to_target_usize(ecx)?;
515 let align = ecx.read_scalar(&args[2])?.to_target_usize(ecx)?;
516
517 let size = Size::from_bytes(size);
518 let align = match Align::from_bytes(align) {
519 Ok(a) => a,
520 Err(err) => {
521 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::Ub(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid align passed to `const_deallocate`: {0}",
err))
})))throw_ub_format!("invalid align passed to `const_deallocate`: {err}")
522 }
523 };
524
525 let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr, 0)?;
528 let is_allocated_in_another_const = #[allow(non_exhaustive_omitted_patterns)] match ecx.tcx.try_get_global_alloc(alloc_id)
{
Some(interpret::GlobalAlloc::Memory(_)) => true,
_ => false,
}matches!(
529 ecx.tcx.try_get_global_alloc(alloc_id),
530 Some(interpret::GlobalAlloc::Memory(_))
531 );
532
533 if !is_allocated_in_another_const {
534 ecx.deallocate_ptr(
535 ptr,
536 Some((size, align)),
537 interpret::MemoryKind::Machine(MemoryKind::Heap { was_made_global: false }),
538 )?;
539 }
540 }
541
542 sym::const_make_global => {
543 let ptr = ecx.read_pointer(&args[0])?;
544 ecx.make_const_heap_ptr_global(ptr)?;
545 ecx.write_pointer(ptr, dest)?;
546 }
547
548 sym::is_val_statically_known => ecx.write_scalar(Scalar::from_bool(false), dest)?,
553
554 sym::assert_inhabited
556 | sym::assert_zero_valid
557 | sym::assert_mem_uninitialized_valid => {
558 let ty = instance.args.type_at(0);
559 let requirement = ValidityRequirement::from_intrinsic(intrinsic_name).unwrap();
560
561 let should_panic = !ecx
562 .tcx
563 .check_validity_requirement((requirement, ecx.typing_env().as_query_input(ty)))
564 .map_err(|_| ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::TooGeneric)err_inval!(TooGeneric))?;
565
566 if should_panic {
567 let layout = ecx.layout_of(ty)?;
568
569 let msg = match requirement {
570 _ if layout.is_uninhabited() => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("aborted execution: attempted to instantiate uninhabited type `{0}`",
ty))
})format!(
573 "aborted execution: attempted to instantiate uninhabited type `{ty}`"
574 ),
575 ValidityRequirement::Inhabited => ::rustc_span::macros::bug_impl(None, format_args!("handled earlier"),
Location::caller())bug!("handled earlier"),
576 ValidityRequirement::Zero => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("aborted execution: attempted to zero-initialize type `{0}`, which is invalid",
ty))
})format!(
577 "aborted execution: attempted to zero-initialize type `{ty}`, which is invalid"
578 ),
579 ValidityRequirement::UninitMitigated0x01Fill => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("aborted execution: attempted to leave type `{0}` uninitialized, which is invalid",
ty))
})format!(
580 "aborted execution: attempted to leave type `{ty}` uninitialized, which is invalid"
581 ),
582 ValidityRequirement::Uninit => ::rustc_span::macros::bug_impl(None,
format_args!("assert_uninit_valid doesn\'t exist"), Location::caller())bug!("assert_uninit_valid doesn't exist"),
583 };
584
585 Self::panic_nounwind(ecx, &msg)?;
586 return interp_ok(None);
588 }
589 }
590
591 sym::type_id_vtable => {
592 let tp_ty = ecx.read_type_id(&args[0])?;
593 let result_ty = ecx.read_type_id(&args[1])?;
594
595 let (implements_trait, preds) = type_implements_dyn_trait(ecx, tp_ty, result_ty)?;
596
597 if implements_trait {
598 let vtable_ptr = ecx.get_vtable_ptr(tp_ty, preds)?;
599 ecx.write_pointer(vtable_ptr, dest)?;
601 } else {
602 ecx.write_discriminant(FIRST_VARIANT, dest)?;
604 }
605 }
606
607 sym::type_of => {
608 let ty = ecx.read_type_id(&args[0])?;
609 ecx.write_type_info(ty, dest)?;
610 }
611
612 sym::type_id_is_signed => {
613 let ty = ecx.read_type_id(&args[0])?;
614 ecx.write_scalar(Scalar::from_bool(ty.is_signed()), dest)?;
615 }
616
617 sym::type_id_points_mutably => {
618 let ty = ecx.read_type_id(&args[0])?;
619 let is_mutable = #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::RawPtr(_, Mutability::Mut) | &ty::Ref(_, _, Mutability::Mut) => true,
_ => false,
}matches!(
620 ty.kind(),
621 ty::RawPtr(_, Mutability::Mut) | &ty::Ref(_, _, Mutability::Mut)
622 );
623 ecx.write_scalar(Scalar::from_bool(is_mutable), dest)?;
624 }
625
626 sym::size_of_type_id => {
627 let ty = ecx.read_type_id(&args[0])?;
628 let layout = ecx.layout_of(ty)?;
629 let variant_index = if layout.is_sized() {
630 let (variant, variant_place) = ecx.project_downcast_named(dest, sym::Some)?;
631 let size_field_place = ecx.project_field(&variant_place, FieldIdx::ZERO)?;
632 ecx.write_scalar(
633 ScalarInt::try_from_target_usize(layout.size.bytes(), ecx.tcx.tcx).unwrap(),
634 &size_field_place,
635 )?;
636 variant
637 } else {
638 ecx.project_downcast_named(dest, sym::None)?.0
639 };
640 ecx.write_discriminant(variant_index, dest)?;
641 }
642
643 sym::type_id_element_ty => {
644 let ty = ecx.read_type_id(&args[0])?;
645 let variant_index = if let ty::Array(ty, _) | ty::Slice(ty) = ty.kind() {
646 let (variant_idx, variant_place) =
647 ecx.project_downcast_named(dest, sym::Some)?;
648 let type_id_field_place = ecx.project_field(&variant_place, FieldIdx::ZERO)?;
649 ecx.write_type_id(*ty, &type_id_field_place)?;
650 variant_idx
651 } else {
652 ecx.project_downcast_named(dest, sym::None)?.0
653 };
654 ecx.write_discriminant(variant_index, dest)?;
655 }
656
657 sym::type_id_array_len => {
658 let ty = ecx.read_type_id(&args[0])?;
659 let len = if let ty::Array(_, len) = ty.kind() {
660 len.to_leaf().to_target_usize(ecx.tcx.tcx())
661 } else {
662 0
663 };
664 ecx.write_scalar(Scalar::from_target_usize(len, ecx), dest)?;
665 }
666
667 sym::type_id_fields => {
668 let ty = ecx.read_type_id(&args[0])?;
669 let variant_idx = ecx.read_target_usize(&args[1])? as usize;
670
671 let variants_num =
672 ty.ty_adt_def().map(|adt_def| adt_def.variants().len()).unwrap_or(1);
673 if variant_idx >= variants_num {
674 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::BoundsCheckFailed {
len: variants_num as u64,
index: variant_idx as u64,
});throw_ub!(BoundsCheckFailed {
675 len: variants_num as u64,
676 index: variant_idx as u64
677 });
678 }
679
680 let fields_num = match ty.kind() {
681 ty::Adt(adt_def, _) => {
682 let variant_def = &adt_def.variants()[VariantIdx::from_usize(variant_idx)];
683 variant_def.fields.len()
684 }
685 ty::Tuple(fields) => fields.len(),
686 _ => 0, };
688
689 ecx.write_scalar(Scalar::from_target_usize(fields_num as u64, ecx), dest)?;
690 }
691
692 sym::type_id_field_representing_type => {
693 let ty = ecx.read_type_id(&args[0])?;
694 let variant_idx = ecx.read_target_usize(&args[1])? as usize;
695 let field_idx = ecx.read_target_usize(&args[2])? as usize;
696
697 let variants_num =
698 ty.ty_adt_def().map(|adt_def| adt_def.variants().len()).unwrap_or(1);
699 if variant_idx >= variants_num {
700 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::BoundsCheckFailed {
len: variants_num as u64,
index: variant_idx as u64,
});throw_ub!(BoundsCheckFailed {
701 len: variants_num as u64,
702 index: variant_idx as u64
703 });
704 }
705
706 let fields_num = match ty.kind() {
707 ty::Adt(adt_def, _) => {
708 let variant_def = &adt_def.variants()[VariantIdx::from_usize(variant_idx)];
709 variant_def.fields.len()
710 }
711 ty::Tuple(fields) => fields.len(),
712 _ => 0, };
714 if field_idx >= fields_num {
715 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::BoundsCheckFailed {
len: fields_num as u64,
index: field_idx as u64,
});throw_ub!(BoundsCheckFailed {
716 len: fields_num as u64,
717 index: field_idx as u64
718 });
719 }
720
721 let frt = Ty::new_field_representing_type(
722 *ecx.tcx,
723 ty,
724 VariantIdx::from_usize(variant_idx),
725 FieldIdx::from_usize(field_idx),
726 );
727 ecx.write_type_id(frt, dest)?;
728 }
729 sym::type_id_function_ptr => {
730 let ty = ecx.read_type_id(&args[0])?;
731 let variant_index = if let ty::FnPtr(sig, fn_header) = ty.kind() {
732 let (variant, variant_place) = ecx.project_downcast_named(dest, sym::Some)?;
733 let field_place = ecx.project_field(&variant_place, FieldIdx::ZERO)?;
734 let sig = sig.skip_binder(); ecx.write_fn_ptr_type_info(field_place, &sig, fn_header)?;
736 variant
737 } else {
738 ecx.project_downcast_named(dest, sym::None)?.0
739 };
740 ecx.write_discriminant(variant_index, dest)?;
741 }
742 sym::type_id_points_to => {
743 let ty = ecx.read_type_id(&args[0])?;
744 let variant_index = if let ty::RawPtr(pointee_ty, _) | ty::Ref(_, pointee_ty, _) =
745 ty.kind()
746 {
747 let (variant, variant_place) = ecx.project_downcast_named(dest, sym::Some)?;
748 let field_place = ecx.project_field(&variant_place, FieldIdx::ZERO)?;
749 ecx.write_type_id(*pointee_ty, &field_place)?;
750 variant
751 } else {
752 ecx.project_downcast_named(dest, sym::None)?.0
753 };
754 ecx.write_discriminant(variant_index, dest)?;
755 }
756
757 sym::type_id_variants => {
758 let ty = ecx.read_type_id(&args[0])?;
759 let variants_num = ty.ty_adt_def().map(|def| def.variants().len()).unwrap_or(1);
760 ecx.write_scalar(Scalar::from_target_usize(variants_num as u64, ecx), dest)?;
761 }
762
763 sym::variant_name => {
764 let base = ecx.read_type_id(&args[0])?;
765
766 let field_name = if let ty::Adt(def, _) = base.kind() {
767 let variant_idx = ecx.read_target_usize(&args[1])? as usize;
768 if variant_idx >= def.variants().len() {
769 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::BoundsCheckFailed {
len: def.variants().len() as u64,
index: variant_idx as u64,
});throw_ub!(BoundsCheckFailed {
770 len: def.variants().len() as u64,
771 index: variant_idx as u64
772 });
773 }
774 let variant_idx = VariantIdx::from_usize(variant_idx);
775 def.variant(variant_idx).name
776 } else {
777 ::rustc_span::macros::bug_impl(Some(ecx.cur_span()),
format_args!("expected enum type, got {0}", base), Location::caller())span_bug!(ecx.cur_span(), "expected enum type, got {base}")
778 };
779 let ptr = ecx.allocate_bytes_dedup(field_name.as_str().as_bytes())?;
780 ecx.write_immediate(
781 Immediate::ScalarPair(
782 Scalar::from_pointer(ptr, ecx),
783 Scalar::from_target_usize(field_name.as_str().len() as u64, ecx),
784 ),
785 dest,
786 )?;
787 }
788
789 sym::variant_non_exhaustive => {
790 let base = ecx.read_type_id(&args[0])?;
791
792 let non_exhaustive = if let ty::Adt(def, _) = base.kind() {
793 let variant_idx = ecx.read_target_usize(&args[1])? as usize;
794 if variant_idx >= def.variants().len() {
795 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::BoundsCheckFailed {
len: def.variants().len() as u64,
index: variant_idx as u64,
});throw_ub!(BoundsCheckFailed {
796 len: def.variants().len() as u64,
797 index: variant_idx as u64
798 });
799 }
800 let variant_idx = VariantIdx::from_usize(variant_idx);
801 def.variant(variant_idx).is_field_list_non_exhaustive()
802 } else {
803 ::rustc_span::macros::bug_impl(Some(ecx.cur_span()),
format_args!("expected enum type, got {0}", base), Location::caller())span_bug!(ecx.cur_span(), "expected enum type, got {base}")
804 };
805 ecx.write_scalar(Scalar::from_bool(non_exhaustive), dest)?;
806 }
807
808 sym::field_offset => {
809 let frt_ty = instance.args.type_at(0);
810 ensure_monomorphic_enough(frt_ty)?;
811
812 let (ty, variant, field) = if let ty::Adt(def, args) = frt_ty.kind()
813 && let Some(FieldInfo { base, variant_idx, field_idx, .. }) =
814 def.field_representing_type_info(ecx.tcx.tcx, args)
815 {
816 (base, variant_idx, field_idx)
817 } else {
818 ::rustc_span::macros::bug_impl(Some(ecx.cur_span()),
format_args!("expected field representing type, got {0}", frt_ty),
Location::caller())span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}")
819 };
820 let layout = ecx.layout_of(ty)?;
821 let cx = ty::layout::LayoutCx::new(ecx.tcx.tcx, ecx.typing_env());
822
823 let layout = layout.for_variant(&cx, variant);
824 let offset = layout.fields.offset(field.index()).bytes();
825
826 ecx.write_scalar(Scalar::from_target_usize(offset, ecx), dest)?;
827 }
828
829 sym::field_representing_type_name => {
830 let frt_ty = ecx.read_type_id(&args[0])?;
831
832 let field_name = if let ty::Adt(def, args) = frt_ty.kind()
833 && let Some(FieldInfo { name, .. }) =
834 def.field_representing_type_info(ecx.tcx.tcx, args)
835 {
836 name
837 } else {
838 ::rustc_span::macros::bug_impl(Some(ecx.cur_span()),
format_args!("expected field representing type, got {0}", frt_ty),
Location::caller())span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}")
839 };
840 let ptr = ecx.allocate_bytes_dedup(field_name.as_str().as_bytes())?;
841 ecx.write_immediate(
842 Immediate::ScalarPair(
843 Scalar::from_pointer(ptr, ecx),
844 Scalar::from_target_usize(field_name.as_str().len() as u64, ecx),
845 ),
846 dest,
847 )?;
848 }
849
850 sym::field_representing_type_offset => {
851 let frt_ty = ecx.read_type_id(&args[0])?;
852
853 let (ty, variant, field) = if let ty::Adt(def, args) = frt_ty.kind()
854 && let Some(FieldInfo { base, variant_idx, field_idx, .. }) =
855 def.field_representing_type_info(ecx.tcx.tcx, args)
856 {
857 (base, variant_idx, field_idx)
858 } else {
859 ::rustc_span::macros::bug_impl(Some(ecx.cur_span()),
format_args!("expected field representing type, got {0}", frt_ty),
Location::caller())span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}")
860 };
861 let layout = ecx.layout_of(ty)?;
862 let cx = ty::layout::LayoutCx::new(ecx.tcx.tcx, ecx.typing_env());
863
864 let layout = layout.for_variant(&cx, variant);
865 let offset = layout.fields.offset(field.index()).bytes();
866
867 ecx.write_scalar(Scalar::from_target_usize(offset, ecx), dest)?;
868 }
869
870 sym::field_representing_type_actual_type_id => {
871 let frt_ty = ecx.read_type_id(&args[0])?;
872
873 let field_ty = if let ty::Adt(def, args) = frt_ty.kind()
874 && let Some(FieldInfo { ty, .. }) =
875 def.field_representing_type_info(ecx.tcx.tcx, args)
876 {
877 ecx.tcx.erase_and_anonymize_regions(ty)
878 } else {
879 ::rustc_span::macros::bug_impl(Some(ecx.cur_span()),
format_args!("expected field representing type, got {0}", frt_ty),
Location::caller())span_bug!(ecx.cur_span(), "expected field representing type, got {frt_ty}")
880 };
881 ecx.write_type_id(field_ty, dest)?;
882 }
883
884 sym::type_id_generics => {
885 let ty = ecx.read_type_id(&args[0])?;
886 ecx.write_type_id_generics(dest, ty)?;
887 }
888
889 sym::non_exhaustive => {
890 let ty = ecx.read_type_id(&args[0])?;
891
892 let non_exhaustive = if let ty::Adt(def, _) = ty.kind() {
894 if def.is_enum() {
895 def.is_variant_list_non_exhaustive()
896 } else {
897 def.non_enum_variant().is_field_list_non_exhaustive()
898 }
899 } else {
900 false
901 };
902
903 ecx.write_scalar(Scalar::from_bool(non_exhaustive), dest)?;
904 }
905
906 _ => {
907 if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden {
909 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("intrinsic `{0}` is not supported at compile-time",
intrinsic_name))
})));throw_unsup_format!(
910 "intrinsic `{intrinsic_name}` is not supported at compile-time"
911 );
912 }
913 return interp_ok(Some(ty::Instance {
914 def: ty::InstanceKind::Item(instance.def_id()),
915 args: instance.args,
916 }));
917 }
918 }
919
920 ecx.return_to_block(target)?;
922 interp_ok(None)
923 }
924
925 fn call_llvm_intrinsic(
926 ecx: &mut InterpCx<'tcx, Self>,
927 instance: ty::Instance<'tcx>,
928 _args: &[OpTy<'tcx>],
929 _dest: &PlaceTy<'tcx, Self::Provenance>,
930 _target: Option<mir::BasicBlock>,
931 ) -> InterpResult<'tcx> {
932 let intrinsic_name = ecx.tcx.codegen_fn_attrs(instance.def_id()).symbol_name.unwrap();
933
934 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("LLVM intrinsic `{0}` is not supported at compile-time",
intrinsic_name))
})));throw_unsup_format!("LLVM intrinsic `{intrinsic_name}` is not supported at compile-time");
935 }
936
937 fn assert_panic(
938 ecx: &mut InterpCx<'tcx, Self>,
939 msg: &AssertMessage<'tcx>,
940 _unwind: mir::UnwindAction,
941 ) -> InterpResult<'tcx> {
942 use rustc_middle::mir::AssertKind::*;
943 let eval_to_int =
945 |op| ecx.read_immediate(&ecx.eval_operand(op, None)?).map(|x| x.to_const_int());
946 let err = match msg {
947 BoundsCheck { len, index } => {
948 let len = eval_to_int(len)?;
949 let index = eval_to_int(index)?;
950 BoundsCheck { len, index }
951 }
952 Overflow(op, l, r) => Overflow(*op, eval_to_int(l)?, eval_to_int(r)?),
953 OverflowNeg(op) => OverflowNeg(eval_to_int(op)?),
954 DivisionByZero(op) => DivisionByZero(eval_to_int(op)?),
955 RemainderByZero(op) => RemainderByZero(eval_to_int(op)?),
956 ResumedAfterReturn(coroutine_kind) => ResumedAfterReturn(*coroutine_kind),
957 ResumedAfterPanic(coroutine_kind) => ResumedAfterPanic(*coroutine_kind),
958 ResumedAfterDrop(coroutine_kind) => ResumedAfterDrop(*coroutine_kind),
959 MisalignedPointerDereference { required, found } => MisalignedPointerDereference {
960 required: eval_to_int(required)?,
961 found: eval_to_int(found)?,
962 },
963 NullPointerDereference => NullPointerDereference,
964 NullReferenceConstructed => NullReferenceConstructed,
965 InvalidEnumConstruction(source) => InvalidEnumConstruction(eval_to_int(source)?),
966 };
967 Err(ConstEvalErrKind::AssertFailure(err)).into()
968 }
969
970 #[inline(always)]
971 fn runtime_checks(
972 _ecx: &InterpCx<'tcx, Self>,
973 _r: mir::RuntimeChecks,
974 ) -> InterpResult<'tcx, bool> {
975 interp_ok(true)
978 }
979
980 fn binary_ptr_op(
981 _ecx: &InterpCx<'tcx, Self>,
982 _bin_op: mir::BinOp,
983 _left: &ImmTy<'tcx>,
984 _right: &ImmTy<'tcx>,
985 ) -> InterpResult<'tcx, ImmTy<'tcx>> {
986 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("pointer arithmetic or comparison is not supported at compile-time"))
})));throw_unsup_format!("pointer arithmetic or comparison is not supported at compile-time");
987 }
988
989 fn increment_const_eval_counter(ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
990 if let Some(new_steps) = ecx.machine.num_evaluated_steps.checked_add(1) {
993 let (limit, start) = if ecx.tcx.sess.opts.unstable_opts.tiny_const_eval_limit {
994 (TINY_LINT_TERMINATOR_LIMIT, TINY_LINT_TERMINATOR_LIMIT)
995 } else {
996 (LINT_TERMINATOR_LIMIT, PROGRESS_INDICATOR_START)
997 };
998
999 ecx.machine.num_evaluated_steps = new_steps;
1000 if new_steps == limit {
1005 let hir_id = ecx.machine.best_lint_scope(*ecx.tcx);
1009 let is_error = ecx
1010 .tcx
1011 .lint_level_spec_at_node(LONG_RUNNING_CONST_EVAL, hir_id)
1012 .level()
1013 .is_error();
1014 let span = ecx.cur_span();
1015 ecx.tcx.emit_node_span_lint(
1016 LONG_RUNNING_CONST_EVAL,
1017 hir_id,
1018 span,
1019 LongRunning { item_span: ecx.tcx.span },
1020 );
1021 if is_error {
1023 let guard = ecx
1024 .tcx
1025 .dcx()
1026 .span_delayed_bug(span, "The deny lint should have already errored");
1027 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::InvalidProgram(::rustc_middle::mir::interpret::InvalidProgramInfo::AlreadyReported(ReportedErrorInfo::allowed_in_infallible(guard)));throw_inval!(AlreadyReported(ReportedErrorInfo::allowed_in_infallible(guard)));
1028 }
1029 } else if new_steps > start && new_steps.is_power_of_two() {
1030 let span = ecx.cur_span();
1034 let mut warn =
1035 ecx.tcx.dcx().create_warn(LongRunningWarn { span, item_span: ecx.tcx.span });
1036 warn.arg("force_duplicate", new_steps);
1040 warn.emit();
1041 }
1042 }
1043
1044 interp_ok(())
1045 }
1046
1047 #[inline(always)]
1048 fn expose_provenance(
1049 _ecx: &InterpCx<'tcx, Self>,
1050 _provenance: Self::Provenance,
1051 ) -> InterpResult<'tcx> {
1052 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::Unsupported(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("exposing pointers is not possible at compile-time"))
})))throw_unsup_format!("exposing pointers is not possible at compile-time")
1054 }
1055
1056 #[inline(always)]
1057 fn init_frame(
1058 ecx: &mut InterpCx<'tcx, Self>,
1059 frame: Frame<'tcx>,
1060 ) -> InterpResult<'tcx, Frame<'tcx>> {
1061 if !ecx.recursion_limit.value_within_limit(ecx.stack().len() + 1) {
1063 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::ResourceExhaustion(::rustc_middle::mir::interpret::ResourceExhaustionInfo::StackFrameLimitReached)throw_exhaust!(StackFrameLimitReached)
1064 } else {
1065 interp_ok(frame)
1066 }
1067 }
1068
1069 #[inline(always)]
1070 fn stack<'a>(
1071 ecx: &'a InterpCx<'tcx, Self>,
1072 ) -> &'a [Frame<'tcx, Self::Provenance, Self::FrameExtra>] {
1073 &ecx.machine.stack
1074 }
1075
1076 #[inline(always)]
1077 fn stack_mut<'a>(
1078 ecx: &'a mut InterpCx<'tcx, Self>,
1079 ) -> &'a mut Vec<Frame<'tcx, Self::Provenance, Self::FrameExtra>> {
1080 &mut ecx.machine.stack
1081 }
1082
1083 fn before_access_global(
1084 _tcx: TyCtxtAt<'tcx>,
1085 machine: &Self,
1086 alloc_id: AllocId,
1087 alloc: ConstAllocation<'tcx>,
1088 _static_def_id: Option<DefId>,
1089 is_write: bool,
1090 ) -> InterpResult<'tcx> {
1091 let alloc = alloc.inner();
1092 if is_write {
1093 match alloc.mutability {
1095 Mutability::Not => do yeet ::rustc_middle::mir::interpret::InterpErrorKind::UndefinedBehavior(::rustc_middle::mir::interpret::UndefinedBehaviorInfo::WriteToReadOnly(alloc_id))throw_ub!(WriteToReadOnly(alloc_id)),
1096 Mutability::Mut => Err(ConstEvalErrKind::ModifiedGlobal).into(),
1097 }
1098 } else {
1099 if machine.can_access_mut_global == CanAccessMutGlobal::Yes {
1101 interp_ok(())
1103 } else if alloc.mutability == Mutability::Mut {
1104 Err(ConstEvalErrKind::ConstAccessesMutGlobal).into()
1107 } else {
1108 {
match (&alloc.mutability, &Mutability::Not) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(alloc.mutability, Mutability::Not);
1110 interp_ok(())
1111 }
1112 }
1113 }
1114
1115 fn retag_ptr_value(
1116 ecx: &mut InterpCx<'tcx, Self>,
1117 val: &ImmTy<'tcx, CtfeProvenance>,
1118 _ty: Ty<'tcx>,
1119 ) -> InterpResult<'tcx, Option<ImmTy<'tcx, CtfeProvenance>>> {
1120 if #[allow(non_exhaustive_omitted_patterns)] match ecx.machine.retag_mode {
RetagMode::None | RetagMode::Raw => true,
_ => false,
}matches!(ecx.machine.retag_mode, RetagMode::None | RetagMode::Raw) {
1121 return interp_ok(None);
1122 }
1123 if let ty::Ref(_, ty, mutbl) = val.layout.ty.kind()
1126 && *mutbl == Mutability::Not
1127 && val.to_scalar_and_meta().0.to_pointer(ecx).provenance.is_some_and(|p| !p.immutable())
1128 {
1129 let is_immutable = ty.is_freeze(*ecx.tcx, ecx.typing_env());
1131 let place = ecx.imm_ptr_to_mplace(val)?;
1132 let new_place = if is_immutable {
1133 place.map_provenance(CtfeProvenance::as_immutable)
1134 } else {
1135 place.map_provenance(CtfeProvenance::as_shared_ref)
1140 };
1141 interp_ok(Some(ImmTy::from_immediate(new_place.to_ref(ecx), val.layout)))
1142 } else {
1143 interp_ok(None)
1144 }
1145 }
1146
1147 fn with_retag_mode<T>(
1148 ecx: &mut InterpCx<'tcx, Self>,
1149 mode: RetagMode,
1150 f: impl FnOnce(&mut InterpCx<'tcx, Self>) -> InterpResult<'tcx, T>,
1151 ) -> InterpResult<'tcx, T> {
1152 let old_mode = mem::replace(&mut ecx.machine.retag_mode, mode);
1153 let ret = f(ecx);
1154 ecx.machine.retag_mode = old_mode;
1155 ret
1156 }
1157
1158 fn before_memory_write(
1159 _tcx: TyCtxtAt<'tcx>,
1160 _machine: &mut Self,
1161 _alloc_extra: &mut Self::AllocExtra,
1162 _ptr: Pointer<Option<Self::Provenance>>,
1163 (_alloc_id, immutable): (AllocId, bool),
1164 range: AllocRange,
1165 ) -> InterpResult<'tcx> {
1166 if range.size == Size::ZERO {
1167 return interp_ok(());
1169 }
1170 if immutable {
1172 return Err(ConstEvalErrKind::WriteThroughImmutablePointer).into();
1173 }
1174 interp_ok(())
1176 }
1177
1178 fn before_alloc_access(
1179 tcx: TyCtxtAt<'tcx>,
1180 machine: &Self,
1181 alloc_id: AllocId,
1182 ) -> InterpResult<'tcx> {
1183 if machine.stack.is_empty() {
1184 return interp_ok(());
1186 }
1187 if Some(alloc_id) == machine.static_root_ids.map(|(id, _)| id) {
1189 return Err(ConstEvalErrKind::RecursiveStatic).into();
1190 }
1191 if machine.static_root_ids.is_some() {
1194 if let Some(GlobalAlloc::Static(def_id)) = tcx.try_get_global_alloc(alloc_id) {
1195 if tcx.is_foreign_item(def_id) {
1196 do yeet ::rustc_middle::mir::interpret::InterpErrorKind::Unsupported(::rustc_middle::mir::interpret::UnsupportedOpInfo::ExternStatic(def_id));throw_unsup!(ExternStatic(def_id));
1197 }
1198 tcx.eval_static_initializer(def_id)?;
1199 }
1200 }
1201 interp_ok(())
1202 }
1203
1204 fn cached_union_data_range<'e>(
1205 ecx: &'e mut InterpCx<'tcx, Self>,
1206 ty: Ty<'tcx>,
1207 compute_range: impl FnOnce() -> RangeSet,
1208 ) -> Cow<'e, RangeSet> {
1209 if ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks {
1210 Cow::Borrowed(ecx.machine.union_data_ranges.entry(ty).or_insert_with(compute_range))
1211 } else {
1212 Cow::Owned(compute_range())
1214 }
1215 }
1216
1217 fn get_default_alloc_params(&self) -> <Self::Bytes as mir::interpret::AllocBytes>::AllocParams {
1218 }
1219}
1220
1221