rustc_const_eval/const_eval/
eval_queries.rs

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// Returns a pointer to where the result lives
28#[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    // This can't use `init_stack_frame` since `body` is not a function,
74    // so computing its ABI would fail. It's also not worth it since there are no arguments to pass.
75    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    // The main interpreter loop.
84    while ecx.step()? {
85        if CTRL_C_RECEIVED.load(Relaxed) {
86            throw_exhaust!(Interrupted);
87        }
88    }
89
90    // Intern the result
91    let intern_result = intern_const_alloc_recursive(ecx, intern_kind, &ret);
92
93    // Since evaluation had no errors, validate the resulting constant.
94    const_validate_mplace(ecx, &ret, cid)?;
95
96    // Only report this after validation, as validation produces much better diagnostics.
97    // FIXME: ensure validation always reports this and stop making interning care about it.
98
99    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
125/// The `InterpCx` is only meant to be used to do field and index projections into constants for
126/// `simd_shuffle` and const patterns in match arms.
127///
128/// This should *not* be used to do any actual interpretation. In particular, alignment checks are
129/// turned off!
130///
131/// The function containing the `match` that is currently being analyzed may have generic bounds
132/// that inform us about the generic bounds of the constant. E.g., using an associated constant
133/// of a function's generic parameter will require knowledge about the bounds on the generic
134/// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
135pub(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
150/// Create an interpreter context to inspect the given `ConstValue`.
151/// Returns both the context and an `OpTy` that represents the constant.
152pub 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    // FIXME: is it a problem to discard the error here?
160    let op = ecx.const_val_to_op(val, ty, None).discard_err()?;
161    Some((ecx, op))
162}
163
164/// This function converts an interpreter value into a MIR constant.
165///
166/// The `for_diagnostics` flag turns the usual rules for returning `ConstValue::Scalar` into a
167/// best-effort attempt. This is not okay for use in const-eval sine it breaks invariants rustc
168/// relies on, but it is okay for diagnostics which will just give up gracefully when they
169/// encounter an `Indirect` they cannot handle.
170#[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    // Handle ZST consistently and early.
177    if op.layout.is_zst() {
178        return ConstValue::ZeroSized;
179    }
180
181    // All scalar types should be stored as `ConstValue::Scalar`. This is needed to make
182    // `ConstValue::try_to_scalar` efficient; we want that to work for *all* constants of scalar
183    // type (it's used throughout the compiler and having it work just on literals is not enough)
184    // and we want it to be fast (i.e., don't go to an `Allocation` and reconstruct the `Scalar`
185    // from its byte-serialized form).
186    let force_as_immediate = match op.layout.backend_repr {
187        BackendRepr::Scalar(abi::Scalar::Initialized { .. }) => true,
188        // We don't *force* `ConstValue::Slice` for `ScalarPair`. This has the advantage that if the
189        // input `op` is a place, then turning it into a `ConstValue` and back into a `OpTy` will
190        // not have to generate any duplicate allocations (we preserve the original `AllocId` in
191        // `ConstValue::Indirect`). It means accessing the contents of a slice can be slow (since
192        // they can be stored as `ConstValue::Indirect`), but that's not relevant since we barely
193        // ever have to do this. (`try_get_slice_bytes_for_diagnostics` exists to provide this
194        // functionality.)
195        _ => 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                    // This discard the error, but for diagnostics that's okay.
203                    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        // see comment on `let force_as_immediate` above
223        Right(imm) => match *imm {
224            Immediate::Scalar(x) => ConstValue::Scalar(x),
225            Immediate::ScalarPair(a, b) => {
226                debug!("ScalarPair(a: {:?}, b: {:?})", a, b);
227                // This codepath solely exists for `valtree_to_const_value` to not need to generate
228                // a `ConstValue::Indirect` for wide references, so it is tightly restricted to just
229                // that case.
230                let pointee_ty = imm.layout.ty.builtin_deref(false).unwrap(); // `false` = no raw ptrs
231                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    // This is just accessing an already computed constant, so no need to check alignment here.
263    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    // Turn this into a proper constant.
280    op_to_const(&ecx, &mplace.into(), /* for diagnostics */ 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    /// This function takes the place where the result of the evaluation is stored
305    /// and prepares it for returning it in the appropriate format needed by the specific
306    /// evaluation query.
307    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    // This shouldn't be used for statics, since statics are conceptually places,
328    // not values -- so what we do here could break pointer identity.
329    assert!(key.value.promoted.is_some() || !tcx.is_static(key.value.instance.def_id()));
330    // Const eval always happens in PostAnalysis mode . See the comment in
331    // `InterpCx::new` for more details.
332    debug_assert_eq!(key.typing_env.typing_mode, ty::TypingMode::PostAnalysis);
333    if cfg!(debug_assertions) {
334        // Make sure we format the instance even if we do not print it.
335        // This serves as a regression test against an ICE on printing.
336        // The next two lines concatenated contain some discussion:
337        // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
338        // subject/anon_const_instance_printing/near/135980032
339        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        // Statics (and promoteds inside statics) may access mutable global memory, because unlike consts
359        // they do not have to behave "as if" they were evaluated at runtime.
360        // For consts however we want to ensure they behave "as if" they were evaluated at runtime,
361        // so we have to reject reading mutable global memory.
362        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 }, // a `static`
383            None => {
384                // This is a normal `const` (not promoted).
385                // The outermost allocation is always only copied, so having `UnsafeCell` in there
386                // is okay despite them being in immutable memory.
387                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            // Instead of just reporting the `InterpError` via the usual machinery, we give a more targeted
393            // error about the validation failure.
394            .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            // FIXME(oli-obk): figure out how to use structured diagnostics again.
420            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            // Add after the frame rendering above, as it adds its own `instance` args.
426            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        // Some other error happened during validation, e.g. an unsupported operation.
441        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            // FIXME(oli-obk): figure out how to use structured diagnostics again.
459            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}