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