]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/const_eval.rs
Rollup merge of #61389 - Zoxc:arena-cleanup, r=eddyb
[rust.git] / src / librustc_mir / const_eval.rs
1 // Not in interpret to make sure we do not use private implementation details
2
3 use std::fmt;
4 use std::error::Error;
5 use std::borrow::{Borrow, Cow};
6 use std::hash::Hash;
7 use std::collections::hash_map::Entry;
8 use std::convert::TryInto;
9
10 use rustc::hir::def::DefKind;
11 use rustc::hir::def_id::DefId;
12 use rustc::mir::interpret::{ConstEvalErr, ErrorHandled};
13 use rustc::mir;
14 use rustc::ty::{self, TyCtxt, query::TyCtxtAt};
15 use rustc::ty::layout::{self, LayoutOf, VariantIdx, Size};
16 use rustc::ty::subst::Subst;
17 use rustc::traits::Reveal;
18 use rustc::util::common::ErrorReported;
19 use rustc_data_structures::fx::FxHashMap;
20
21 use syntax::ast::Mutability;
22 use syntax::source_map::{Span, DUMMY_SP};
23
24 use crate::interpret::{self,
25     PlaceTy, MPlaceTy, MemPlace, OpTy, ImmTy, Immediate, Scalar,
26     RawConst, ConstValue,
27     EvalResult, EvalError, InterpError, GlobalId, InterpretCx, StackPopCleanup,
28     Allocation, AllocId, MemoryKind,
29     snapshot, RefTracking,
30 };
31
32 /// Number of steps until the detector even starts doing anything.
33 /// Also, a warning is shown to the user when this number is reached.
34 const STEPS_UNTIL_DETECTOR_ENABLED: isize = 1_000_000;
35 /// The number of steps between loop detector snapshots.
36 /// Should be a power of two for performance reasons.
37 const DETECTOR_SNAPSHOT_PERIOD: isize = 256;
38
39 /// The `InterpretCx` is only meant to be used to do field and index projections into constants for
40 /// `simd_shuffle` and const patterns in match arms.
41 ///
42 /// The function containing the `match` that is currently being analyzed may have generic bounds
43 /// that inform us about the generic bounds of the constant. E.g., using an associated constant
44 /// of a function's generic parameter will require knowledge about the bounds on the generic
45 /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
46 pub(crate) fn mk_eval_cx<'a, 'mir, 'tcx>(
47     tcx: TyCtxt<'a, 'tcx, 'tcx>,
48     span: Span,
49     param_env: ty::ParamEnv<'tcx>,
50 ) -> CompileTimeEvalContext<'a, 'mir, 'tcx> {
51     debug!("mk_eval_cx: {:?}", param_env);
52     InterpretCx::new(tcx.at(span), param_env, CompileTimeInterpreter::new())
53 }
54
55 pub(crate) fn eval_promoted<'a, 'mir, 'tcx>(
56     tcx: TyCtxt<'a, 'tcx, 'tcx>,
57     cid: GlobalId<'tcx>,
58     mir: &'mir mir::Body<'tcx>,
59     param_env: ty::ParamEnv<'tcx>,
60 ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
61     let span = tcx.def_span(cid.instance.def_id());
62     let mut ecx = mk_eval_cx(tcx, span, param_env);
63     eval_body_using_ecx(&mut ecx, cid, mir, param_env)
64 }
65
66 fn mplace_to_const<'tcx>(
67     ecx: &CompileTimeEvalContext<'_, '_, 'tcx>,
68     mplace: MPlaceTy<'tcx>,
69 ) -> &'tcx ty::Const<'tcx> {
70     let MemPlace { ptr, align, meta } = *mplace;
71     // extract alloc-offset pair
72     assert!(meta.is_none());
73     let ptr = ptr.to_ptr().unwrap();
74     let alloc = ecx.memory.get(ptr.alloc_id).unwrap();
75     assert!(alloc.align >= align);
76     assert!(alloc.bytes.len() as u64 - ptr.offset.bytes() >= mplace.layout.size.bytes());
77     let mut alloc = alloc.clone();
78     alloc.align = align;
79     // FIXME shouldn't it be the case that `mark_static_initialized` has already
80     // interned this?  I thought that is the entire point of that `FinishStatic` stuff?
81     let alloc = ecx.tcx.intern_const_alloc(alloc);
82     let val = ConstValue::ByRef(ptr, alloc);
83     ecx.tcx.mk_const(ty::Const { val, ty: mplace.layout.ty })
84 }
85
86 fn op_to_const<'tcx>(
87     ecx: &CompileTimeEvalContext<'_, '_, 'tcx>,
88     op: OpTy<'tcx>,
89 ) -> &'tcx ty::Const<'tcx> {
90     // We do not normalize just any data.  Only non-union scalars and slices.
91     let normalize = match op.layout.abi {
92         layout::Abi::Scalar(..) => op.layout.ty.ty_adt_def().map_or(true, |adt| !adt.is_union()),
93         layout::Abi::ScalarPair(..) => match op.layout.ty.sty {
94             ty::Ref(_, inner, _) => match inner.sty {
95                 ty::Slice(elem) => elem == ecx.tcx.types.u8,
96                 ty::Str => true,
97                 _ => false,
98             },
99             _ => false,
100         },
101         _ => false,
102     };
103     let normalized_op = if normalize {
104         Err(*ecx.read_immediate(op).expect("normalization works on validated constants"))
105     } else {
106         op.try_as_mplace()
107     };
108     let val = match normalized_op {
109         Ok(mplace) => return mplace_to_const(ecx, mplace),
110         Err(Immediate::Scalar(x)) =>
111             ConstValue::Scalar(x.not_undef().unwrap()),
112         Err(Immediate::ScalarPair(a, b)) => {
113             let (data, start) = match a.not_undef().unwrap() {
114                 Scalar::Ptr(ptr) => (
115                     ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id),
116                     ptr.offset.bytes(),
117                 ),
118                 Scalar::Raw { .. } => (
119                     ecx.tcx.intern_const_alloc(Allocation::from_byte_aligned_bytes(
120                         b"" as &[u8], (),
121                     )),
122                     0,
123                 ),
124             };
125             let len = b.to_usize(&ecx.tcx.tcx).unwrap();
126             let start = start.try_into().unwrap();
127             let len: usize = len.try_into().unwrap();
128             ConstValue::Slice {
129                 data,
130                 start,
131                 end: start + len,
132             }
133         },
134     };
135     ecx.tcx.mk_const(ty::Const { val, ty: op.layout.ty })
136 }
137
138 // Returns a pointer to where the result lives
139 fn eval_body_using_ecx<'mir, 'tcx>(
140     ecx: &mut CompileTimeEvalContext<'_, 'mir, 'tcx>,
141     cid: GlobalId<'tcx>,
142     mir: &'mir mir::Body<'tcx>,
143     param_env: ty::ParamEnv<'tcx>,
144 ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
145     debug!("eval_body_using_ecx: {:?}, {:?}", cid, param_env);
146     let tcx = ecx.tcx.tcx;
147     let layout = ecx.layout_of(mir.return_ty().subst(tcx, cid.instance.substs))?;
148     assert!(!layout.is_unsized());
149     let ret = ecx.allocate(layout, MemoryKind::Stack);
150
151     let name = ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()));
152     let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p));
153     trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom);
154     assert!(mir.arg_count == 0);
155     ecx.push_stack_frame(
156         cid.instance,
157         mir.span,
158         mir,
159         Some(ret.into()),
160         StackPopCleanup::None { cleanup: false },
161     )?;
162
163     // The main interpreter loop.
164     ecx.run()?;
165
166     // Intern the result
167     let mutability = if tcx.is_mutable_static(cid.instance.def_id()) ||
168                      !layout.ty.is_freeze(tcx, param_env, mir.span) {
169         Mutability::Mutable
170     } else {
171         Mutability::Immutable
172     };
173     ecx.memory.intern_static(ret.ptr.to_ptr()?.alloc_id, mutability)?;
174
175     debug!("eval_body_using_ecx done: {:?}", *ret);
176     Ok(ret)
177 }
178
179 impl<'tcx> Into<EvalError<'tcx>> for ConstEvalError {
180     fn into(self) -> EvalError<'tcx> {
181         InterpError::MachineError(self.to_string()).into()
182     }
183 }
184
185 #[derive(Clone, Debug)]
186 enum ConstEvalError {
187     NeedsRfc(String),
188 }
189
190 impl fmt::Display for ConstEvalError {
191     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192         use self::ConstEvalError::*;
193         match *self {
194             NeedsRfc(ref msg) => {
195                 write!(
196                     f,
197                     "\"{}\" needs an rfc before being allowed inside constants",
198                     msg
199                 )
200             }
201         }
202     }
203 }
204
205 impl Error for ConstEvalError {
206     fn description(&self) -> &str {
207         use self::ConstEvalError::*;
208         match *self {
209             NeedsRfc(_) => "this feature needs an rfc before being allowed inside constants",
210         }
211     }
212
213     fn cause(&self) -> Option<&dyn Error> {
214         None
215     }
216 }
217
218 // Extra machine state for CTFE, and the Machine instance
219 pub struct CompileTimeInterpreter<'a, 'mir, 'tcx: 'a+'mir> {
220     /// When this value is negative, it indicates the number of interpreter
221     /// steps *until* the loop detector is enabled. When it is positive, it is
222     /// the number of steps after the detector has been enabled modulo the loop
223     /// detector period.
224     pub(super) steps_since_detector_enabled: isize,
225
226     /// Extra state to detect loops.
227     pub(super) loop_detector: snapshot::InfiniteLoopDetector<'a, 'mir, 'tcx>,
228 }
229
230 impl<'a, 'mir, 'tcx> CompileTimeInterpreter<'a, 'mir, 'tcx> {
231     fn new() -> Self {
232         CompileTimeInterpreter {
233             loop_detector: Default::default(),
234             steps_since_detector_enabled: -STEPS_UNTIL_DETECTOR_ENABLED,
235         }
236     }
237 }
238
239 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
240     #[inline(always)]
241     fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
242         where K: Borrow<Q>
243     {
244         FxHashMap::contains_key(self, k)
245     }
246
247     #[inline(always)]
248     fn insert(&mut self, k: K, v: V) -> Option<V>
249     {
250         FxHashMap::insert(self, k, v)
251     }
252
253     #[inline(always)]
254     fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
255         where K: Borrow<Q>
256     {
257         FxHashMap::remove(self, k)
258     }
259
260     #[inline(always)]
261     fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
262         self.iter()
263             .filter_map(move |(k, v)| f(k, &*v))
264             .collect()
265     }
266
267     #[inline(always)]
268     fn get_or<E>(
269         &self,
270         k: K,
271         vacant: impl FnOnce() -> Result<V, E>
272     ) -> Result<&V, E>
273     {
274         match self.get(&k) {
275             Some(v) => Ok(v),
276             None => {
277                 vacant()?;
278                 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
279             }
280         }
281     }
282
283     #[inline(always)]
284     fn get_mut_or<E>(
285         &mut self,
286         k: K,
287         vacant: impl FnOnce() -> Result<V, E>
288     ) -> Result<&mut V, E>
289     {
290         match self.entry(k) {
291             Entry::Occupied(e) => Ok(e.into_mut()),
292             Entry::Vacant(e) => {
293                 let v = vacant()?;
294                 Ok(e.insert(v))
295             }
296         }
297     }
298 }
299
300 type CompileTimeEvalContext<'a, 'mir, 'tcx> =
301     InterpretCx<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>;
302
303 impl interpret::MayLeak for ! {
304     #[inline(always)]
305     fn may_leak(self) -> bool {
306         // `self` is uninhabited
307         self
308     }
309 }
310
311 impl<'a, 'mir, 'tcx> interpret::Machine<'a, 'mir, 'tcx>
312     for CompileTimeInterpreter<'a, 'mir, 'tcx>
313 {
314     type MemoryKinds = !;
315     type PointerTag = ();
316
317     type FrameExtra = ();
318     type MemoryExtra = ();
319     type AllocExtra = ();
320
321     type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>;
322
323     const STATIC_KIND: Option<!> = None; // no copying of statics allowed
324
325     #[inline(always)]
326     fn enforce_validity(_ecx: &InterpretCx<'a, 'mir, 'tcx, Self>) -> bool {
327         false // for now, we don't enforce validity
328     }
329
330     fn find_fn(
331         ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
332         instance: ty::Instance<'tcx>,
333         args: &[OpTy<'tcx>],
334         dest: Option<PlaceTy<'tcx>>,
335         ret: Option<mir::BasicBlock>,
336     ) -> EvalResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
337         debug!("eval_fn_call: {:?}", instance);
338         // Only check non-glue functions
339         if let ty::InstanceDef::Item(def_id) = instance.def {
340             // Execution might have wandered off into other crates, so we cannot to a stability-
341             // sensitive check here.  But we can at least rule out functions that are not const
342             // at all.
343             if !ecx.tcx.is_const_fn_raw(def_id) {
344                 // Some functions we support even if they are non-const -- but avoid testing
345                 // that for const fn!  We certainly do *not* want to actually call the fn
346                 // though, so be sure we return here.
347                 return if ecx.hook_fn(instance, args, dest)? {
348                     ecx.goto_block(ret)?; // fully evaluated and done
349                     Ok(None)
350                 } else {
351                     err!(MachineError(format!("calling non-const function `{}`", instance)))
352                 };
353             }
354         }
355         // This is a const fn. Call it.
356         Ok(Some(match ecx.load_mir(instance.def) {
357             Ok(mir) => mir,
358             Err(err) => {
359                 if let InterpError::NoMirFor(ref path) = err.kind {
360                     return Err(
361                         ConstEvalError::NeedsRfc(format!("calling extern function `{}`", path))
362                             .into(),
363                     );
364                 }
365                 return Err(err);
366             }
367         }))
368     }
369
370     fn call_intrinsic(
371         ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
372         instance: ty::Instance<'tcx>,
373         args: &[OpTy<'tcx>],
374         dest: PlaceTy<'tcx>,
375     ) -> EvalResult<'tcx> {
376         if ecx.emulate_intrinsic(instance, args, dest)? {
377             return Ok(());
378         }
379         // An intrinsic that we do not support
380         let intrinsic_name = &ecx.tcx.item_name(instance.def_id()).as_str()[..];
381         Err(
382             ConstEvalError::NeedsRfc(format!("calling intrinsic `{}`", intrinsic_name)).into()
383         )
384     }
385
386     fn ptr_op(
387         _ecx: &InterpretCx<'a, 'mir, 'tcx, Self>,
388         _bin_op: mir::BinOp,
389         _left: ImmTy<'tcx>,
390         _right: ImmTy<'tcx>,
391     ) -> EvalResult<'tcx, (Scalar, bool)> {
392         Err(
393             ConstEvalError::NeedsRfc("pointer arithmetic or comparison".to_string()).into(),
394         )
395     }
396
397     fn find_foreign_static(
398         _def_id: DefId,
399         _tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
400         _memory_extra: &(),
401     ) -> EvalResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag>>> {
402         err!(ReadForeignStatic)
403     }
404
405     #[inline(always)]
406     fn adjust_static_allocation<'b>(
407         alloc: &'b Allocation,
408         _memory_extra: &(),
409     ) -> Cow<'b, Allocation<Self::PointerTag>> {
410         // We do not use a tag so we can just cheaply forward the reference
411         Cow::Borrowed(alloc)
412     }
413
414     #[inline(always)]
415     fn new_allocation(
416         _size: Size,
417         _extra: &Self::MemoryExtra,
418         _kind: MemoryKind<!>,
419     ) -> (Self::AllocExtra, Self::PointerTag) {
420         ((), ())
421     }
422
423     fn box_alloc(
424         _ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
425         _dest: PlaceTy<'tcx>,
426     ) -> EvalResult<'tcx> {
427         Err(
428             ConstEvalError::NeedsRfc("heap allocations via `box` keyword".to_string()).into(),
429         )
430     }
431
432     fn before_terminator(ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>) -> EvalResult<'tcx> {
433         {
434             let steps = &mut ecx.machine.steps_since_detector_enabled;
435
436             *steps += 1;
437             if *steps < 0 {
438                 return Ok(());
439             }
440
441             *steps %= DETECTOR_SNAPSHOT_PERIOD;
442             if *steps != 0 {
443                 return Ok(());
444             }
445         }
446
447         let span = ecx.frame().span;
448         ecx.machine.loop_detector.observe_and_analyze(
449             *ecx.tcx,
450             span,
451             &ecx.memory,
452             &ecx.stack[..],
453         )
454     }
455
456     #[inline(always)]
457     fn stack_push(
458         _ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
459     ) -> EvalResult<'tcx> {
460         Ok(())
461     }
462
463     /// Called immediately before a stack frame gets popped.
464     #[inline(always)]
465     fn stack_pop(
466         _ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
467         _extra: (),
468     ) -> EvalResult<'tcx> {
469         Ok(())
470     }
471 }
472
473 /// Projects to a field of a (variant of a) const.
474 // this function uses `unwrap` copiously, because an already validated constant must have valid
475 // fields and can thus never fail outside of compiler bugs
476 pub fn const_field<'a, 'tcx>(
477     tcx: TyCtxt<'a, 'tcx, 'tcx>,
478     param_env: ty::ParamEnv<'tcx>,
479     variant: Option<VariantIdx>,
480     field: mir::Field,
481     value: &'tcx ty::Const<'tcx>,
482 ) -> &'tcx ty::Const<'tcx> {
483     trace!("const_field: {:?}, {:?}", field, value);
484     let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
485     // get the operand again
486     let op = ecx.eval_const_to_op(value, None).unwrap();
487     // downcast
488     let down = match variant {
489         None => op,
490         Some(variant) => ecx.operand_downcast(op, variant).unwrap(),
491     };
492     // then project
493     let field = ecx.operand_field(down, field.index() as u64).unwrap();
494     // and finally move back to the const world, always normalizing because
495     // this is not called for statics.
496     op_to_const(&ecx, field)
497 }
498
499 // this function uses `unwrap` copiously, because an already validated constant must have valid
500 // fields and can thus never fail outside of compiler bugs
501 pub fn const_variant_index<'a, 'tcx>(
502     tcx: TyCtxt<'a, 'tcx, 'tcx>,
503     param_env: ty::ParamEnv<'tcx>,
504     val: &'tcx ty::Const<'tcx>,
505 ) -> VariantIdx {
506     trace!("const_variant_index: {:?}", val);
507     let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
508     let op = ecx.eval_const_to_op(val, None).unwrap();
509     ecx.read_discriminant(op).unwrap().1
510 }
511
512 pub fn error_to_const_error<'a, 'mir, 'tcx>(
513     ecx: &InterpretCx<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>,
514     mut error: EvalError<'tcx>
515 ) -> ConstEvalErr<'tcx> {
516     error.print_backtrace();
517     let stacktrace = ecx.generate_stacktrace(None);
518     ConstEvalErr { error: error.kind, stacktrace, span: ecx.tcx.span }
519 }
520
521 fn validate_and_turn_into_const<'a, 'tcx>(
522     tcx: TyCtxt<'a, 'tcx, 'tcx>,
523     constant: RawConst<'tcx>,
524     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
525 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
526     let cid = key.value;
527     let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env);
528     let val = (|| {
529         let mplace = ecx.raw_const_to_mplace(constant)?;
530         let mut ref_tracking = RefTracking::new(mplace);
531         while let Some((mplace, path)) = ref_tracking.todo.pop() {
532             ecx.validate_operand(
533                 mplace.into(),
534                 path,
535                 Some(&mut ref_tracking),
536                 true, // const mode
537             )?;
538         }
539         // Now that we validated, turn this into a proper constant.
540         let def_id = cid.instance.def.def_id();
541         if tcx.is_static(def_id) || cid.promoted.is_some() {
542             Ok(mplace_to_const(&ecx, mplace))
543         } else {
544             Ok(op_to_const(&ecx, mplace.into()))
545         }
546     })();
547
548     val.map_err(|error| {
549         let err = error_to_const_error(&ecx, error);
550         match err.struct_error(ecx.tcx, "it is undefined behavior to use this value") {
551             Ok(mut diag) => {
552                 diag.note("The rules on what exactly is undefined behavior aren't clear, \
553                     so this check might be overzealous. Please open an issue on the rust compiler \
554                     repository if you believe it should not be considered undefined behavior",
555                 );
556                 diag.emit();
557                 ErrorHandled::Reported
558             }
559             Err(err) => err,
560         }
561     })
562 }
563
564 pub fn const_eval_provider<'a, 'tcx>(
565     tcx: TyCtxt<'a, 'tcx, 'tcx>,
566     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
567 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
568     // see comment in const_eval_provider for what we're doing here
569     if key.param_env.reveal == Reveal::All {
570         let mut key = key.clone();
571         key.param_env.reveal = Reveal::UserFacing;
572         match tcx.const_eval(key) {
573             // try again with reveal all as requested
574             Err(ErrorHandled::TooGeneric) => {
575                 // Promoteds should never be "too generic" when getting evaluated.
576                 // They either don't get evaluated, or we are in a monomorphic context
577                 assert!(key.value.promoted.is_none());
578             },
579             // dedupliate calls
580             other => return other,
581         }
582     }
583     tcx.const_eval_raw(key).and_then(|val| {
584         validate_and_turn_into_const(tcx, val, key)
585     })
586 }
587
588 pub fn const_eval_raw_provider<'a, 'tcx>(
589     tcx: TyCtxt<'a, 'tcx, 'tcx>,
590     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
591 ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> {
592     // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
593     // reporting the same error twice here. To resolve this, we check whether we can evaluate the
594     // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
595     // computed. For a large percentage of constants that will already have succeeded. Only
596     // associated constants of generic functions will fail due to not enough monomorphization
597     // information being available.
598
599     // In case we fail in the `UserFacing` variant, we just do the real computation.
600     if key.param_env.reveal == Reveal::All {
601         let mut key = key.clone();
602         key.param_env.reveal = Reveal::UserFacing;
603         match tcx.const_eval_raw(key) {
604             // try again with reveal all as requested
605             Err(ErrorHandled::TooGeneric) => {},
606             // dedupliate calls
607             other => return other,
608         }
609     }
610     if cfg!(debug_assertions) {
611         // Make sure we format the instance even if we do not print it.
612         // This serves as a regression test against an ICE on printing.
613         // The next two lines concatenated contain some discussion:
614         // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
615         // subject/anon_const_instance_printing/near/135980032
616         let instance = key.value.instance.to_string();
617         trace!("const eval: {:?} ({})", key, instance);
618     }
619
620     let cid = key.value;
621     let def_id = cid.instance.def.def_id();
622
623     if def_id.is_local() && tcx.typeck_tables_of(def_id).tainted_by_errors {
624         return Err(ErrorHandled::Reported);
625     }
626
627     let span = tcx.def_span(cid.instance.def_id());
628     let mut ecx = InterpretCx::new(tcx.at(span), key.param_env, CompileTimeInterpreter::new());
629
630     let res = ecx.load_mir(cid.instance.def);
631     res.map(|mir| {
632         if let Some(index) = cid.promoted {
633             &mir.promoted[index]
634         } else {
635             mir
636         }
637     }).and_then(
638         |mir| eval_body_using_ecx(&mut ecx, cid, mir, key.param_env)
639     ).and_then(|place| {
640         Ok(RawConst {
641             alloc_id: place.to_ptr().expect("we allocated this ptr!").alloc_id,
642             ty: place.layout.ty
643         })
644     }).map_err(|error| {
645         let err = error_to_const_error(&ecx, error);
646         // errors in statics are always emitted as fatal errors
647         if tcx.is_static(def_id) {
648             // Ensure that if the above error was either `TooGeneric` or `Reported`
649             // an error must be reported.
650             let reported_err = tcx.sess.track_errors(|| {
651                 err.report_as_error(ecx.tcx,
652                                     "could not evaluate static initializer")
653             });
654             match reported_err {
655                 Ok(v) => {
656                     tcx.sess.delay_span_bug(err.span,
657                                         &format!("static eval failure did not emit an error: {:#?}",
658                                         v));
659                     v
660                 },
661                 Err(ErrorReported) => ErrorHandled::Reported,
662             }
663         } else if def_id.is_local() {
664             // constant defined in this crate, we can figure out a lint level!
665             match tcx.def_kind(def_id) {
666                 // constants never produce a hard error at the definition site. Anything else is
667                 // a backwards compatibility hazard (and will break old versions of winapi for sure)
668                 //
669                 // note that validation may still cause a hard error on this very same constant,
670                 // because any code that existed before validation could not have failed validation
671                 // thus preventing such a hard error from being a backwards compatibility hazard
672                 Some(DefKind::Const) | Some(DefKind::AssocConst) => {
673                     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
674                     err.report_as_lint(
675                         tcx.at(tcx.def_span(def_id)),
676                         "any use of this value will cause an error",
677                         hir_id,
678                         Some(err.span),
679                     )
680                 },
681                 // promoting runtime code is only allowed to error if it references broken constants
682                 // any other kind of error will be reported to the user as a deny-by-default lint
683                 _ => if let Some(p) = cid.promoted {
684                     let span = tcx.optimized_mir(def_id).promoted[p].span;
685                     if let InterpError::ReferencedConstant = err.error {
686                         err.report_as_error(
687                             tcx.at(span),
688                             "evaluation of constant expression failed",
689                         )
690                     } else {
691                         err.report_as_lint(
692                             tcx.at(span),
693                             "reaching this expression at runtime will panic or abort",
694                             tcx.hir().as_local_hir_id(def_id).unwrap(),
695                             Some(err.span),
696                         )
697                     }
698                 // anything else (array lengths, enum initializers, constant patterns) are reported
699                 // as hard errors
700                 } else {
701                     err.report_as_error(
702                         ecx.tcx,
703                         "evaluation of constant value failed",
704                     )
705                 },
706             }
707         } else {
708             // use of broken constant from other crate
709             err.report_as_error(ecx.tcx, "could not evaluate constant")
710         }
711     })
712 }