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