1 use super::{error_to_const_error, CompileTimeEvalContext, CompileTimeInterpreter, MemoryExtra};
2 use crate::interpret::eval_nullary_intrinsic;
3 use crate::interpret::{
4 intern_const_alloc_recursive, Allocation, ConstValue, GlobalId, ImmTy, Immediate, InternKind,
5 InterpCx, InterpResult, MPlaceTy, MemoryKind, OpTy, RawConst, RefTracking, Scalar,
6 ScalarMaybeUndef, StackPopCleanup,
9 use rustc::mir::interpret::{ConstEvalErr, ErrorHandled};
10 use rustc::traits::Reveal;
11 use rustc::ty::{self, layout, layout::LayoutOf, subst::Subst, TyCtxt};
12 use rustc_hir::def::DefKind;
13 use rustc_span::source_map::Span;
14 use std::convert::TryInto;
16 pub fn note_on_undefined_behavior_error() -> &'static str {
17 "The rules on what exactly is undefined behavior aren't clear, \
18 so this check might be overzealous. Please open an issue on the rustc \
19 repository if you believe it should not be considered undefined behavior."
22 // Returns a pointer to where the result lives
23 fn eval_body_using_ecx<'mir, 'tcx>(
24 ecx: &mut CompileTimeEvalContext<'mir, 'tcx>,
26 body: &'mir mir::Body<'tcx>,
27 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
28 debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env);
29 let tcx = ecx.tcx.tcx;
30 let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?;
31 assert!(!layout.is_unsized());
32 let ret = ecx.allocate(layout, MemoryKind::Stack);
34 let name = ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()));
35 let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p));
36 trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom);
38 // Assert all args (if any) are zero-sized types; `eval_body_using_ecx` doesn't
39 // make sense if the body is expecting nontrivial arguments.
40 // (The alternative would be to use `eval_fn_call` with an args slice.)
41 for arg in body.args_iter() {
42 let decl = body.local_decls.get(arg).expect("arg missing from local_decls");
43 let layout = ecx.layout_of(decl.ty.subst(tcx, cid.instance.substs))?;
44 assert!(layout.is_zst())
52 StackPopCleanup::None { cleanup: false },
55 // The main interpreter loop.
59 let intern_kind = match tcx.static_mutability(cid.instance.def_id()) {
60 Some(m) => InternKind::Static(m),
61 None if cid.promoted.is_some() => InternKind::Promoted,
62 _ => InternKind::Constant,
64 intern_const_alloc_recursive(
68 body.ignore_interior_mut_in_const_validation,
71 debug!("eval_body_using_ecx done: {:?}", *ret);
75 /// The `InterpCx` is only meant to be used to do field and index projections into constants for
76 /// `simd_shuffle` and const patterns in match arms.
78 /// The function containing the `match` that is currently being analyzed may have generic bounds
79 /// that inform us about the generic bounds of the constant. E.g., using an associated constant
80 /// of a function's generic parameter will require knowledge about the bounds on the generic
81 /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
82 pub(super) fn mk_eval_cx<'mir, 'tcx>(
85 param_env: ty::ParamEnv<'tcx>,
86 can_access_statics: bool,
87 ) -> CompileTimeEvalContext<'mir, 'tcx> {
88 debug!("mk_eval_cx: {:?}", param_env);
92 CompileTimeInterpreter::new(),
93 MemoryExtra { can_access_statics },
97 pub(super) fn op_to_const<'tcx>(
98 ecx: &CompileTimeEvalContext<'_, 'tcx>,
100 ) -> ConstValue<'tcx> {
101 // We do not have value optimizations for everything.
102 // Only scalars and slices, since they are very common.
103 // Note that further down we turn scalars of undefined bits back to `ByRef`. These can result
104 // from scalar unions that are initialized with one of their zero sized variants. We could
105 // instead allow `ConstValue::Scalar` to store `ScalarMaybeUndef`, but that would affect all
106 // the usual cases of extracting e.g. a `usize`, without there being a real use case for the
107 // `Undef` situation.
108 let try_as_immediate = match op.layout.abi {
109 layout::Abi::Scalar(..) => true,
110 layout::Abi::ScalarPair(..) => match op.layout.ty.kind {
111 ty::Ref(_, inner, _) => match inner.kind {
112 ty::Slice(elem) => elem == ecx.tcx.types.u8,
120 let immediate = if try_as_immediate {
121 Err(ecx.read_immediate(op).expect("normalization works on validated constants"))
123 // It is guaranteed that any non-slice scalar pair is actually ByRef here.
124 // When we come back from raw const eval, we are always by-ref. The only way our op here is
125 // by-val is if we are in const_field, i.e., if this is (a field of) something that we
126 // "tried to make immediate" before. We wouldn't do that for non-slice scalar pairs or
127 // structs containing such.
128 op.try_as_mplace(ecx)
131 let to_const_value = |mplace: MPlaceTy<'_>| match mplace.ptr {
132 Scalar::Ptr(ptr) => {
133 let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
134 ConstValue::ByRef { alloc, offset: ptr.offset }
136 Scalar::Raw { data, .. } => {
137 assert!(mplace.layout.is_zst());
140 mplace.layout.align.abi.bytes().into(),
141 "this MPlaceTy must come from `try_as_mplace` being used on a zst, so we know what
142 value this integer address must have",
144 ConstValue::Scalar(Scalar::zst())
148 Ok(mplace) => to_const_value(mplace),
149 // see comment on `let try_as_immediate` above
150 Err(ImmTy { imm: Immediate::Scalar(x), .. }) => match x {
151 ScalarMaybeUndef::Scalar(s) => ConstValue::Scalar(s),
152 ScalarMaybeUndef::Undef => to_const_value(op.assert_mem_place(ecx)),
154 Err(ImmTy { imm: Immediate::ScalarPair(a, b), .. }) => {
155 let (data, start) = match a.not_undef().unwrap() {
156 Scalar::Ptr(ptr) => {
157 (ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id), ptr.offset.bytes())
159 Scalar::Raw { .. } => (
160 ecx.tcx.intern_const_alloc(Allocation::from_byte_aligned_bytes(b"" as &[u8])),
164 let len = b.to_machine_usize(&ecx.tcx.tcx).unwrap();
165 let start = start.try_into().unwrap();
166 let len: usize = len.try_into().unwrap();
167 ConstValue::Slice { data, start, end: start + len }
172 fn validate_and_turn_into_const<'tcx>(
174 constant: RawConst<'tcx>,
175 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
176 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
178 let def_id = cid.instance.def.def_id();
179 let is_static = tcx.is_static(def_id);
180 let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env, is_static);
182 let mplace = ecx.raw_const_to_mplace(constant)?;
184 // FIXME do not validate promoteds until a decision on
185 // https://github.com/rust-lang/rust/issues/67465 is made
186 if cid.promoted.is_none() {
187 let mut ref_tracking = RefTracking::new(mplace);
188 while let Some((mplace, path)) = ref_tracking.todo.pop() {
189 ecx.validate_operand(mplace.into(), path, Some(&mut ref_tracking))?;
192 // Now that we validated, turn this into a proper constant.
193 // Statics/promoteds are always `ByRef`, for the rest `op_to_const` decides
194 // whether they become immediates.
195 if is_static || cid.promoted.is_some() {
196 let ptr = mplace.ptr.assert_ptr();
197 Ok(ConstValue::ByRef {
198 alloc: ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id),
202 Ok(op_to_const(&ecx, mplace.into()))
206 val.map_err(|error| {
207 let err = error_to_const_error(&ecx, error);
208 match err.struct_error(ecx.tcx, "it is undefined behavior to use this value", |mut diag| {
209 diag.note(note_on_undefined_behavior_error());
212 Ok(_) => ErrorHandled::Reported,
218 pub fn const_eval_validated_provider<'tcx>(
220 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
221 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
222 // see comment in const_eval_raw_provider for what we're doing here
223 if key.param_env.reveal == Reveal::All {
225 key.param_env.reveal = Reveal::UserFacing;
226 match tcx.const_eval_validated(key) {
227 // try again with reveal all as requested
228 Err(ErrorHandled::TooGeneric) => {}
230 other => return other,
234 // We call `const_eval` for zero arg intrinsics, too, in order to cache their value.
235 // Catch such calls and evaluate them instead of trying to load a constant's MIR.
236 if let ty::InstanceDef::Intrinsic(def_id) = key.value.instance.def {
237 let ty = key.value.instance.ty_env(tcx, key.param_env);
238 let substs = match ty.kind {
239 ty::FnDef(_, substs) => substs,
240 _ => bug!("intrinsic with type {:?}", ty),
242 return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs).map_err(|error| {
243 let span = tcx.def_span(def_id);
244 let error = ConstEvalErr { error: error.kind, stacktrace: vec![], span };
245 error.report_as_error(tcx.at(span), "could not evaluate nullary intrinsic")
249 tcx.const_eval_raw(key).and_then(|val| validate_and_turn_into_const(tcx, val, key))
252 pub fn const_eval_raw_provider<'tcx>(
254 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
255 ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> {
256 // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
257 // reporting the same error twice here. To resolve this, we check whether we can evaluate the
258 // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
259 // computed. For a large percentage of constants that will already have succeeded. Only
260 // associated constants of generic functions will fail due to not enough monomorphization
261 // information being available.
263 // In case we fail in the `UserFacing` variant, we just do the real computation.
264 if key.param_env.reveal == Reveal::All {
266 key.param_env.reveal = Reveal::UserFacing;
267 match tcx.const_eval_raw(key) {
268 // try again with reveal all as requested
269 Err(ErrorHandled::TooGeneric) => {}
271 other => return other,
274 if cfg!(debug_assertions) {
275 // Make sure we format the instance even if we do not print it.
276 // This serves as a regression test against an ICE on printing.
277 // The next two lines concatenated contain some discussion:
278 // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
279 // subject/anon_const_instance_printing/near/135980032
280 let instance = key.value.instance.to_string();
281 trace!("const eval: {:?} ({})", key, instance);
285 let def_id = cid.instance.def.def_id();
288 && tcx.has_typeck_tables(def_id)
289 && tcx.typeck_tables_of(def_id).tainted_by_errors
291 return Err(ErrorHandled::Reported);
294 let is_static = tcx.is_static(def_id);
296 let span = tcx.def_span(cid.instance.def_id());
297 let mut ecx = InterpCx::new(
300 CompileTimeInterpreter::new(),
301 MemoryExtra { can_access_statics: is_static },
304 let res = ecx.load_mir(cid.instance.def, cid.promoted);
305 res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, *body))
307 Ok(RawConst { alloc_id: place.ptr.assert_ptr().alloc_id, ty: place.layout.ty })
310 let err = error_to_const_error(&ecx, error);
311 // errors in statics are always emitted as fatal errors
313 // Ensure that if the above error was either `TooGeneric` or `Reported`
314 // an error must be reported.
315 let v = err.report_as_error(ecx.tcx, "could not evaluate static initializer");
317 // If this is `Reveal:All`, then we need to make sure an error is reported but if
318 // this is `Reveal::UserFacing`, then it's expected that we could get a
319 // `TooGeneric` error. When we fall back to `Reveal::All`, then it will either
320 // succeed or we'll report this error then.
321 if key.param_env.reveal == Reveal::All {
322 tcx.sess.delay_span_bug(
324 &format!("static eval failure did not emit an error: {:#?}", v),
329 } else if def_id.is_local() {
330 // constant defined in this crate, we can figure out a lint level!
331 match tcx.def_kind(def_id) {
332 // constants never produce a hard error at the definition site. Anything else is
333 // a backwards compatibility hazard (and will break old versions of winapi for
336 // note that validation may still cause a hard error on this very same constant,
337 // because any code that existed before validation could not have failed
338 // validation thus preventing such a hard error from being a backwards
339 // compatibility hazard
340 Some(DefKind::Const) | Some(DefKind::AssocConst) => {
341 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
343 tcx.at(tcx.def_span(def_id)),
344 "any use of this value will cause an error",
349 // promoting runtime code is only allowed to error if it references broken
350 // constants any other kind of error will be reported to the user as a
351 // deny-by-default lint
353 if let Some(p) = cid.promoted {
354 let span = tcx.promoted_mir(def_id)[p].span;
355 if let err_inval!(ReferencedConstant) = err.error {
358 "evaluation of constant expression failed",
363 "reaching this expression at runtime will panic or abort",
364 tcx.hir().as_local_hir_id(def_id).unwrap(),
368 // anything else (array lengths, enum initializers, constant patterns) are
369 // reported as hard errors
371 err.report_as_error(ecx.tcx, "evaluation of constant value failed")
376 // use of broken constant from other crate
377 err.report_as_error(ecx.tcx, "could not evaluate constant")