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