1 use super::{CompileTimeEvalContext, CompileTimeInterpreter, ConstEvalErr, MemoryExtra};
2 use crate::interpret::eval_nullary_intrinsic;
3 use crate::interpret::{
4 intern_const_alloc_recursive, Allocation, ConstAlloc, ConstValue, CtfeValidationMode, GlobalId,
5 Immediate, InternKind, InterpCx, InterpResult, MPlaceTy, MemoryKind, OpTy, RefTracking, Scalar,
6 ScalarMaybeUninit, StackPopCleanup,
9 use rustc_errors::ErrorReported;
11 use rustc_hir::def::DefKind;
12 use rustc_middle::mir;
13 use rustc_middle::mir::interpret::ErrorHandled;
14 use rustc_middle::mir::pretty::display_allocation;
15 use rustc_middle::traits::Reveal;
16 use rustc_middle::ty::layout::LayoutOf;
17 use rustc_middle::ty::print::with_no_trimmed_paths;
18 use rustc_middle::ty::{self, subst::Subst, TyCtxt};
19 use rustc_span::source_map::Span;
20 use rustc_target::abi::Abi;
22 use std::convert::TryInto;
24 pub fn note_on_undefined_behavior_error() -> &'static str {
25 "The rules on what exactly is undefined behavior aren't clear, \
26 so this check might be overzealous. Please open an issue on the rustc \
27 repository if you believe it should not be considered undefined behavior."
30 // Returns a pointer to where the result lives
31 fn eval_body_using_ecx<'mir, 'tcx>(
32 ecx: &mut CompileTimeEvalContext<'mir, 'tcx>,
34 body: &'mir mir::Body<'tcx>,
35 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
36 debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env);
39 cid.promoted.is_some()
41 ecx.tcx.def_kind(cid.instance.def_id()),
46 | DefKind::InlineConst
49 "Unexpected DefKind: {:?}",
50 ecx.tcx.def_kind(cid.instance.def_id())
52 let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?;
53 assert!(!layout.is_unsized());
54 let ret = ecx.allocate(layout, MemoryKind::Stack)?;
57 "eval_body_using_ecx: pushing stack frame for global: {}{}",
58 with_no_trimmed_paths(|| ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()))),
59 cid.promoted.map_or_else(String::new, |p| format!("::promoted[{:?}]", p))
66 StackPopCleanup::None { cleanup: false },
69 // The main interpreter loop.
73 let intern_kind = if cid.promoted.is_some() {
76 match tcx.static_mutability(cid.instance.def_id()) {
77 Some(m) => InternKind::Static(m),
78 None => InternKind::Constant,
81 intern_const_alloc_recursive(ecx, intern_kind, &ret)?;
83 debug!("eval_body_using_ecx done: {:?}", *ret);
87 /// The `InterpCx` is only meant to be used to do field and index projections into constants for
88 /// `simd_shuffle` and const patterns in match arms.
90 /// The function containing the `match` that is currently being analyzed may have generic bounds
91 /// that inform us about the generic bounds of the constant. E.g., using an associated constant
92 /// of a function's generic parameter will require knowledge about the bounds on the generic
93 /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
94 pub(super) fn mk_eval_cx<'mir, 'tcx>(
97 param_env: ty::ParamEnv<'tcx>,
98 can_access_statics: bool,
99 ) -> CompileTimeEvalContext<'mir, 'tcx> {
100 debug!("mk_eval_cx: {:?}", param_env);
105 CompileTimeInterpreter::new(tcx.const_eval_limit()),
106 MemoryExtra { can_access_statics },
110 /// This function converts an interpreter value into a constant that is meant for use in the
112 pub(super) fn op_to_const<'tcx>(
113 ecx: &CompileTimeEvalContext<'_, 'tcx>,
115 ) -> ConstValue<'tcx> {
116 // We do not have value optimizations for everything.
117 // Only scalars and slices, since they are very common.
118 // Note that further down we turn scalars of uninitialized bits back to `ByRef`. These can result
119 // from scalar unions that are initialized with one of their zero sized variants. We could
120 // instead allow `ConstValue::Scalar` to store `ScalarMaybeUninit`, but that would affect all
121 // the usual cases of extracting e.g. a `usize`, without there being a real use case for the
122 // `Undef` situation.
123 let try_as_immediate = match op.layout.abi {
124 Abi::Scalar(..) => true,
125 Abi::ScalarPair(..) => match op.layout.ty.kind() {
126 ty::Ref(_, inner, _) => match *inner.kind() {
127 ty::Slice(elem) => elem == ecx.tcx.types.u8,
135 let immediate = if try_as_immediate {
136 Err(ecx.read_immediate(op).expect("normalization works on validated constants"))
138 // It is guaranteed that any non-slice scalar pair is actually ByRef here.
139 // When we come back from raw const eval, we are always by-ref. The only way our op here is
140 // by-val is if we are in destructure_const, i.e., if this is (a field of) something that we
141 // "tried to make immediate" before. We wouldn't do that for non-slice scalar pairs or
142 // structs containing such.
146 // We know `offset` is relative to the allocation, so we can use `into_parts`.
147 let to_const_value = |mplace: &MPlaceTy<'_>| match mplace.ptr.into_parts() {
148 (Some(alloc_id), offset) => {
149 let alloc = ecx.tcx.global_alloc(alloc_id).unwrap_memory();
150 ConstValue::ByRef { alloc, offset }
153 assert!(mplace.layout.is_zst());
155 offset.bytes() % mplace.layout.align.abi.bytes(),
157 "this MPlaceTy must come from a validated constant, thus we can assume the \
158 alignment is correct",
160 ConstValue::Scalar(Scalar::ZST)
164 Ok(ref mplace) => to_const_value(mplace),
165 // see comment on `let try_as_immediate` above
166 Err(imm) => match *imm {
167 Immediate::Scalar(x) => match x {
168 ScalarMaybeUninit::Scalar(s) => ConstValue::Scalar(s),
169 ScalarMaybeUninit::Uninit => to_const_value(&op.assert_mem_place()),
171 Immediate::ScalarPair(a, b) => {
172 // We know `offset` is relative to the allocation, so we can use `into_parts`.
173 let (data, start) = match ecx.scalar_to_ptr(a.check_init().unwrap()).into_parts() {
174 (Some(alloc_id), offset) => {
175 (ecx.tcx.global_alloc(alloc_id).unwrap_memory(), offset.bytes())
178 ecx.tcx.intern_const_alloc(Allocation::from_bytes_byte_aligned_immutable(
184 let len = b.to_machine_usize(ecx).unwrap();
185 let start = start.try_into().unwrap();
186 let len: usize = len.try_into().unwrap();
187 ConstValue::Slice { data, start, end: start + len }
193 fn turn_into_const_value<'tcx>(
195 constant: ConstAlloc<'tcx>,
196 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
197 ) -> ConstValue<'tcx> {
199 let def_id = cid.instance.def.def_id();
200 let is_static = tcx.is_static(def_id);
201 let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env, is_static);
203 let mplace = ecx.raw_const_to_mplace(constant).expect(
204 "can only fail if layout computation failed, \
205 which should have given a good error before ever invoking this function",
208 !is_static || cid.promoted.is_some(),
209 "the `eval_to_const_value_raw` query should not be used for statics, use `eval_to_allocation` instead"
211 // Turn this into a proper constant.
212 op_to_const(&ecx, &mplace.into())
215 pub fn eval_to_const_value_raw_provider<'tcx>(
217 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
218 ) -> ::rustc_middle::mir::interpret::EvalToConstValueResult<'tcx> {
219 assert!(key.param_env.constness() == hir::Constness::Const);
220 // see comment in eval_to_allocation_raw_provider for what we're doing here
221 if key.param_env.reveal() == Reveal::All {
223 key.param_env = key.param_env.with_user_facing();
224 match tcx.eval_to_const_value_raw(key) {
225 // try again with reveal all as requested
226 Err(ErrorHandled::TooGeneric) => {}
228 other => return other,
232 // We call `const_eval` for zero arg intrinsics, too, in order to cache their value.
233 // Catch such calls and evaluate them instead of trying to load a constant's MIR.
234 if let ty::InstanceDef::Intrinsic(def_id) = key.value.instance.def {
235 let ty = key.value.instance.ty(tcx, key.param_env);
236 let substs = match ty.kind() {
237 ty::FnDef(_, substs) => substs,
238 _ => bug!("intrinsic with type {:?}", ty),
240 return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs).map_err(|error| {
241 let span = tcx.def_span(def_id);
242 let error = ConstEvalErr { error: error.into_kind(), stacktrace: vec![], span };
243 error.report_as_error(tcx.at(span), "could not evaluate nullary intrinsic")
247 tcx.eval_to_allocation_raw(key).map(|val| turn_into_const_value(tcx, val, key))
250 pub fn eval_to_allocation_raw_provider<'tcx>(
252 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
253 ) -> ::rustc_middle::mir::interpret::EvalToAllocationRawResult<'tcx> {
254 assert!(key.param_env.constness() == hir::Constness::Const);
255 // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
256 // reporting the same error twice here. To resolve this, we check whether we can evaluate the
257 // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
258 // computed. For a large percentage of constants that will already have succeeded. Only
259 // associated constants of generic functions will fail due to not enough monomorphization
260 // information being available.
262 // In case we fail in the `UserFacing` variant, we just do the real computation.
263 if key.param_env.reveal() == Reveal::All {
265 key.param_env = key.param_env.with_user_facing();
266 match tcx.eval_to_allocation_raw(key) {
267 // try again with reveal all as requested
268 Err(ErrorHandled::TooGeneric) => {}
270 other => return other,
273 if cfg!(debug_assertions) {
274 // Make sure we format the instance even if we do not print it.
275 // This serves as a regression test against an ICE on printing.
276 // The next two lines concatenated contain some discussion:
277 // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
278 // subject/anon_const_instance_printing/near/135980032
279 let instance = with_no_trimmed_paths(|| key.value.instance.to_string());
280 trace!("const eval: {:?} ({})", key, instance);
284 let def = cid.instance.def.with_opt_param();
286 if let Some(def) = def.as_local() {
287 if tcx.has_typeck_results(def.did) {
288 if let Some(error_reported) = tcx.typeck_opt_const_arg(def).tainted_by_errors {
289 return Err(ErrorHandled::Reported(error_reported));
292 if !tcx.is_mir_available(def.did) {
293 tcx.sess.delay_span_bug(
294 tcx.def_span(def.did),
295 &format!("no MIR body is available for {:?}", def.did),
297 return Err(ErrorHandled::Reported(ErrorReported {}));
299 if let Some(error_reported) = tcx.mir_const_qualif_opt_const_arg(def).error_occured {
300 return Err(ErrorHandled::Reported(error_reported));
304 let is_static = tcx.is_static(def.did);
306 let mut ecx = InterpCx::new(
308 tcx.def_span(def.did),
310 CompileTimeInterpreter::new(tcx.const_eval_limit()),
311 // Statics (and promoteds inside statics) may access other statics, because unlike consts
312 // they do not have to behave "as if" they were evaluated at runtime.
313 MemoryExtra { can_access_statics: is_static },
316 let res = ecx.load_mir(cid.instance.def, cid.promoted);
317 match res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, &body)) {
319 let err = ConstEvalErr::new(&ecx, error, None);
320 // Some CTFE errors raise just a lint, not a hard error; see
321 // <https://github.com/rust-lang/rust/issues/71800>.
322 let is_hard_err = if let Some(def) = def.as_local() {
323 // (Associated) consts only emit a lint, since they might be unused.
324 !matches!(tcx.def_kind(def.did.to_def_id()), DefKind::Const | DefKind::AssocConst)
325 // check if the inner InterpError is hard
326 || err.error.is_hard_err()
328 // use of broken constant from other crate: always an error
333 let msg = if is_static {
334 Cow::from("could not evaluate static initializer")
336 // If the current item has generics, we'd like to enrich the message with the
337 // instance and its substs: to show the actual compile-time values, in addition to
338 // the expression, leading to the const eval error.
339 let instance = &key.value.instance;
340 if !instance.substs.is_empty() {
341 let instance = with_no_trimmed_paths(|| instance.to_string());
342 let msg = format!("evaluation of `{}` failed", instance);
345 Cow::from("evaluation of constant value failed")
349 Err(err.report_as_error(ecx.tcx.at(ecx.cur_span()), &msg))
351 let hir_id = tcx.hir().local_def_id_to_hir_id(def.as_local().unwrap().did);
352 Err(err.report_as_lint(
353 tcx.at(tcx.def_span(def.did)),
354 "any use of this value will cause an error",
361 // Since evaluation had no errors, validate the resulting constant.
362 // This is a separate `try` block to provide more targeted error reporting.
363 let validation = try {
364 let mut ref_tracking = RefTracking::new(mplace);
365 let mut inner = false;
366 while let Some((mplace, path)) = ref_tracking.todo.pop() {
367 let mode = match tcx.static_mutability(cid.instance.def_id()) {
368 Some(_) if cid.promoted.is_some() => {
369 // Promoteds in statics are allowed to point to statics.
370 CtfeValidationMode::Const { inner, allow_static_ptrs: true }
372 Some(_) => CtfeValidationMode::Regular, // a `static`
373 None => CtfeValidationMode::Const { inner, allow_static_ptrs: false },
375 ecx.const_validate_operand(&mplace.into(), path, &mut ref_tracking, mode)?;
379 let alloc_id = mplace.ptr.provenance.unwrap();
380 if let Err(error) = validation {
381 // Validation failed, report an error. This is always a hard error.
382 let err = ConstEvalErr::new(&ecx, error, None);
383 Err(err.struct_error(
385 "it is undefined behavior to use this value",
387 diag.note(note_on_undefined_behavior_error());
389 "the raw bytes of the constant ({}",
392 ecx.tcx.global_alloc(alloc_id).unwrap_memory()
399 // Convert to raw constant
400 Ok(ConstAlloc { alloc_id, ty: mplace.layout.ty })