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