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;
10 use rustc_hir::def::DefKind;
11 use rustc_middle::mir;
12 use rustc_middle::mir::interpret::ErrorHandled;
13 use rustc_middle::mir::pretty::display_allocation;
14 use rustc_middle::traits::Reveal;
15 use rustc_middle::ty::layout::LayoutOf;
16 use rustc_middle::ty::print::with_no_trimmed_paths;
17 use rustc_middle::ty::{self, subst::Subst, TyCtxt};
18 use rustc_span::source_map::Span;
19 use rustc_target::abi::Abi;
21 use std::convert::TryInto;
23 pub fn note_on_undefined_behavior_error() -> &'static str {
24 "The rules on what exactly is undefined behavior aren't clear, \
25 so this check might be overzealous. Please open an issue on the rustc \
26 repository if you believe it should not be considered undefined behavior."
29 // Returns a pointer to where the result lives
30 fn eval_body_using_ecx<'mir, 'tcx>(
31 ecx: &mut CompileTimeEvalContext<'mir, 'tcx>,
33 body: &'mir mir::Body<'tcx>,
34 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
35 debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env);
38 cid.promoted.is_some()
40 ecx.tcx.def_kind(cid.instance.def_id()),
47 "Unexpected DefKind: {:?}",
48 ecx.tcx.def_kind(cid.instance.def_id())
50 let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?;
51 assert!(!layout.is_unsized());
52 let ret = ecx.allocate(layout, MemoryKind::Stack)?;
55 "eval_body_using_ecx: pushing stack frame for global: {}{}",
56 with_no_trimmed_paths(|| ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()))),
57 cid.promoted.map_or_else(String::new, |p| format!("::promoted[{:?}]", p))
64 StackPopCleanup::None { cleanup: false },
67 // The main interpreter loop.
71 let intern_kind = if cid.promoted.is_some() {
74 match tcx.static_mutability(cid.instance.def_id()) {
75 Some(m) => InternKind::Static(m),
76 None => InternKind::Constant,
79 intern_const_alloc_recursive(ecx, intern_kind, &ret)?;
81 debug!("eval_body_using_ecx done: {:?}", *ret);
85 /// The `InterpCx` is only meant to be used to do field and index projections into constants for
86 /// `simd_shuffle` and const patterns in match arms.
88 /// The function containing the `match` that is currently being analyzed may have generic bounds
89 /// that inform us about the generic bounds of the constant. E.g., using an associated constant
90 /// of a function's generic parameter will require knowledge about the bounds on the generic
91 /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
92 pub(super) fn mk_eval_cx<'mir, 'tcx>(
95 param_env: ty::ParamEnv<'tcx>,
96 can_access_statics: bool,
97 ) -> CompileTimeEvalContext<'mir, 'tcx> {
98 debug!("mk_eval_cx: {:?}", param_env);
103 CompileTimeInterpreter::new(tcx.const_eval_limit()),
104 MemoryExtra { can_access_statics },
108 /// This function converts an interpreter value into a constant that is meant for use in the
110 pub(super) fn op_to_const<'tcx>(
111 ecx: &CompileTimeEvalContext<'_, 'tcx>,
113 ) -> ConstValue<'tcx> {
114 // We do not have value optimizations for everything.
115 // Only scalars and slices, since they are very common.
116 // Note that further down we turn scalars of uninitialized bits back to `ByRef`. These can result
117 // from scalar unions that are initialized with one of their zero sized variants. We could
118 // instead allow `ConstValue::Scalar` to store `ScalarMaybeUninit`, but that would affect all
119 // the usual cases of extracting e.g. a `usize`, without there being a real use case for the
120 // `Undef` situation.
121 let try_as_immediate = match op.layout.abi {
122 Abi::Scalar(..) => true,
123 Abi::ScalarPair(..) => match op.layout.ty.kind() {
124 ty::Ref(_, inner, _) => match *inner.kind() {
125 ty::Slice(elem) => elem == ecx.tcx.types.u8,
133 let immediate = if try_as_immediate {
134 Err(ecx.read_immediate(op).expect("normalization works on validated constants"))
136 // It is guaranteed that any non-slice scalar pair is actually ByRef here.
137 // When we come back from raw const eval, we are always by-ref. The only way our op here is
138 // by-val is if we are in destructure_const, i.e., if this is (a field of) something that we
139 // "tried to make immediate" before. We wouldn't do that for non-slice scalar pairs or
140 // structs containing such.
144 // We know `offset` is relative to the allocation, so we can use `into_parts`.
145 let to_const_value = |mplace: &MPlaceTy<'_>| match mplace.ptr.into_parts() {
146 (Some(alloc_id), offset) => {
147 let alloc = ecx.tcx.global_alloc(alloc_id).unwrap_memory();
148 ConstValue::ByRef { alloc, offset }
151 assert!(mplace.layout.is_zst());
153 offset.bytes() % mplace.layout.align.abi.bytes(),
155 "this MPlaceTy must come from a validated constant, thus we can assume the \
156 alignment is correct",
158 ConstValue::Scalar(Scalar::ZST)
162 Ok(ref mplace) => to_const_value(mplace),
163 // see comment on `let try_as_immediate` above
164 Err(imm) => match *imm {
165 Immediate::Scalar(x) => match x {
166 ScalarMaybeUninit::Scalar(s) => ConstValue::Scalar(s),
167 ScalarMaybeUninit::Uninit => to_const_value(&op.assert_mem_place()),
169 Immediate::ScalarPair(a, b) => {
170 // We know `offset` is relative to the allocation, so we can use `into_parts`.
171 let (data, start) = match ecx.scalar_to_ptr(a.check_init().unwrap()).into_parts() {
172 (Some(alloc_id), offset) => {
173 (ecx.tcx.global_alloc(alloc_id).unwrap_memory(), offset.bytes())
176 ecx.tcx.intern_const_alloc(Allocation::from_bytes_byte_aligned_immutable(
182 let len = b.to_machine_usize(ecx).unwrap();
183 let start = start.try_into().unwrap();
184 let len: usize = len.try_into().unwrap();
185 ConstValue::Slice { data, start, end: start + len }
191 fn turn_into_const_value<'tcx>(
193 constant: ConstAlloc<'tcx>,
194 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
195 ) -> ConstValue<'tcx> {
197 let def_id = cid.instance.def.def_id();
198 let is_static = tcx.is_static(def_id);
199 let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env, is_static);
201 let mplace = ecx.raw_const_to_mplace(constant).expect(
202 "can only fail if layout computation failed, \
203 which should have given a good error before ever invoking this function",
206 !is_static || cid.promoted.is_some(),
207 "the `eval_to_const_value_raw` query should not be used for statics, use `eval_to_allocation` instead"
209 // Turn this into a proper constant.
210 op_to_const(&ecx, &mplace.into())
213 pub fn eval_to_const_value_raw_provider<'tcx>(
215 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
216 ) -> ::rustc_middle::mir::interpret::EvalToConstValueResult<'tcx> {
217 // see comment in eval_to_allocation_raw_provider for what we're doing here
218 if key.param_env.reveal() == Reveal::All {
220 key.param_env = key.param_env.with_user_facing();
221 match tcx.eval_to_const_value_raw(key) {
222 // try again with reveal all as requested
223 Err(ErrorHandled::TooGeneric) => {}
225 other => return other,
229 // We call `const_eval` for zero arg intrinsics, too, in order to cache their value.
230 // Catch such calls and evaluate them instead of trying to load a constant's MIR.
231 if let ty::InstanceDef::Intrinsic(def_id) = key.value.instance.def {
232 let ty = key.value.instance.ty(tcx, key.param_env);
233 let substs = match ty.kind() {
234 ty::FnDef(_, substs) => substs,
235 _ => bug!("intrinsic with type {:?}", ty),
237 return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs).map_err(|error| {
238 let span = tcx.def_span(def_id);
239 let error = ConstEvalErr { error: error.into_kind(), stacktrace: vec![], span };
240 error.report_as_error(tcx.at(span), "could not evaluate nullary intrinsic")
244 tcx.eval_to_allocation_raw(key).map(|val| turn_into_const_value(tcx, val, key))
247 pub fn eval_to_allocation_raw_provider<'tcx>(
249 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
250 ) -> ::rustc_middle::mir::interpret::EvalToAllocationRawResult<'tcx> {
251 // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
252 // reporting the same error twice here. To resolve this, we check whether we can evaluate the
253 // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
254 // computed. For a large percentage of constants that will already have succeeded. Only
255 // associated constants of generic functions will fail due to not enough monomorphization
256 // information being available.
258 // In case we fail in the `UserFacing` variant, we just do the real computation.
259 if key.param_env.reveal() == Reveal::All {
261 key.param_env = key.param_env.with_user_facing();
262 match tcx.eval_to_allocation_raw(key) {
263 // try again with reveal all as requested
264 Err(ErrorHandled::TooGeneric) => {}
266 other => return other,
269 if cfg!(debug_assertions) {
270 // Make sure we format the instance even if we do not print it.
271 // This serves as a regression test against an ICE on printing.
272 // The next two lines concatenated contain some discussion:
273 // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
274 // subject/anon_const_instance_printing/near/135980032
275 let instance = with_no_trimmed_paths(|| key.value.instance.to_string());
276 trace!("const eval: {:?} ({})", key, instance);
280 let def = cid.instance.def.with_opt_param();
282 if let Some(def) = def.as_local() {
283 if tcx.has_typeck_results(def.did) {
284 if let Some(error_reported) = tcx.typeck_opt_const_arg(def).tainted_by_errors {
285 return Err(ErrorHandled::Reported(error_reported));
288 if !tcx.is_mir_available(def.did) {
289 tcx.sess.delay_span_bug(
290 tcx.def_span(def.did),
291 &format!("no MIR body is available for {:?}", def.did),
293 return Err(ErrorHandled::Reported(ErrorReported {}));
295 if let Some(error_reported) = tcx.mir_const_qualif_opt_const_arg(def).error_occured {
296 return Err(ErrorHandled::Reported(error_reported));
300 let is_static = tcx.is_static(def.did);
302 let mut ecx = InterpCx::new(
304 tcx.def_span(def.did),
306 CompileTimeInterpreter::new(tcx.const_eval_limit()),
307 // Statics (and promoteds inside statics) may access other statics, because unlike consts
308 // they do not have to behave "as if" they were evaluated at runtime.
309 MemoryExtra { can_access_statics: is_static },
312 let res = ecx.load_mir(cid.instance.def, cid.promoted);
313 match res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, &body)) {
315 let err = ConstEvalErr::new(&ecx, error, None);
316 // Some CTFE errors raise just a lint, not a hard error; see
317 // <https://github.com/rust-lang/rust/issues/71800>.
318 let is_hard_err = if let Some(def) = def.as_local() {
319 // (Associated) consts only emit a lint, since they might be unused.
320 !matches!(tcx.def_kind(def.did.to_def_id()), DefKind::Const | DefKind::AssocConst)
321 // check if the inner InterpError is hard
322 || err.error.is_hard_err()
324 // use of broken constant from other crate: always an error
329 let msg = if is_static {
330 Cow::from("could not evaluate static initializer")
332 // If the current item has generics, we'd like to enrich the message with the
333 // instance and its substs: to show the actual compile-time values, in addition to
334 // the expression, leading to the const eval error.
335 let instance = &key.value.instance;
336 if !instance.substs.is_empty() {
337 let instance = with_no_trimmed_paths(|| instance.to_string());
338 let msg = format!("evaluation of `{}` failed", instance);
341 Cow::from("evaluation of constant value failed")
345 Err(err.report_as_error(ecx.tcx.at(ecx.cur_span()), &msg))
347 let hir_id = tcx.hir().local_def_id_to_hir_id(def.as_local().unwrap().did);
348 Err(err.report_as_lint(
349 tcx.at(tcx.def_span(def.did)),
350 "any use of this value will cause an error",
357 // Since evaluation had no errors, validate the resulting constant.
358 // This is a separate `try` block to provide more targeted error reporting.
359 let validation = try {
360 let mut ref_tracking = RefTracking::new(mplace);
361 let mut inner = false;
362 while let Some((mplace, path)) = ref_tracking.todo.pop() {
363 let mode = match tcx.static_mutability(cid.instance.def_id()) {
364 Some(_) if cid.promoted.is_some() => {
365 // Promoteds in statics are allowed to point to statics.
366 CtfeValidationMode::Const { inner, allow_static_ptrs: true }
368 Some(_) => CtfeValidationMode::Regular, // a `static`
369 None => CtfeValidationMode::Const { inner, allow_static_ptrs: false },
371 ecx.const_validate_operand(&mplace.into(), path, &mut ref_tracking, mode)?;
375 let alloc_id = mplace.ptr.provenance.unwrap();
376 if let Err(error) = validation {
377 // Validation failed, report an error. This is always a hard error.
378 let err = ConstEvalErr::new(&ecx, error, None);
379 Err(err.struct_error(
381 "it is undefined behavior to use this value",
383 diag.note(note_on_undefined_behavior_error());
385 "the raw bytes of the constant ({}",
388 ecx.tcx.global_alloc(alloc_id).unwrap_memory()
395 // Convert to raw constant
396 Ok(ConstAlloc { alloc_id, ty: mplace.layout.ty })