]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/const_eval.rs
Rollup merge of #67160 - matthewjasper:gat-generics, 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 use std::convert::TryInto;
9
10 use rustc::hir::def::DefKind;
11 use rustc::hir::def_id::DefId;
12 use rustc::mir::interpret::{ConstEvalErr, ErrorHandled, ScalarMaybeUndef};
13 use rustc::mir;
14 use rustc::ty::{self, Ty, TyCtxt, subst::Subst};
15 use rustc::ty::layout::{self, HasTyCtxt, LayoutOf, VariantIdx};
16 use rustc::traits::Reveal;
17 use rustc_data_structures::fx::FxHashMap;
18 use crate::interpret::eval_nullary_intrinsic;
19
20 use syntax::{source_map::{Span, DUMMY_SP}, symbol::Symbol};
21
22 use crate::interpret::{self,
23     PlaceTy, MPlaceTy, OpTy, ImmTy, Immediate, Scalar, Pointer,
24     RawConst, ConstValue, Machine,
25     InterpResult, InterpErrorInfo, GlobalId, InterpCx, StackPopCleanup, AssertMessage,
26     Allocation, AllocId, MemoryKind, Memory,
27     snapshot, RefTracking, intern_const_alloc_recursive,
28 };
29
30 /// Number of steps until the detector even starts doing anything.
31 /// Also, a warning is shown to the user when this number is reached.
32 const STEPS_UNTIL_DETECTOR_ENABLED: isize = 1_000_000;
33 /// The number of steps between loop detector snapshots.
34 /// Should be a power of two for performance reasons.
35 const DETECTOR_SNAPSHOT_PERIOD: isize = 256;
36
37 /// The `InterpCx` is only meant to be used to do field and index projections into constants for
38 /// `simd_shuffle` and const patterns in match arms.
39 ///
40 /// The function containing the `match` that is currently being analyzed may have generic bounds
41 /// that inform us about the generic bounds of the constant. E.g., using an associated constant
42 /// of a function's generic parameter will require knowledge about the bounds on the generic
43 /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
44 fn mk_eval_cx<'mir, 'tcx>(
45     tcx: TyCtxt<'tcx>,
46     span: Span,
47     param_env: ty::ParamEnv<'tcx>,
48 ) -> CompileTimeEvalContext<'mir, 'tcx> {
49     debug!("mk_eval_cx: {:?}", param_env);
50     InterpCx::new(tcx.at(span), param_env, CompileTimeInterpreter::new(), Default::default())
51 }
52
53 fn op_to_const<'tcx>(
54     ecx: &CompileTimeEvalContext<'_, 'tcx>,
55     op: OpTy<'tcx>,
56 ) -> &'tcx ty::Const<'tcx> {
57     // We do not have value optimizations for everything.
58     // Only scalars and slices, since they are very common.
59     // Note that further down we turn scalars of undefined bits back to `ByRef`. These can result
60     // from scalar unions that are initialized with one of their zero sized variants. We could
61     // instead allow `ConstValue::Scalar` to store `ScalarMaybeUndef`, but that would affect all
62     // the usual cases of extracting e.g. a `usize`, without there being a real use case for the
63     // `Undef` situation.
64     let try_as_immediate = match op.layout.abi {
65         layout::Abi::Scalar(..) => true,
66         layout::Abi::ScalarPair(..) => match op.layout.ty.kind {
67             ty::Ref(_, inner, _) => match inner.kind {
68                 ty::Slice(elem) => elem == ecx.tcx.types.u8,
69                 ty::Str => true,
70                 _ => false,
71             },
72             _ => false,
73         },
74         _ => false,
75     };
76     let immediate = if try_as_immediate {
77         Err(ecx.read_immediate(op).expect("normalization works on validated constants"))
78     } else {
79         // It is guaranteed that any non-slice scalar pair is actually ByRef here.
80         // When we come back from raw const eval, we are always by-ref. The only way our op here is
81         // by-val is if we are in const_field, i.e., if this is (a field of) something that we
82         // "tried to make immediate" before. We wouldn't do that for non-slice scalar pairs or
83         // structs containing such.
84         op.try_as_mplace()
85     };
86     let val = match immediate {
87         Ok(mplace) => {
88             let ptr = mplace.ptr.to_ptr().unwrap();
89             let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
90             ConstValue::ByRef { alloc, offset: ptr.offset }
91         },
92         // see comment on `let try_as_immediate` above
93         Err(ImmTy { imm: Immediate::Scalar(x), .. }) => match x {
94             ScalarMaybeUndef::Scalar(s) => ConstValue::Scalar(s),
95             ScalarMaybeUndef::Undef => {
96                 // When coming out of "normal CTFE", we'll always have an `Indirect` operand as
97                 // argument and we will not need this. The only way we can already have an
98                 // `Immediate` is when we are called from `const_field`, and that `Immediate`
99                 // comes from a constant so it can happen have `Undef`, because the indirect
100                 // memory that was read had undefined bytes.
101                 let mplace = op.assert_mem_place();
102                 let ptr = mplace.ptr.to_ptr().unwrap();
103                 let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id);
104                 ConstValue::ByRef { alloc, offset: ptr.offset }
105             },
106         },
107         Err(ImmTy { imm: Immediate::ScalarPair(a, b), .. }) => {
108             let (data, start) = match a.not_undef().unwrap() {
109                 Scalar::Ptr(ptr) => (
110                     ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id),
111                     ptr.offset.bytes(),
112                 ),
113                 Scalar::Raw { .. } => (
114                     ecx.tcx.intern_const_alloc(Allocation::from_byte_aligned_bytes(
115                         b"" as &[u8],
116                     )),
117                     0,
118                 ),
119             };
120             let len = b.to_machine_usize(&ecx.tcx.tcx).unwrap();
121             let start = start.try_into().unwrap();
122             let len: usize = len.try_into().unwrap();
123             ConstValue::Slice {
124                 data,
125                 start,
126                 end: start + len,
127             }
128         },
129     };
130     ecx.tcx.mk_const(ty::Const { val: ty::ConstKind::Value(val), ty: op.layout.ty })
131 }
132
133 // Returns a pointer to where the result lives
134 fn eval_body_using_ecx<'mir, 'tcx>(
135     ecx: &mut CompileTimeEvalContext<'mir, 'tcx>,
136     cid: GlobalId<'tcx>,
137     body: &'mir mir::Body<'tcx>,
138 ) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
139     debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env);
140     let tcx = ecx.tcx.tcx;
141     let layout = ecx.layout_of(body.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
149     // Assert all args (if any) are zero-sized types; `eval_body_using_ecx` doesn't
150     // make sense if the body is expecting nontrivial arguments.
151     // (The alternative would be to use `eval_fn_call` with an args slice.)
152     for arg in body.args_iter() {
153         let decl = body.local_decls.get(arg).expect("arg missing from local_decls");
154         let layout = ecx.layout_of(decl.ty.subst(tcx, cid.instance.substs))?;
155         assert!(layout.is_zst())
156     };
157
158     ecx.push_stack_frame(
159         cid.instance,
160         body.span,
161         body,
162         Some(ret.into()),
163         StackPopCleanup::None { cleanup: false },
164     )?;
165
166     // The main interpreter loop.
167     ecx.run()?;
168
169     // Intern the result
170     intern_const_alloc_recursive(ecx, tcx.static_mutability(cid.instance.def_id()), ret)?;
171
172     debug!("eval_body_using_ecx done: {:?}", *ret);
173     Ok(ret)
174 }
175
176 #[derive(Clone, Debug)]
177 pub enum ConstEvalError {
178     NeedsRfc(String),
179 }
180
181 impl<'tcx> Into<InterpErrorInfo<'tcx>> for ConstEvalError {
182     fn into(self) -> InterpErrorInfo<'tcx> {
183         err_unsup!(Unsupported(self.to_string())).into()
184     }
185 }
186
187 impl fmt::Display for ConstEvalError {
188     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189         use self::ConstEvalError::*;
190         match *self {
191             NeedsRfc(ref msg) => {
192                 write!(
193                     f,
194                     "\"{}\" needs an rfc before being allowed inside constants",
195                     msg
196                 )
197             }
198         }
199     }
200 }
201
202 impl Error for ConstEvalError {
203     fn description(&self) -> &str {
204         use self::ConstEvalError::*;
205         match *self {
206             NeedsRfc(_) => "this feature needs an rfc before being allowed inside constants",
207         }
208     }
209
210     fn cause(&self) -> Option<&dyn Error> {
211         None
212     }
213 }
214
215 // Extra machine state for CTFE, and the Machine instance
216 pub struct CompileTimeInterpreter<'mir, 'tcx> {
217     /// When this value is negative, it indicates the number of interpreter
218     /// steps *until* the loop detector is enabled. When it is positive, it is
219     /// the number of steps after the detector has been enabled modulo the loop
220     /// detector period.
221     pub(super) steps_since_detector_enabled: isize,
222
223     /// Extra state to detect loops.
224     pub(super) loop_detector: snapshot::InfiniteLoopDetector<'mir, 'tcx>,
225 }
226
227 impl<'mir, 'tcx> CompileTimeInterpreter<'mir, 'tcx> {
228     fn new() -> Self {
229         CompileTimeInterpreter {
230             loop_detector: Default::default(),
231             steps_since_detector_enabled: -STEPS_UNTIL_DETECTOR_ENABLED,
232         }
233     }
234 }
235
236 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
237     #[inline(always)]
238     fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
239         where K: Borrow<Q>
240     {
241         FxHashMap::contains_key(self, k)
242     }
243
244     #[inline(always)]
245     fn insert(&mut self, k: K, v: V) -> Option<V>
246     {
247         FxHashMap::insert(self, k, v)
248     }
249
250     #[inline(always)]
251     fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
252         where K: Borrow<Q>
253     {
254         FxHashMap::remove(self, k)
255     }
256
257     #[inline(always)]
258     fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
259         self.iter()
260             .filter_map(move |(k, v)| f(k, &*v))
261             .collect()
262     }
263
264     #[inline(always)]
265     fn get_or<E>(
266         &self,
267         k: K,
268         vacant: impl FnOnce() -> Result<V, E>
269     ) -> Result<&V, E>
270     {
271         match self.get(&k) {
272             Some(v) => Ok(v),
273             None => {
274                 vacant()?;
275                 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
276             }
277         }
278     }
279
280     #[inline(always)]
281     fn get_mut_or<E>(
282         &mut self,
283         k: K,
284         vacant: impl FnOnce() -> Result<V, E>
285     ) -> Result<&mut V, E>
286     {
287         match self.entry(k) {
288             Entry::Occupied(e) => Ok(e.into_mut()),
289             Entry::Vacant(e) => {
290                 let v = vacant()?;
291                 Ok(e.insert(v))
292             }
293         }
294     }
295 }
296
297 crate type CompileTimeEvalContext<'mir, 'tcx> =
298     InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>;
299
300 impl interpret::MayLeak for ! {
301     #[inline(always)]
302     fn may_leak(self) -> bool {
303         // `self` is uninhabited
304         self
305     }
306 }
307
308 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, 'tcx> {
309     type MemoryKinds = !;
310     type PointerTag = ();
311     type ExtraFnVal = !;
312
313     type FrameExtra = ();
314     type MemoryExtra = ();
315     type AllocExtra = ();
316
317     type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>;
318
319     const STATIC_KIND: Option<!> = None; // no copying of statics allowed
320
321     // We do not check for alignment to avoid having to carry an `Align`
322     // in `ConstValue::ByRef`.
323     const CHECK_ALIGN: bool = false;
324
325     #[inline(always)]
326     fn enforce_validity(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
327         false // for now, we don't enforce validity
328     }
329
330     fn find_mir_or_eval_fn(
331         ecx: &mut InterpCx<'mir, 'tcx, Self>,
332         instance: ty::Instance<'tcx>,
333         args: &[OpTy<'tcx>],
334         ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
335         _unwind: Option<mir::BasicBlock> // unwinding is not supported in consts
336     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
337         debug!("find_mir_or_eval_fn: {:?}", instance);
338
339         // Only check non-glue functions
340         if let ty::InstanceDef::Item(def_id) = instance.def {
341             // Execution might have wandered off into other crates, so we cannot do a stability-
342             // sensitive check here.  But we can at least rule out functions that are not const
343             // at all.
344             if ecx.tcx.is_const_fn_raw(def_id) {
345                 // If this function is a `const fn` then as an optimization we can query this
346                 // evaluation immediately.
347                 //
348                 // For the moment we only do this for functions which take no arguments
349                 // (or all arguments are ZSTs) so that we don't memoize too much.
350                 //
351                 // Because `#[track_caller]` adds an implicit non-ZST argument, we also cannot
352                 // perform this optimization on items tagged with it.
353                 let no_implicit_args = !instance.def.requires_caller_location(ecx.tcx());
354                 if args.iter().all(|a| a.layout.is_zst()) && no_implicit_args {
355                     let gid = GlobalId { instance, promoted: None };
356                     ecx.eval_const_fn_call(gid, ret)?;
357                     return Ok(None);
358                 }
359             } else {
360                 // Some functions we support even if they are non-const -- but avoid testing
361                 // that for const fn!  We certainly do *not* want to actually call the fn
362                 // though, so be sure we return here.
363                 return if ecx.hook_panic_fn(instance, args, ret)? {
364                     Ok(None)
365                 } else {
366                     throw_unsup_format!("calling non-const function `{}`", instance)
367                 };
368             }
369         }
370         // This is a const fn. Call it.
371         Ok(Some(match ecx.load_mir(instance.def, None) {
372             Ok(body) => *body,
373             Err(err) => {
374                 if let err_unsup!(NoMirFor(ref path)) = err.kind {
375                     return Err(
376                         ConstEvalError::NeedsRfc(format!("calling extern function `{}`", path))
377                             .into(),
378                     );
379                 }
380                 return Err(err);
381             }
382         }))
383     }
384
385     fn call_extra_fn(
386         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
387         fn_val: !,
388         _args: &[OpTy<'tcx>],
389         _ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
390         _unwind: Option<mir::BasicBlock>
391     ) -> InterpResult<'tcx> {
392         match fn_val {}
393     }
394
395     fn call_intrinsic(
396         ecx: &mut InterpCx<'mir, 'tcx, Self>,
397         span: Span,
398         instance: ty::Instance<'tcx>,
399         args: &[OpTy<'tcx>],
400         ret: Option<(PlaceTy<'tcx>, mir::BasicBlock)>,
401         _unwind: Option<mir::BasicBlock>
402     ) -> InterpResult<'tcx> {
403         if ecx.emulate_intrinsic(span, instance, args, ret)? {
404             return Ok(());
405         }
406         // An intrinsic that we do not support
407         let intrinsic_name = ecx.tcx.item_name(instance.def_id());
408         Err(
409             ConstEvalError::NeedsRfc(format!("calling intrinsic `{}`", intrinsic_name)).into()
410         )
411     }
412
413     fn assert_panic(
414         ecx: &mut InterpCx<'mir, 'tcx, Self>,
415         _span: Span,
416         msg: &AssertMessage<'tcx>,
417         _unwind: Option<mir::BasicBlock>,
418     ) -> InterpResult<'tcx> {
419         use rustc::mir::interpret::PanicInfo::*;
420         Err(match msg {
421             BoundsCheck { ref len, ref index } => {
422                 let len = ecx
423                     .read_immediate(ecx.eval_operand(len, None)?)
424                     .expect("can't eval len")
425                     .to_scalar()?
426                     .to_machine_usize(&*ecx)?;
427                 let index = ecx
428                     .read_immediate(ecx.eval_operand(index, None)?)
429                     .expect("can't eval index")
430                     .to_scalar()?
431                     .to_machine_usize(&*ecx)?;
432                 err_panic!(BoundsCheck { len, index })
433             }
434             Overflow(op) => err_panic!(Overflow(*op)),
435             OverflowNeg => err_panic!(OverflowNeg),
436             DivisionByZero => err_panic!(DivisionByZero),
437             RemainderByZero => err_panic!(RemainderByZero),
438             ResumedAfterReturn(generator_kind)
439                 => err_panic!(ResumedAfterReturn(*generator_kind)),
440             ResumedAfterPanic(generator_kind)
441                 => err_panic!(ResumedAfterPanic(*generator_kind)),
442             Panic { .. } => bug!("`Panic` variant cannot occur in MIR"),
443         }
444         .into())
445     }
446
447     fn ptr_to_int(
448         _mem: &Memory<'mir, 'tcx, Self>,
449         _ptr: Pointer,
450     ) -> InterpResult<'tcx, u64> {
451         Err(
452             ConstEvalError::NeedsRfc("pointer-to-integer cast".to_string()).into(),
453         )
454     }
455
456     fn binary_ptr_op(
457         _ecx: &InterpCx<'mir, 'tcx, Self>,
458         _bin_op: mir::BinOp,
459         _left: ImmTy<'tcx>,
460         _right: ImmTy<'tcx>,
461     ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
462         Err(
463             ConstEvalError::NeedsRfc("pointer arithmetic or comparison".to_string()).into(),
464         )
465     }
466
467     fn find_foreign_static(
468         _tcx: TyCtxt<'tcx>,
469         _def_id: DefId,
470     ) -> InterpResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag>>> {
471         throw_unsup!(ReadForeignStatic)
472     }
473
474     #[inline(always)]
475     fn init_allocation_extra<'b>(
476         _memory_extra: &(),
477         _id: AllocId,
478         alloc: Cow<'b, Allocation>,
479         _kind: Option<MemoryKind<!>>,
480     ) -> (Cow<'b, Allocation<Self::PointerTag>>, Self::PointerTag) {
481         // We do not use a tag so we can just cheaply forward the allocation
482         (alloc, ())
483     }
484
485     #[inline(always)]
486     fn tag_static_base_pointer(
487         _memory_extra: &(),
488         _id: AllocId,
489     ) -> Self::PointerTag {
490         ()
491     }
492
493     fn box_alloc(
494         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
495         _dest: PlaceTy<'tcx>,
496     ) -> InterpResult<'tcx> {
497         Err(
498             ConstEvalError::NeedsRfc("heap allocations via `box` keyword".to_string()).into(),
499         )
500     }
501
502     fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
503         {
504             let steps = &mut ecx.machine.steps_since_detector_enabled;
505
506             *steps += 1;
507             if *steps < 0 {
508                 return Ok(());
509             }
510
511             *steps %= DETECTOR_SNAPSHOT_PERIOD;
512             if *steps != 0 {
513                 return Ok(());
514             }
515         }
516
517         let span = ecx.frame().span;
518         ecx.machine.loop_detector.observe_and_analyze(
519             *ecx.tcx,
520             span,
521             &ecx.memory,
522             &ecx.stack[..],
523         )
524     }
525
526     #[inline(always)]
527     fn stack_push(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
528         Ok(())
529     }
530 }
531
532 /// Extracts a field of a (variant of a) const.
533 // this function uses `unwrap` copiously, because an already validated constant must have valid
534 // fields and can thus never fail outside of compiler bugs
535 pub fn const_field<'tcx>(
536     tcx: TyCtxt<'tcx>,
537     param_env: ty::ParamEnv<'tcx>,
538     variant: Option<VariantIdx>,
539     field: mir::Field,
540     value: &'tcx ty::Const<'tcx>,
541 ) -> &'tcx ty::Const<'tcx> {
542     trace!("const_field: {:?}, {:?}", field, value);
543     let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
544     // get the operand again
545     let op = ecx.eval_const_to_op(value, None).unwrap();
546     // downcast
547     let down = match variant {
548         None => op,
549         Some(variant) => ecx.operand_downcast(op, variant).unwrap(),
550     };
551     // then project
552     let field = ecx.operand_field(down, field.index() as u64).unwrap();
553     // and finally move back to the const world, always normalizing because
554     // this is not called for statics.
555     op_to_const(&ecx, field)
556 }
557
558 pub fn const_caller_location<'tcx>(
559     tcx: TyCtxt<'tcx>,
560     (file, line, col): (Symbol, u32, u32),
561 ) -> &'tcx ty::Const<'tcx> {
562     trace!("const_caller_location: {}:{}:{}", file, line, col);
563     let mut ecx = mk_eval_cx(tcx, DUMMY_SP, ty::ParamEnv::reveal_all());
564
565     let loc_ty = tcx.caller_location_ty();
566     let loc_place = ecx.alloc_caller_location(file, line, col);
567     intern_const_alloc_recursive(&mut ecx, None, loc_place).unwrap();
568     let loc_const = ty::Const {
569         ty: loc_ty,
570         val: ty::ConstKind::Value(ConstValue::Scalar(loc_place.ptr.into())),
571     };
572
573     tcx.mk_const(loc_const)
574 }
575
576 // this function uses `unwrap` copiously, because an already validated constant must have valid
577 // fields and can thus never fail outside of compiler bugs
578 pub fn const_variant_index<'tcx>(
579     tcx: TyCtxt<'tcx>,
580     param_env: ty::ParamEnv<'tcx>,
581     val: &'tcx ty::Const<'tcx>,
582 ) -> VariantIdx {
583     trace!("const_variant_index: {:?}", val);
584     let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
585     let op = ecx.eval_const_to_op(val, None).unwrap();
586     ecx.read_discriminant(op).unwrap().1
587 }
588
589 /// Turn an interpreter error into something to report to the user.
590 /// As a side-effect, if RUSTC_CTFE_BACKTRACE is set, this prints the backtrace.
591 /// Should be called only if the error is actually going to to be reported!
592 pub fn error_to_const_error<'mir, 'tcx, M: Machine<'mir, 'tcx>>(
593     ecx: &InterpCx<'mir, 'tcx, M>,
594     mut error: InterpErrorInfo<'tcx>,
595 ) -> ConstEvalErr<'tcx> {
596     error.print_backtrace();
597     let stacktrace = ecx.generate_stacktrace(None);
598     ConstEvalErr { error: error.kind, stacktrace, span: ecx.tcx.span }
599 }
600
601 pub fn note_on_undefined_behavior_error() -> &'static str {
602     "The rules on what exactly is undefined behavior aren't clear, \
603      so this check might be overzealous. Please open an issue on the rustc \
604      repository if you believe it should not be considered undefined behavior."
605 }
606
607 fn validate_and_turn_into_const<'tcx>(
608     tcx: TyCtxt<'tcx>,
609     constant: RawConst<'tcx>,
610     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
611 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
612     let cid = key.value;
613     let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env);
614     let val = (|| {
615         let mplace = ecx.raw_const_to_mplace(constant)?;
616         let mut ref_tracking = RefTracking::new(mplace);
617         while let Some((mplace, path)) = ref_tracking.todo.pop() {
618             ecx.validate_operand(
619                 mplace.into(),
620                 path,
621                 Some(&mut ref_tracking),
622             )?;
623         }
624         // Now that we validated, turn this into a proper constant.
625         // Statics/promoteds are always `ByRef`, for the rest `op_to_const` decides
626         // whether they become immediates.
627         let def_id = cid.instance.def.def_id();
628         if tcx.is_static(def_id) || cid.promoted.is_some() {
629             let ptr = mplace.ptr.to_ptr()?;
630             Ok(tcx.mk_const(ty::Const {
631                 val: ty::ConstKind::Value(ConstValue::ByRef {
632                     alloc: ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id),
633                     offset: ptr.offset,
634                 }),
635                 ty: mplace.layout.ty,
636             }))
637         } else {
638             Ok(op_to_const(&ecx, mplace.into()))
639         }
640     })();
641
642     val.map_err(|error| {
643         let err = error_to_const_error(&ecx, error);
644         match err.struct_error(ecx.tcx, "it is undefined behavior to use this value") {
645             Ok(mut diag) => {
646                 diag.note(note_on_undefined_behavior_error());
647                 diag.emit();
648                 ErrorHandled::Reported
649             }
650             Err(err) => err,
651         }
652     })
653 }
654
655 pub fn const_eval_provider<'tcx>(
656     tcx: TyCtxt<'tcx>,
657     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
658 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
659     // see comment in const_eval_raw_provider for what we're doing here
660     if key.param_env.reveal == Reveal::All {
661         let mut key = key.clone();
662         key.param_env.reveal = Reveal::UserFacing;
663         match tcx.const_eval(key) {
664             // try again with reveal all as requested
665             Err(ErrorHandled::TooGeneric) => {
666                 // Promoteds should never be "too generic" when getting evaluated.
667                 // They either don't get evaluated, or we are in a monomorphic context
668                 assert!(key.value.promoted.is_none());
669             },
670             // dedupliate calls
671             other => return other,
672         }
673     }
674
675     // We call `const_eval` for zero arg intrinsics, too, in order to cache their value.
676     // Catch such calls and evaluate them instead of trying to load a constant's MIR.
677     if let ty::InstanceDef::Intrinsic(def_id) = key.value.instance.def {
678         let ty = key.value.instance.ty(tcx);
679         let substs = match ty.kind {
680             ty::FnDef(_, substs) => substs,
681             _ => bug!("intrinsic with type {:?}", ty),
682         };
683         return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs)
684             .map_err(|error| {
685                 let span = tcx.def_span(def_id);
686                 let error = ConstEvalErr { error: error.kind, stacktrace: vec![], span };
687                 error.report_as_error(tcx.at(span), "could not evaluate nullary intrinsic")
688             })
689     }
690
691     tcx.const_eval_raw(key).and_then(|val| {
692         validate_and_turn_into_const(tcx, val, key)
693     })
694 }
695
696 pub fn const_eval_raw_provider<'tcx>(
697     tcx: TyCtxt<'tcx>,
698     key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
699 ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> {
700     // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
701     // reporting the same error twice here. To resolve this, we check whether we can evaluate the
702     // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
703     // computed. For a large percentage of constants that will already have succeeded. Only
704     // associated constants of generic functions will fail due to not enough monomorphization
705     // information being available.
706
707     // In case we fail in the `UserFacing` variant, we just do the real computation.
708     if key.param_env.reveal == Reveal::All {
709         let mut key = key.clone();
710         key.param_env.reveal = Reveal::UserFacing;
711         match tcx.const_eval_raw(key) {
712             // try again with reveal all as requested
713             Err(ErrorHandled::TooGeneric) => {},
714             // dedupliate calls
715             other => return other,
716         }
717     }
718     if cfg!(debug_assertions) {
719         // Make sure we format the instance even if we do not print it.
720         // This serves as a regression test against an ICE on printing.
721         // The next two lines concatenated contain some discussion:
722         // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
723         // subject/anon_const_instance_printing/near/135980032
724         let instance = key.value.instance.to_string();
725         trace!("const eval: {:?} ({})", key, instance);
726     }
727
728     let cid = key.value;
729     let def_id = cid.instance.def.def_id();
730
731     if def_id.is_local() && tcx.typeck_tables_of(def_id).tainted_by_errors {
732         return Err(ErrorHandled::Reported);
733     }
734
735     let span = tcx.def_span(cid.instance.def_id());
736     let mut ecx = InterpCx::new(
737         tcx.at(span),
738         key.param_env,
739         CompileTimeInterpreter::new(),
740         Default::default()
741     );
742
743     let res = ecx.load_mir(cid.instance.def, cid.promoted);
744     res.and_then(
745         |body| eval_body_using_ecx(&mut ecx, cid, *body)
746     ).and_then(|place| {
747         Ok(RawConst {
748             alloc_id: place.ptr.assert_ptr().alloc_id,
749             ty: place.layout.ty
750         })
751     }).map_err(|error| {
752         let err = error_to_const_error(&ecx, error);
753         // errors in statics are always emitted as fatal errors
754         if tcx.is_static(def_id) {
755             // Ensure that if the above error was either `TooGeneric` or `Reported`
756             // an error must be reported.
757             let v = err.report_as_error(ecx.tcx, "could not evaluate static initializer");
758             tcx.sess.delay_span_bug(
759                 err.span,
760                 &format!("static eval failure did not emit an error: {:#?}", v)
761             );
762             v
763         } else if def_id.is_local() {
764             // constant defined in this crate, we can figure out a lint level!
765             match tcx.def_kind(def_id) {
766                 // constants never produce a hard error at the definition site. Anything else is
767                 // a backwards compatibility hazard (and will break old versions of winapi for sure)
768                 //
769                 // note that validation may still cause a hard error on this very same constant,
770                 // because any code that existed before validation could not have failed validation
771                 // thus preventing such a hard error from being a backwards compatibility hazard
772                 Some(DefKind::Const) | Some(DefKind::AssocConst) => {
773                     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
774                     err.report_as_lint(
775                         tcx.at(tcx.def_span(def_id)),
776                         "any use of this value will cause an error",
777                         hir_id,
778                         Some(err.span),
779                     )
780                 },
781                 // promoting runtime code is only allowed to error if it references broken constants
782                 // any other kind of error will be reported to the user as a deny-by-default lint
783                 _ => if let Some(p) = cid.promoted {
784                     let span = tcx.promoted_mir(def_id)[p].span;
785                     if let err_inval!(ReferencedConstant) = err.error {
786                         err.report_as_error(
787                             tcx.at(span),
788                             "evaluation of constant expression failed",
789                         )
790                     } else {
791                         err.report_as_lint(
792                             tcx.at(span),
793                             "reaching this expression at runtime will panic or abort",
794                             tcx.hir().as_local_hir_id(def_id).unwrap(),
795                             Some(err.span),
796                         )
797                     }
798                 // anything else (array lengths, enum initializers, constant patterns) are reported
799                 // as hard errors
800                 } else {
801                     err.report_as_error(
802                         ecx.tcx,
803                         "evaluation of constant value failed",
804                     )
805                 },
806             }
807         } else {
808             // use of broken constant from other crate
809             err.report_as_error(ecx.tcx, "could not evaluate constant")
810         }
811     })
812 }