1 // Not in interpret to make sure we do not use private implementation details
3 use std::borrow::{Borrow, Cow};
4 use std::collections::hash_map::Entry;
5 use std::convert::TryInto;
10 use crate::interpret::eval_nullary_intrinsic;
11 use rustc::hir::def::DefKind;
12 use rustc::hir::def_id::DefId;
14 use rustc::mir::interpret::{ConstEvalErr, ErrorHandled, ScalarMaybeUndef};
15 use rustc::traits::Reveal;
16 use rustc::ty::layout::{self, HasTyCtxt, LayoutOf, VariantIdx};
17 use rustc::ty::{self, subst::Subst, Ty, TyCtxt};
18 use rustc_data_structures::fx::FxHashMap;
21 source_map::{Span, DUMMY_SP},
25 use crate::interpret::{
26 self, intern_const_alloc_recursive, snapshot, AllocId, Allocation, AssertMessage, ConstValue,
27 GlobalId, ImmTy, Immediate, InterpCx, InterpErrorInfo, InterpResult, MPlaceTy, Machine, Memory,
28 MemoryKind, OpTy, PlaceTy, Pointer, RawConst, RefTracking, Scalar, StackPopCleanup,
31 /// Number of steps until the detector even starts doing anything.
32 /// Also, a warning is shown to the user when this number is reached.
33 const STEPS_UNTIL_DETECTOR_ENABLED: isize = 1_000_000;
34 /// The number of steps between loop detector snapshots.
35 /// Should be a power of two for performance reasons.
36 const DETECTOR_SNAPSHOT_PERIOD: isize = 256;
38 /// The `InterpCx` is only meant to be used to do field and index projections into constants for
39 /// `simd_shuffle` and const patterns in match arms.
41 /// The function containing the `match` that is currently being analyzed may have generic bounds
42 /// that inform us about the generic bounds of the constant. E.g., using an associated constant
43 /// of a function's generic parameter will require knowledge about the bounds on the generic
44 /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
45 fn mk_eval_cx<'mir, 'tcx>(
48 param_env: ty::ParamEnv<'tcx>,
49 can_access_statics: bool,
50 ) -> CompileTimeEvalContext<'mir, 'tcx> {
51 debug!("mk_eval_cx: {:?}", param_env);
55 CompileTimeInterpreter::new(),
56 MemoryExtra { can_access_statics },
61 ecx: &CompileTimeEvalContext<'_, 'tcx>,
63 ) -> &'tcx ty::Const<'tcx> {
64 // We do not have value optimizations for everything.
65 // Only scalars and slices, since they are very common.
66 // Note that further down we turn scalars of undefined bits back to `ByRef`. These can result
67 // from scalar unions that are initialized with one of their zero sized variants. We could
68 // instead allow `ConstValue::Scalar` to store `ScalarMaybeUndef`, but that would affect all
69 // the usual cases of extracting e.g. a `usize`, without there being a real use case for the
71 let try_as_immediate = match op.layout.abi {
72 layout::Abi::Scalar(..) => true,
73 layout::Abi::ScalarPair(..) => match op.layout.ty.kind {
74 ty::Ref(_, inner, _) => match inner.kind {
75 ty::Slice(elem) => elem == ecx.tcx.types.u8,
83 let immediate = if try_as_immediate {
84 Err(ecx.read_immediate(op).expect("normalization works on validated constants"))
86 // It is guaranteed that any non-slice scalar pair is actually ByRef here.
87 // When we come back from raw const eval, we are always by-ref. The only way our op here is
88 // by-val is if we are in const_field, i.e., if this is (a field of) something that we
89 // "tried to make immediate" before. We wouldn't do that for non-slice scalar pairs or
90 // structs containing such.
93 let val = match immediate {
95 let ptr = mplace.ptr.to_ptr().unwrap();
96 let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
97 ConstValue::ByRef { alloc, offset: ptr.offset }
99 // see comment on `let try_as_immediate` above
100 Err(ImmTy { imm: Immediate::Scalar(x), .. }) => match x {
101 ScalarMaybeUndef::Scalar(s) => ConstValue::Scalar(s),
102 ScalarMaybeUndef::Undef => {
103 // When coming out of "normal CTFE", we'll always have an `Indirect` operand as
104 // argument and we will not need this. The only way we can already have an
105 // `Immediate` is when we are called from `const_field`, and that `Immediate`
106 // comes from a constant so it can happen have `Undef`, because the indirect
107 // memory that was read had undefined bytes.
108 let mplace = op.assert_mem_place();
109 let ptr = mplace.ptr.to_ptr().unwrap();
110 let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
111 ConstValue::ByRef { alloc, offset: ptr.offset }
114 Err(ImmTy { imm: Immediate::ScalarPair(a, b), .. }) => {
115 let (data, start) = match a.not_undef().unwrap() {
116 Scalar::Ptr(ptr) => {
117 (ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id), ptr.offset.bytes())
119 Scalar::Raw { .. } => (
120 ecx.tcx.intern_const_alloc(Allocation::from_byte_aligned_bytes(b"" as &[u8])),
124 let len = b.to_machine_usize(&ecx.tcx.tcx).unwrap();
125 let start = start.try_into().unwrap();
126 let len: usize = len.try_into().unwrap();
127 ConstValue::Slice { data, start, end: start + len }
130 ecx.tcx.mk_const(ty::Const { val: ty::ConstKind::Value(val), ty: op.layout.ty })
133 // Returns a pointer to where the result lives
134 fn eval_body_using_ecx<'mir, 'tcx>(
135 ecx: &mut CompileTimeEvalContext<'mir, 'tcx>,
137 body: &'mir mir::Body<'tcx>,
138 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
139 debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env);
140 let tcx = ecx.tcx.tcx;
141 let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?;
142 assert!(!layout.is_unsized());
143 let ret = ecx.allocate(layout, MemoryKind::Stack);
145 let name = ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()));
146 let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p));
147 trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom);
149 // Assert all args (if any) are zero-sized types; `eval_body_using_ecx` doesn't
150 // make sense if the body is expecting nontrivial arguments.
151 // (The alternative would be to use `eval_fn_call` with an args slice.)
152 for arg in body.args_iter() {
153 let decl = body.local_decls.get(arg).expect("arg missing from local_decls");
154 let layout = ecx.layout_of(decl.ty.subst(tcx, cid.instance.substs))?;
155 assert!(layout.is_zst())
158 ecx.push_stack_frame(
163 StackPopCleanup::None { cleanup: false },
166 // The main interpreter loop.
170 intern_const_alloc_recursive(ecx, tcx.static_mutability(cid.instance.def_id()), ret)?;
172 debug!("eval_body_using_ecx done: {:?}", *ret);
176 #[derive(Clone, Debug)]
177 pub enum ConstEvalError {
182 impl<'tcx> Into<InterpErrorInfo<'tcx>> for ConstEvalError {
183 fn into(self) -> InterpErrorInfo<'tcx> {
184 err_unsup!(Unsupported(self.to_string())).into()
188 impl fmt::Display for ConstEvalError {
189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190 use self::ConstEvalError::*;
192 NeedsRfc(ref msg) => {
193 write!(f, "\"{}\" needs an rfc before being allowed inside constants", msg)
195 ConstAccessesStatic => write!(f, "constant accesses static"),
200 impl Error for ConstEvalError {
201 fn description(&self) -> &str {
202 use self::ConstEvalError::*;
204 NeedsRfc(_) => "this feature needs an rfc before being allowed inside constants",
205 ConstAccessesStatic => "constant accesses static",
209 fn cause(&self) -> Option<&dyn Error> {
214 // Extra machine state for CTFE, and the Machine instance
215 pub struct CompileTimeInterpreter<'mir, 'tcx> {
216 /// When this value is negative, it indicates the number of interpreter
217 /// steps *until* the loop detector is enabled. When it is positive, it is
218 /// the number of steps after the detector has been enabled modulo the loop
220 pub(super) steps_since_detector_enabled: isize,
222 /// Extra state to detect loops.
223 pub(super) loop_detector: snapshot::InfiniteLoopDetector<'mir, 'tcx>,
226 #[derive(Copy, Clone, Debug)]
227 pub struct MemoryExtra {
228 /// Whether this machine may read from statics
229 can_access_statics: bool,
232 impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> {
234 CompileTimeInterpreter {
235 loop_detector: Default::default(),
236 steps_since_detector_enabled: -STEPS_UNTIL_DETECTOR_ENABLED,
241 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
243 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
247 FxHashMap::contains_key(self, k)
251 fn insert(&mut self, k: K, v: V) -> Option<V> {
252 FxHashMap::insert(self, k, v)
256 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
260 FxHashMap::remove(self, k)
264 fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
265 self.iter().filter_map(move |(k, v)| f(k, &*v)).collect()
269 fn get_or<E>(&self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&V, E> {
274 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
280 fn get_mut_or<E>(&mut self, k: K, vacant: impl FnOnce() -> Result<V, E>) -> Result<&mut V, E> {
281 match self.entry(k) {
282 Entry::Occupied(e) => Ok(e.into_mut()),
283 Entry::Vacant(e) => {
291 crate type CompileTimeEvalContext<'mir, 'tcx> =
292 InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>;
294 impl interpret::MayLeak for ! {
296 fn may_leak(self) -> bool {
297 // `self` is uninhabited
302 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> {
303 type MemoryKinds = !;
304 type PointerTag = ();
307 type FrameExtra = ();
308 type MemoryExtra = MemoryExtra;
309 type AllocExtra = ();
311 type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>;
313 const STATIC_KIND: Option<!> = None; // no copying of statics allowed
315 // We do not check for alignment to avoid having to carry an `Align`
316 // in `ConstValue::ByRef`.
317 const CHECK_ALIGN: bool = false;
320 fn enforce_validity(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
321 false // for now, we don't enforce validity
324 fn find_mir_or_eval_fn(
325 ecx: &mut InterpCx<'mir, 'tcx, Self>,
326 instance: ty::Instance<'tcx>,
328 ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
329 _unwind: Option<mir::BasicBlock>, // unwinding is not supported in consts
330 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
331 debug!("find_mir_or_eval_fn: {:?}", instance);
333 // Only check non-glue functions
334 if let ty::InstanceDef::Item(def_id) = instance.def {
335 // Execution might have wandered off into other crates, so we cannot do a stability-
336 // sensitive check here. But we can at least rule out functions that are not const
338 if ecx.tcx.is_const_fn_raw(def_id) {
339 // If this function is a `const fn` then as an optimization we can query this
340 // evaluation immediately.
342 // For the moment we only do this for functions which take no arguments
343 // (or all arguments are ZSTs) so that we don't memoize too much.
345 // Because `#[track_caller]` adds an implicit non-ZST argument, we also cannot
346 // perform this optimization on items tagged with it.
347 let no_implicit_args = !instance.def.requires_caller_location(ecx.tcx());
348 if args.iter().all(|a| a.layout.is_zst()) && no_implicit_args {
349 let gid = GlobalId { instance, promoted: None };
350 ecx.eval_const_fn_call(gid, ret)?;
354 // Some functions we support even if they are non-const -- but avoid testing
355 // that for const fn! We certainly do *not* want to actually call the fn
356 // though, so be sure we return here.
357 return if ecx.hook_panic_fn(instance, args, ret)? {
360 throw_unsup_format!("calling non-const function `{}`", instance)
364 // This is a const fn. Call it.
365 Ok(Some(match ecx.load_mir(instance.def, None) {
368 if let err_unsup!(NoMirFor(ref path)) = err.kind {
369 return Err(ConstEvalError::NeedsRfc(format!(
370 "calling extern function `{}`",
381 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
383 _args: &[OpTy<'tcx>],
384 _ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
385 _unwind: Option<mir::BasicBlock>,
386 ) -> InterpResult<'tcx> {
391 ecx: &mut InterpCx<'mir, 'tcx, Self>,
393 instance: ty::Instance<'tcx>,
395 ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
396 _unwind: Option<mir::BasicBlock>,
397 ) -> InterpResult<'tcx> {
398 if ecx.emulate_intrinsic(span, instance, args, ret)? {
401 // An intrinsic that we do not support
402 let intrinsic_name = ecx.tcx.item_name(instance.def_id());
403 Err(ConstEvalError::NeedsRfc(format!("calling intrinsic `{}`", intrinsic_name)).into())
407 ecx: &mut InterpCx<'mir, 'tcx, Self>,
409 msg: &AssertMessage<'tcx>,
410 _unwind: Option<mir::BasicBlock>,
411 ) -> InterpResult<'tcx> {
412 use rustc::mir::interpret::PanicInfo::*;
414 BoundsCheck { ref len, ref index } => {
416 .read_immediate(ecx.eval_operand(len, None)?)
417 .expect("can't eval len")
419 .to_machine_usize(&*ecx)?;
421 .read_immediate(ecx.eval_operand(index, None)?)
422 .expect("can't eval index")
424 .to_machine_usize(&*ecx)?;
425 err_panic!(BoundsCheck { len, index })
427 Overflow(op) => err_panic!(Overflow(*op)),
428 OverflowNeg => err_panic!(OverflowNeg),
429 DivisionByZero => err_panic!(DivisionByZero),
430 RemainderByZero => err_panic!(RemainderByZero),
431 ResumedAfterReturn(generator_kind) => err_panic!(ResumedAfterReturn(*generator_kind)),
432 ResumedAfterPanic(generator_kind) => err_panic!(ResumedAfterPanic(*generator_kind)),
433 Panic { .. } => bug!("`Panic` variant cannot occur in MIR"),
438 fn ptr_to_int(_mem: &Memory<'mir, 'tcx, Self>, _ptr: Pointer) -> InterpResult<'tcx, u64> {
439 Err(ConstEvalError::NeedsRfc("pointer-to-integer cast".to_string()).into())
443 _ecx: &InterpCx<'mir, 'tcx, Self>,
447 ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
448 Err(ConstEvalError::NeedsRfc("pointer arithmetic or comparison".to_string()).into())
451 fn find_foreign_static(
454 ) -> InterpResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag>>> {
455 throw_unsup!(ReadForeignStatic)
459 fn init_allocation_extra<'b>(
460 _memory_extra: &MemoryExtra,
462 alloc: Cow<'b, Allocation>,
463 _kind: Option<MemoryKind<!>>,
464 ) -> (Cow<'b, Allocation<Self::PointerTag>>, Self::PointerTag) {
465 // We do not use a tag so we can just cheaply forward the allocation
470 fn tag_static_base_pointer(_memory_extra: &MemoryExtra, _id: AllocId) -> Self::PointerTag {
475 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
476 _dest: PlaceTy<'tcx>,
477 ) -> InterpResult<'tcx> {
478 Err(ConstEvalError::NeedsRfc("heap allocations via `box` keyword".to_string()).into())
481 fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
483 let steps = &mut ecx.machine.steps_since_detector_enabled;
490 *steps %= DETECTOR_SNAPSHOT_PERIOD;
496 let span = ecx.frame().span;
497 ecx.machine.loop_detector.observe_and_analyze(*ecx.tcx, span, &ecx.memory, &ecx.stack[..])
501 fn stack_push(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
505 fn before_access_static(
506 memory_extra: &MemoryExtra,
507 _allocation: &Allocation,
508 ) -> InterpResult<'tcx> {
509 if memory_extra.can_access_statics {
512 Err(ConstEvalError::ConstAccessesStatic.into())
517 /// Extracts a field of a (variant of a) const.
518 // this function uses `unwrap` copiously, because an already validated constant must have valid
519 // fields and can thus never fail outside of compiler bugs
520 pub fn const_field<'tcx>(
522 param_env: ty::ParamEnv<'tcx>,
523 variant: Option<VariantIdx>,
525 value: &'tcx ty::Const<'tcx>,
526 ) -> &'tcx ty::Const<'tcx> {
527 trace!("const_field: {:?}, {:?}", field, value);
528 let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false);
529 // get the operand again
530 let op = ecx.eval_const_to_op(value, None).unwrap();
532 let down = match variant {
534 Some(variant) => ecx.operand_downcast(op, variant).unwrap(),
537 let field = ecx.operand_field(down, field.index() as u64).unwrap();
538 // and finally move back to the const world, always normalizing because
539 // this is not called for statics.
540 op_to_const(&ecx, field)
543 pub fn const_caller_location<'tcx>(
545 (file, line, col): (Symbol, u32, u32),
546 ) -> &'tcx ty::Const<'tcx> {
547 trace!("const_caller_location: {}:{}:{}", file, line, col);
548 let mut ecx = mk_eval_cx(tcx, DUMMY_SP, ty::ParamEnv::reveal_all(), false);
550 let loc_ty = tcx.caller_location_ty();
551 let loc_place = ecx.alloc_caller_location(file, line, col);
552 intern_const_alloc_recursive(&mut ecx, None, loc_place).unwrap();
553 let loc_const = ty::Const {
555 val: ty::ConstKind::Value(ConstValue::Scalar(loc_place.ptr.into())),
558 tcx.mk_const(loc_const)
561 // this function uses `unwrap` copiously, because an already validated constant must have valid
562 // fields and can thus never fail outside of compiler bugs
563 pub fn const_variant_index<'tcx>(
565 param_env: ty::ParamEnv<'tcx>,
566 val: &'tcx ty::Const<'tcx>,
568 trace!("const_variant_index: {:?}", val);
569 let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false);
570 let op = ecx.eval_const_to_op(val, None).unwrap();
571 ecx.read_discriminant(op).unwrap().1
574 /// Turn an interpreter error into something to report to the user.
575 /// As a side-effect, if RUSTC_CTFE_BACKTRACE is set, this prints the backtrace.
576 /// Should be called only if the error is actually going to to be reported!
577 pub fn error_to_const_error<'mir, 'tcx, M: Machine<'mir, 'tcx>>(
578 ecx: &InterpCx<'mir, 'tcx, M>,
579 mut error: InterpErrorInfo<'tcx>,
580 ) -> ConstEvalErr<'tcx> {
581 error.print_backtrace();
582 let stacktrace = ecx.generate_stacktrace(None);
583 ConstEvalErr { error: error.kind, stacktrace, span: ecx.tcx.span }
586 pub fn note_on_undefined_behavior_error() -> &'static str {
587 "The rules on what exactly is undefined behavior aren't clear, \
588 so this check might be overzealous. Please open an issue on the rustc \
589 repository if you believe it should not be considered undefined behavior."
592 fn validate_and_turn_into_const<'tcx>(
594 constant: RawConst<'tcx>,
595 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
596 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
598 let def_id = cid.instance.def.def_id();
599 let is_static = tcx.is_static(def_id);
600 let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env, is_static);
602 let mplace = ecx.raw_const_to_mplace(constant)?;
603 let mut ref_tracking = RefTracking::new(mplace);
604 while let Some((mplace, path)) = ref_tracking.todo.pop() {
605 ecx.validate_operand(mplace.into(), path, Some(&mut ref_tracking))?;
607 // Now that we validated, turn this into a proper constant.
608 // Statics/promoteds are always `ByRef`, for the rest `op_to_const` decides
609 // whether they become immediates.
610 if is_static || cid.promoted.is_some() {
611 let ptr = mplace.ptr.to_ptr()?;
612 Ok(tcx.mk_const(ty::Const {
613 val: ty::ConstKind::Value(ConstValue::ByRef {
614 alloc: ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id),
617 ty: mplace.layout.ty,
620 Ok(op_to_const(&ecx, mplace.into()))
624 val.map_err(|error| {
625 let err = error_to_const_error(&ecx, error);
626 match err.struct_error(ecx.tcx, "it is undefined behavior to use this value") {
628 diag.note(note_on_undefined_behavior_error());
630 ErrorHandled::Reported
637 pub fn const_eval_validated_provider<'tcx>(
639 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
640 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
641 // see comment in const_eval_raw_provider for what we're doing here
642 if key.param_env.reveal == Reveal::All {
643 let mut key = key.clone();
644 key.param_env.reveal = Reveal::UserFacing;
645 match tcx.const_eval_validated(key) {
646 // try again with reveal all as requested
647 Err(ErrorHandled::TooGeneric) => {
648 // Promoteds should never be "too generic" when getting evaluated.
649 // They either don't get evaluated, or we are in a monomorphic context
650 assert!(key.value.promoted.is_none());
653 other => return other,
657 // We call `const_eval` for zero arg intrinsics, too, in order to cache their value.
658 // Catch such calls and evaluate them instead of trying to load a constant's MIR.
659 if let ty::InstanceDef::Intrinsic(def_id) = key.value.instance.def {
660 let ty = key.value.instance.ty(tcx);
661 let substs = match ty.kind {
662 ty::FnDef(_, substs) => substs,
663 _ => bug!("intrinsic with type {:?}", ty),
665 return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs).map_err(|error| {
666 let span = tcx.def_span(def_id);
667 let error = ConstEvalErr { error: error.kind, stacktrace: vec![], span };
668 error.report_as_error(tcx.at(span), "could not evaluate nullary intrinsic")
672 tcx.const_eval_raw(key).and_then(|val| validate_and_turn_into_const(tcx, val, key))
675 pub fn const_eval_raw_provider<'tcx>(
677 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
678 ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> {
679 // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
680 // reporting the same error twice here. To resolve this, we check whether we can evaluate the
681 // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
682 // computed. For a large percentage of constants that will already have succeeded. Only
683 // associated constants of generic functions will fail due to not enough monomorphization
684 // information being available.
686 // In case we fail in the `UserFacing` variant, we just do the real computation.
687 if key.param_env.reveal == Reveal::All {
688 let mut key = key.clone();
689 key.param_env.reveal = Reveal::UserFacing;
690 match tcx.const_eval_raw(key) {
691 // try again with reveal all as requested
692 Err(ErrorHandled::TooGeneric) => {}
694 other => return other,
697 if cfg!(debug_assertions) {
698 // Make sure we format the instance even if we do not print it.
699 // This serves as a regression test against an ICE on printing.
700 // The next two lines concatenated contain some discussion:
701 // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
702 // subject/anon_const_instance_printing/near/135980032
703 let instance = key.value.instance.to_string();
704 trace!("const eval: {:?} ({})", key, instance);
708 let def_id = cid.instance.def.def_id();
710 if def_id.is_local() && tcx.typeck_tables_of(def_id).tainted_by_errors {
711 return Err(ErrorHandled::Reported);
714 let is_static = tcx.is_static(def_id);
716 let span = tcx.def_span(cid.instance.def_id());
717 let mut ecx = InterpCx::new(
720 CompileTimeInterpreter::new(),
721 MemoryExtra { can_access_statics: is_static },
724 let res = ecx.load_mir(cid.instance.def, cid.promoted);
725 res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, *body))
727 Ok(RawConst { alloc_id: place.ptr.assert_ptr().alloc_id, ty: place.layout.ty })
730 let err = error_to_const_error(&ecx, error);
731 // errors in statics are always emitted as fatal errors
733 // Ensure that if the above error was either `TooGeneric` or `Reported`
734 // an error must be reported.
735 let v = err.report_as_error(ecx.tcx, "could not evaluate static initializer");
736 tcx.sess.delay_span_bug(
738 &format!("static eval failure did not emit an error: {:#?}", v),
741 } else if def_id.is_local() {
742 // constant defined in this crate, we can figure out a lint level!
743 match tcx.def_kind(def_id) {
744 // constants never produce a hard error at the definition site. Anything else is
745 // a backwards compatibility hazard (and will break old versions of winapi for sure)
747 // note that validation may still cause a hard error on this very same constant,
748 // because any code that existed before validation could not have failed validation
749 // thus preventing such a hard error from being a backwards compatibility hazard
750 Some(DefKind::Const) | Some(DefKind::AssocConst) => {
751 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
753 tcx.at(tcx.def_span(def_id)),
754 "any use of this value will cause an error",
759 // promoting runtime code is only allowed to error if it references broken constants
760 // any other kind of error will be reported to the user as a deny-by-default lint
762 if let Some(p) = cid.promoted {
763 let span = tcx.promoted_mir(def_id)[p].span;
764 if let err_inval!(ReferencedConstant) = err.error {
767 "evaluation of constant expression failed",
772 "reaching this expression at runtime will panic or abort",
773 tcx.hir().as_local_hir_id(def_id).unwrap(),
777 // anything else (array lengths, enum initializers, constant patterns) are reported
780 err.report_as_error(ecx.tcx, "evaluation of constant value failed")
785 // use of broken constant from other crate
786 err.report_as_error(ecx.tcx, "could not evaluate constant")