1use std::sync::atomic::Ordering::Relaxed;
2
3use either::{Left, Right};
4use rustc_abi::{self as abi, BackendRepr};
5use rustc_errors::E0080;
6use rustc_hir::def::DefKind;
7use rustc_middle::mir::interpret::{AllocId, ErrorHandled, InterpErrorInfo, ReportedErrorInfo};
8use rustc_middle::mir::{self, ConstAlloc, ConstValue};
9use rustc_middle::query::TyCtxtAt;
10use rustc_middle::ty::layout::HasTypingEnv;
11use rustc_middle::ty::print::with_no_trimmed_paths;
12use rustc_middle::ty::{self, Ty, TyCtxt};
13use rustc_middle::{bug, throw_inval};
14use rustc_span::def_id::LocalDefId;
15use rustc_span::{DUMMY_SP, Span};
16use tracing::{debug, instrument, trace};
17
18use super::{CanAccessMutGlobal, CompileTimeInterpCx, CompileTimeMachine};
19use crate::const_eval::CheckAlignment;
20use crate::interpret::{
21 CtfeValidationMode, GlobalId, Immediate, InternError, InternKind, InterpCx, InterpErrorKind,
22 InterpResult, MPlaceTy, MemoryKind, OpTy, RefTracking, ReturnContinuation, create_static_alloc,
23 intern_const_alloc_recursive, interp_ok, throw_exhaust,
24};
25use crate::{CTRL_C_RECEIVED, errors};
26
27#[instrument(level = "trace", skip(ecx, body))]
29fn eval_body_using_ecx<'tcx, R: InterpretationResult<'tcx>>(
30 ecx: &mut CompileTimeInterpCx<'tcx>,
31 cid: GlobalId<'tcx>,
32 body: &'tcx mir::Body<'tcx>,
33) -> InterpResult<'tcx, R> {
34 let tcx = *ecx.tcx;
35 assert!(
36 cid.promoted.is_some()
37 || matches!(
38 ecx.tcx.def_kind(cid.instance.def_id()),
39 DefKind::Const
40 | DefKind::Static { .. }
41 | DefKind::ConstParam
42 | DefKind::AnonConst
43 | DefKind::InlineConst
44 | DefKind::AssocConst
45 ),
46 "Unexpected DefKind: {:?}",
47 ecx.tcx.def_kind(cid.instance.def_id())
48 );
49 let layout = ecx.layout_of(body.bound_return_ty().instantiate(tcx, cid.instance.args))?;
50 assert!(layout.is_sized());
51
52 let intern_kind = if cid.promoted.is_some() {
53 InternKind::Promoted
54 } else {
55 match tcx.static_mutability(cid.instance.def_id()) {
56 Some(m) => InternKind::Static(m),
57 None => InternKind::Constant,
58 }
59 };
60
61 let ret = if let InternKind::Static(_) = intern_kind {
62 create_static_alloc(ecx, cid.instance.def_id().expect_local(), layout)?
63 } else {
64 ecx.allocate(layout, MemoryKind::Stack)?
65 };
66
67 trace!(
68 "eval_body_using_ecx: pushing stack frame for global: {}{}",
69 with_no_trimmed_paths!(ecx.tcx.def_path_str(cid.instance.def_id())),
70 cid.promoted.map_or_else(String::new, |p| format!("::{p:?}"))
71 );
72
73 ecx.push_stack_frame_raw(
76 cid.instance,
77 body,
78 &ret.clone().into(),
79 ReturnContinuation::Stop { cleanup: false },
80 )?;
81 ecx.storage_live_for_always_live_locals()?;
82
83 while ecx.step()? {
85 if CTRL_C_RECEIVED.load(Relaxed) {
86 throw_exhaust!(Interrupted);
87 }
88 }
89
90 let intern_result = intern_const_alloc_recursive(ecx, intern_kind, &ret);
92
93 const_validate_mplace(ecx, &ret, cid)?;
95
96 match intern_result {
100 Ok(()) => {}
101 Err(InternError::DanglingPointer) => {
102 throw_inval!(AlreadyReported(ReportedErrorInfo::non_const_eval_error(
103 ecx.tcx
104 .dcx()
105 .emit_err(errors::DanglingPtrInFinal { span: ecx.tcx.span, kind: intern_kind }),
106 )));
107 }
108 Err(InternError::BadMutablePointer) => {
109 throw_inval!(AlreadyReported(ReportedErrorInfo::non_const_eval_error(
110 ecx.tcx
111 .dcx()
112 .emit_err(errors::MutablePtrInFinal { span: ecx.tcx.span, kind: intern_kind }),
113 )));
114 }
115 Err(InternError::ConstAllocNotGlobal) => {
116 throw_inval!(AlreadyReported(ReportedErrorInfo::non_const_eval_error(
117 ecx.tcx.dcx().emit_err(errors::ConstHeapPtrInFinal { span: ecx.tcx.span }),
118 )));
119 }
120 }
121
122 interp_ok(R::make_result(ret, ecx))
123}
124
125pub(crate) fn mk_eval_cx_to_read_const_val<'tcx>(
136 tcx: TyCtxt<'tcx>,
137 root_span: Span,
138 typing_env: ty::TypingEnv<'tcx>,
139 can_access_mut_global: CanAccessMutGlobal,
140) -> CompileTimeInterpCx<'tcx> {
141 debug!("mk_eval_cx: {:?}", typing_env);
142 InterpCx::new(
143 tcx,
144 root_span,
145 typing_env,
146 CompileTimeMachine::new(can_access_mut_global, CheckAlignment::No),
147 )
148}
149
150pub fn mk_eval_cx_for_const_val<'tcx>(
153 tcx: TyCtxtAt<'tcx>,
154 typing_env: ty::TypingEnv<'tcx>,
155 val: mir::ConstValue,
156 ty: Ty<'tcx>,
157) -> Option<(CompileTimeInterpCx<'tcx>, OpTy<'tcx>)> {
158 let ecx = mk_eval_cx_to_read_const_val(tcx.tcx, tcx.span, typing_env, CanAccessMutGlobal::No);
159 let op = ecx.const_val_to_op(val, ty, None).discard_err()?;
161 Some((ecx, op))
162}
163
164#[instrument(skip(ecx), level = "debug")]
171pub(super) fn op_to_const<'tcx>(
172 ecx: &CompileTimeInterpCx<'tcx>,
173 op: &OpTy<'tcx>,
174 for_diagnostics: bool,
175) -> ConstValue {
176 if op.layout.is_zst() {
178 return ConstValue::ZeroSized;
179 }
180
181 let force_as_immediate = match op.layout.backend_repr {
187 BackendRepr::Scalar(abi::Scalar::Initialized { .. }) => true,
188 _ => false,
196 };
197 let immediate = if force_as_immediate {
198 match ecx.read_immediate(op).report_err() {
199 Ok(imm) => Right(imm),
200 Err(err) => {
201 if for_diagnostics {
202 op.as_mplace_or_imm()
204 } else {
205 panic!("normalization works on validated constants: {err:?}")
206 }
207 }
208 }
209 } else {
210 op.as_mplace_or_imm()
211 };
212
213 debug!(?immediate);
214
215 match immediate {
216 Left(ref mplace) => {
217 let (prov, offset) =
218 mplace.ptr().into_pointer_or_addr().unwrap().prov_and_relative_offset();
219 let alloc_id = prov.alloc_id();
220 ConstValue::Indirect { alloc_id, offset }
221 }
222 Right(imm) => match *imm {
224 Immediate::Scalar(x) => ConstValue::Scalar(x),
225 Immediate::ScalarPair(a, b) => {
226 debug!("ScalarPair(a: {:?}, b: {:?})", a, b);
227 let pointee_ty = imm.layout.ty.builtin_deref(false).unwrap(); debug_assert!(
232 matches!(
233 ecx.tcx.struct_tail_for_codegen(pointee_ty, ecx.typing_env()).kind(),
234 ty::Str | ty::Slice(..),
235 ),
236 "`ConstValue::Slice` is for slice-tailed types only, but got {}",
237 imm.layout.ty,
238 );
239 let msg = "`op_to_const` on an immediate scalar pair must only be used on slice references to the beginning of an actual allocation";
240 let ptr = a.to_pointer(ecx).expect(msg);
241 let (prov, offset) =
242 ptr.into_pointer_or_addr().expect(msg).prov_and_relative_offset();
243 let alloc_id = prov.alloc_id();
244 assert!(offset == abi::Size::ZERO, "{}", msg);
245 let meta = b.to_target_usize(ecx).expect(msg);
246 ConstValue::Slice { alloc_id, meta }
247 }
248 Immediate::Uninit => bug!("`Uninit` is not a valid value for {}", op.layout.ty),
249 },
250 }
251}
252
253#[instrument(skip(tcx), level = "debug", ret)]
254pub(crate) fn turn_into_const_value<'tcx>(
255 tcx: TyCtxt<'tcx>,
256 constant: ConstAlloc<'tcx>,
257 key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>,
258) -> ConstValue {
259 let cid = key.value;
260 let def_id = cid.instance.def.def_id();
261 let is_static = tcx.is_static(def_id);
262 let ecx = mk_eval_cx_to_read_const_val(
264 tcx,
265 tcx.def_span(key.value.instance.def_id()),
266 key.typing_env,
267 CanAccessMutGlobal::from(is_static),
268 );
269
270 let mplace = ecx.raw_const_to_mplace(constant).expect(
271 "can only fail if layout computation failed, \
272 which should have given a good error before ever invoking this function",
273 );
274 assert!(
275 !is_static || cid.promoted.is_some(),
276 "the `eval_to_const_value_raw` query should not be used for statics, use `eval_to_allocation` instead"
277 );
278
279 op_to_const(&ecx, &mplace.into(), false)
281}
282
283#[instrument(skip(tcx), level = "debug")]
284pub fn eval_to_const_value_raw_provider<'tcx>(
285 tcx: TyCtxt<'tcx>,
286 key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>,
287) -> ::rustc_middle::mir::interpret::EvalToConstValueResult<'tcx> {
288 tcx.eval_to_allocation_raw(key).map(|val| turn_into_const_value(tcx, val, key))
289}
290
291#[instrument(skip(tcx), level = "debug")]
292pub fn eval_static_initializer_provider<'tcx>(
293 tcx: TyCtxt<'tcx>,
294 def_id: LocalDefId,
295) -> ::rustc_middle::mir::interpret::EvalStaticInitializerRawResult<'tcx> {
296 assert!(tcx.is_static(def_id.to_def_id()));
297
298 let instance = ty::Instance::mono(tcx, def_id.to_def_id());
299 let cid = rustc_middle::mir::interpret::GlobalId { instance, promoted: None };
300 eval_in_interpreter(tcx, cid, ty::TypingEnv::fully_monomorphized())
301}
302
303pub trait InterpretationResult<'tcx> {
304 fn make_result(
308 mplace: MPlaceTy<'tcx>,
309 ecx: &mut InterpCx<'tcx, CompileTimeMachine<'tcx>>,
310 ) -> Self;
311}
312
313impl<'tcx> InterpretationResult<'tcx> for ConstAlloc<'tcx> {
314 fn make_result(
315 mplace: MPlaceTy<'tcx>,
316 _ecx: &mut InterpCx<'tcx, CompileTimeMachine<'tcx>>,
317 ) -> Self {
318 ConstAlloc { alloc_id: mplace.ptr().provenance.unwrap().alloc_id(), ty: mplace.layout.ty }
319 }
320}
321
322#[instrument(skip(tcx), level = "debug")]
323pub fn eval_to_allocation_raw_provider<'tcx>(
324 tcx: TyCtxt<'tcx>,
325 key: ty::PseudoCanonicalInput<'tcx, GlobalId<'tcx>>,
326) -> ::rustc_middle::mir::interpret::EvalToAllocationRawResult<'tcx> {
327 assert!(key.value.promoted.is_some() || !tcx.is_static(key.value.instance.def_id()));
330 debug_assert_eq!(key.typing_env.typing_mode, ty::TypingMode::PostAnalysis);
333 if cfg!(debug_assertions) {
334 let instance = with_no_trimmed_paths!(key.value.instance.to_string());
340 trace!("const eval: {:?} ({})", key, instance);
341 }
342
343 eval_in_interpreter(tcx, key.value, key.typing_env)
344}
345
346fn eval_in_interpreter<'tcx, R: InterpretationResult<'tcx>>(
347 tcx: TyCtxt<'tcx>,
348 cid: GlobalId<'tcx>,
349 typing_env: ty::TypingEnv<'tcx>,
350) -> Result<R, ErrorHandled> {
351 let def = cid.instance.def.def_id();
352 let is_static = tcx.is_static(def);
353
354 let mut ecx = InterpCx::new(
355 tcx,
356 tcx.def_span(def),
357 typing_env,
358 CompileTimeMachine::new(CanAccessMutGlobal::from(is_static), CheckAlignment::Error),
363 );
364 let res = ecx.load_mir(cid.instance.def, cid.promoted);
365 res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, body))
366 .report_err()
367 .map_err(|error| report_eval_error(&ecx, cid, error))
368}
369
370#[inline(always)]
371fn const_validate_mplace<'tcx>(
372 ecx: &mut InterpCx<'tcx, CompileTimeMachine<'tcx>>,
373 mplace: &MPlaceTy<'tcx>,
374 cid: GlobalId<'tcx>,
375) -> Result<(), ErrorHandled> {
376 let alloc_id = mplace.ptr().provenance.unwrap().alloc_id();
377 let mut ref_tracking = RefTracking::new(mplace.clone());
378 let mut inner = false;
379 while let Some((mplace, path)) = ref_tracking.next() {
380 let mode = match ecx.tcx.static_mutability(cid.instance.def_id()) {
381 _ if cid.promoted.is_some() => CtfeValidationMode::Promoted,
382 Some(mutbl) => CtfeValidationMode::Static { mutbl }, None => {
384 CtfeValidationMode::Const { allow_immutable_unsafe_cell: !inner }
388 }
389 };
390 ecx.const_validate_operand(&mplace.into(), path, &mut ref_tracking, mode)
391 .report_err()
392 .map_err(|error| report_validation_error(&ecx, cid, error, alloc_id))?;
395 inner = true;
396 }
397
398 Ok(())
399}
400
401#[inline(never)]
402fn report_eval_error<'tcx>(
403 ecx: &InterpCx<'tcx, CompileTimeMachine<'tcx>>,
404 cid: GlobalId<'tcx>,
405 error: InterpErrorInfo<'tcx>,
406) -> ErrorHandled {
407 let (error, backtrace) = error.into_parts();
408 backtrace.print_backtrace();
409
410 let instance = with_no_trimmed_paths!(cid.instance.to_string());
411
412 super::report(
413 ecx,
414 error,
415 DUMMY_SP,
416 || super::get_span_and_frames(ecx.tcx, ecx.stack()),
417 |diag, span, frames| {
418 let num_frames = frames.len();
419 diag.code(E0080);
421 diag.span_label(span, crate::fluent_generated::const_eval_error);
422 for frame in frames {
423 diag.subdiagnostic(frame);
424 }
425 diag.arg("instance", instance);
427 diag.arg("num_frames", num_frames);
428 },
429 )
430}
431
432#[inline(never)]
433fn report_validation_error<'tcx>(
434 ecx: &InterpCx<'tcx, CompileTimeMachine<'tcx>>,
435 cid: GlobalId<'tcx>,
436 error: InterpErrorInfo<'tcx>,
437 alloc_id: AllocId,
438) -> ErrorHandled {
439 if !matches!(error.kind(), InterpErrorKind::UndefinedBehavior(_)) {
440 return report_eval_error(ecx, cid, error);
442 }
443
444 let (error, backtrace) = error.into_parts();
445 backtrace.print_backtrace();
446
447 let bytes = ecx.print_alloc_bytes_for_diagnostics(alloc_id);
448 let info = ecx.get_alloc_info(alloc_id);
449 let raw_bytes =
450 errors::RawBytesNote { size: info.size.bytes(), align: info.align.bytes(), bytes };
451
452 crate::const_eval::report(
453 ecx,
454 error,
455 DUMMY_SP,
456 || crate::const_eval::get_span_and_frames(ecx.tcx, ecx.stack()),
457 move |diag, span, frames| {
458 diag.code(E0080);
460 diag.span_label(span, crate::fluent_generated::const_eval_validation_failure);
461 diag.note(crate::fluent_generated::const_eval_validation_failure_note);
462 for frame in frames {
463 diag.subdiagnostic(frame);
464 }
465 diag.subdiagnostic(raw_bytes);
466 },
467 )
468}