1 // Not in interpret to make sure we do not use private implementation details
5 use std::borrow::{Borrow, Cow};
7 use std::collections::hash_map::Entry;
9 use rustc::hir::{self, def_id::DefId};
10 use rustc::hir::def::Def;
11 use rustc::mir::interpret::{ConstEvalErr, ErrorHandled};
13 use rustc::ty::{self, TyCtxt, query::TyCtxtAt};
14 use rustc::ty::layout::{self, LayoutOf, VariantIdx};
15 use rustc::ty::subst::Subst;
16 use rustc::traits::Reveal;
17 use rustc_data_structures::fx::FxHashMap;
18 use rustc::util::common::ErrorReported;
20 use syntax::ast::Mutability;
21 use syntax::source_map::{Span, DUMMY_SP};
23 use crate::interpret::{self,
24 PlaceTy, MPlaceTy, MemPlace, OpTy, ImmTy, Operand, Immediate, Scalar, Pointer,
26 EvalResult, EvalError, EvalErrorKind, GlobalId, EvalContext, StackPopCleanup,
27 Allocation, AllocId, MemoryKind,
28 snapshot, RefTracking,
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;
38 /// The `EvalContext` is only meant to be used to do field and index projections into constants for
39 /// `simd_shuffle` and const patterns in match arms.
41 /// The function containing the `match` that is currently being analyzed may have generic bounds
42 /// that inform us about the generic bounds of the constant. E.g., using an associated constant
43 /// of a function's generic parameter will require knowledge about the bounds on the generic
44 /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
45 pub(crate) fn mk_eval_cx<'a, 'mir, 'tcx>(
46 tcx: TyCtxt<'a, 'tcx, 'tcx>,
48 param_env: ty::ParamEnv<'tcx>,
49 ) -> CompileTimeEvalContext<'a, 'mir, 'tcx> {
50 debug!("mk_eval_cx: {:?}", param_env);
51 EvalContext::new(tcx.at(span), param_env, CompileTimeInterpreter::new())
54 pub(crate) fn eval_promoted<'a, 'mir, 'tcx>(
55 tcx: TyCtxt<'a, 'tcx, 'tcx>,
57 mir: &'mir mir::Mir<'tcx>,
58 param_env: ty::ParamEnv<'tcx>,
59 ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
60 let span = tcx.def_span(cid.instance.def_id());
61 let mut ecx = mk_eval_cx(tcx, span, param_env);
62 eval_body_using_ecx(&mut ecx, cid, Some(mir), param_env)
65 // FIXME: These two conversion functions are bad hacks. We should just always use allocations.
66 pub fn op_to_const<'tcx>(
67 ecx: &CompileTimeEvalContext<'_, '_, 'tcx>,
70 ) -> EvalResult<'tcx, ty::Const<'tcx>> {
71 // We do not normalize just any data. Only scalar layout and slices.
72 let normalize = may_normalize
73 && match op.layout.abi {
74 layout::Abi::Scalar(..) => true,
75 layout::Abi::ScalarPair(..) => op.layout.ty.is_slice(),
78 let normalized_op = if normalize {
79 ecx.try_read_immediate(op)?
82 Operand::Indirect(mplace) => Err(mplace),
83 Operand::Immediate(val) => Ok(val)
86 let val = match normalized_op {
87 Err(MemPlace { ptr, align, meta }) => {
88 // extract alloc-offset pair
89 assert!(meta.is_none());
90 let ptr = ptr.to_ptr()?;
91 let alloc = ecx.memory.get(ptr.alloc_id)?;
92 assert!(alloc.align >= align);
93 assert!(alloc.bytes.len() as u64 - ptr.offset.bytes() >= op.layout.size.bytes());
94 let mut alloc = alloc.clone();
96 // FIXME shouldn't it be the case that `mark_static_initialized` has already
97 // interned this? I thought that is the entire point of that `FinishStatic` stuff?
98 let alloc = ecx.tcx.intern_const_alloc(alloc);
99 ConstValue::ByRef(ptr.alloc_id, alloc, ptr.offset)
101 Ok(Immediate::Scalar(x)) =>
102 ConstValue::Scalar(x.not_undef()?),
103 Ok(Immediate::ScalarPair(a, b)) =>
104 ConstValue::Slice(a.not_undef()?, b.to_usize(ecx)?),
106 Ok(ty::Const { val, ty: op.layout.ty })
109 fn eval_body_and_ecx<'a, 'mir, 'tcx>(
110 tcx: TyCtxt<'a, 'tcx, 'tcx>,
112 mir: Option<&'mir mir::Mir<'tcx>>,
113 param_env: ty::ParamEnv<'tcx>,
114 ) -> (EvalResult<'tcx, MPlaceTy<'tcx>>, CompileTimeEvalContext<'a, 'mir, 'tcx>) {
115 // we start out with the best span we have
116 // and try improving it down the road when more information is available
117 let span = tcx.def_span(cid.instance.def_id());
118 let span = mir.map(|mir| mir.span).unwrap_or(span);
119 let mut ecx = EvalContext::new(tcx.at(span), param_env, CompileTimeInterpreter::new());
120 let r = eval_body_using_ecx(&mut ecx, cid, mir, param_env);
124 // Returns a pointer to where the result lives
125 fn eval_body_using_ecx<'mir, 'tcx>(
126 ecx: &mut CompileTimeEvalContext<'_, 'mir, 'tcx>,
128 mir: Option<&'mir mir::Mir<'tcx>>,
129 param_env: ty::ParamEnv<'tcx>,
130 ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
131 debug!("eval_body_using_ecx: {:?}, {:?}", cid, param_env);
132 let tcx = ecx.tcx.tcx;
133 let mut mir = match mir {
135 None => ecx.load_mir(cid.instance.def)?,
137 if let Some(index) = cid.promoted {
138 mir = &mir.promoted[index];
140 let layout = ecx.layout_of(mir.return_ty().subst(tcx, cid.instance.substs))?;
141 assert!(!layout.is_unsized());
142 let ret = ecx.allocate(layout, MemoryKind::Stack);
144 let name = ty::tls::with(|tcx| tcx.item_path_str(cid.instance.def_id()));
145 let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p));
146 trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom);
147 assert!(mir.arg_count == 0);
148 ecx.push_stack_frame(
153 StackPopCleanup::None { cleanup: false },
156 // The main interpreter loop.
160 let internally_mutable = !layout.ty.is_freeze(tcx, param_env, mir.span);
161 let is_static = tcx.is_static(cid.instance.def_id());
162 let mutability = if is_static == Some(hir::Mutability::MutMutable) || internally_mutable {
165 Mutability::Immutable
167 ecx.memory.intern_static(ret.ptr.to_ptr()?.alloc_id, mutability)?;
169 debug!("eval_body_using_ecx done: {:?}", *ret);
173 impl<'tcx> Into<EvalError<'tcx>> for ConstEvalError {
174 fn into(self) -> EvalError<'tcx> {
175 EvalErrorKind::MachineError(self.to_string()).into()
179 #[derive(Clone, Debug)]
180 enum ConstEvalError {
184 impl fmt::Display for ConstEvalError {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 use self::ConstEvalError::*;
188 NeedsRfc(ref msg) => {
191 "\"{}\" needs an rfc before being allowed inside constants",
199 impl Error for ConstEvalError {
200 fn description(&self) -> &str {
201 use self::ConstEvalError::*;
203 NeedsRfc(_) => "this feature needs an rfc before being allowed inside constants",
207 fn cause(&self) -> Option<&dyn Error> {
212 // Extra machine state for CTFE, and the Machine instance
213 pub struct CompileTimeInterpreter<'a, 'mir, 'tcx: 'a+'mir> {
214 /// When this value is negative, it indicates the number of interpreter
215 /// steps *until* the loop detector is enabled. When it is positive, it is
216 /// the number of steps after the detector has been enabled modulo the loop
218 pub(super) steps_since_detector_enabled: isize,
220 /// Extra state to detect loops.
221 pub(super) loop_detector: snapshot::InfiniteLoopDetector<'a, 'mir, 'tcx>,
224 impl<'a, 'mir, 'tcx> CompileTimeInterpreter<'a, 'mir, 'tcx> {
226 CompileTimeInterpreter {
227 loop_detector: Default::default(),
228 steps_since_detector_enabled: -STEPS_UNTIL_DETECTOR_ENABLED,
233 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
235 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
238 FxHashMap::contains_key(self, k)
242 fn insert(&mut self, k: K, v: V) -> Option<V>
244 FxHashMap::insert(self, k, v)
248 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
251 FxHashMap::remove(self, k)
255 fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
257 .filter_map(move |(k, v)| f(k, &*v))
265 vacant: impl FnOnce() -> Result<V, E>
272 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
281 vacant: impl FnOnce() -> Result<V, E>
282 ) -> Result<&mut V, E>
284 match self.entry(k) {
285 Entry::Occupied(e) => Ok(e.into_mut()),
286 Entry::Vacant(e) => {
294 type CompileTimeEvalContext<'a, 'mir, 'tcx> =
295 EvalContext<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>;
297 impl interpret::MayLeak for ! {
299 fn may_leak(self) -> bool {
300 // `self` is uninhabited
305 impl<'a, 'mir, 'tcx> interpret::Machine<'a, 'mir, 'tcx>
306 for CompileTimeInterpreter<'a, 'mir, 'tcx>
308 type MemoryKinds = !;
309 type PointerTag = ();
311 type FrameExtra = ();
312 type MemoryExtra = ();
313 type AllocExtra = ();
315 type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>;
317 const STATIC_KIND: Option<!> = None; // no copying of statics allowed
320 fn enforce_validity(_ecx: &EvalContext<'a, 'mir, 'tcx, Self>) -> bool {
321 false // for now, we don't enforce validity
325 ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
326 instance: ty::Instance<'tcx>,
328 dest: Option<PlaceTy<'tcx>>,
329 ret: Option<mir::BasicBlock>,
330 ) -> EvalResult<'tcx, Option<&'mir mir::Mir<'tcx>>> {
331 debug!("eval_fn_call: {:?}", instance);
332 // Only check non-glue functions
333 if let ty::InstanceDef::Item(def_id) = instance.def {
334 // Execution might have wandered off into other crates, so we cannot to a stability-
335 // sensitive check here. But we can at least rule out functions that are not const
337 if !ecx.tcx.is_const_fn_raw(def_id) {
338 // Some functions we support even if they are non-const -- but avoid testing
339 // that for const fn! We certainly do *not* want to actually call the fn
340 // though, so be sure we return here.
341 return if ecx.hook_fn(instance, args, dest)? {
342 ecx.goto_block(ret)?; // fully evaluated and done
345 err!(MachineError(format!("calling non-const function `{}`", instance)))
349 // This is a const fn. Call it.
350 Ok(Some(match ecx.load_mir(instance.def) {
353 if let EvalErrorKind::NoMirFor(ref path) = err.kind {
355 ConstEvalError::NeedsRfc(format!("calling extern function `{}`", path))
365 ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
366 instance: ty::Instance<'tcx>,
369 ) -> EvalResult<'tcx> {
370 if ecx.emulate_intrinsic(instance, args, dest)? {
373 // An intrinsic that we do not support
374 let intrinsic_name = &ecx.tcx.item_name(instance.def_id()).as_str()[..];
376 ConstEvalError::NeedsRfc(format!("calling intrinsic `{}`", intrinsic_name)).into()
381 _ecx: &EvalContext<'a, 'mir, 'tcx, Self>,
385 ) -> EvalResult<'tcx, (Scalar, bool)> {
387 ConstEvalError::NeedsRfc("pointer arithmetic or comparison".to_string()).into(),
391 fn find_foreign_static(
393 _tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
395 ) -> EvalResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag>>> {
396 err!(ReadForeignStatic)
400 fn adjust_static_allocation<'b>(
401 alloc: &'b Allocation,
403 ) -> Cow<'b, Allocation<Self::PointerTag>> {
404 // We do not use a tag so we can just cheaply forward the reference
409 _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
410 _dest: PlaceTy<'tcx>,
411 ) -> EvalResult<'tcx> {
413 ConstEvalError::NeedsRfc("heap allocations via `box` keyword".to_string()).into(),
417 fn before_terminator(ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>) -> EvalResult<'tcx> {
419 let steps = &mut ecx.machine.steps_since_detector_enabled;
426 *steps %= DETECTOR_SNAPSHOT_PERIOD;
432 let span = ecx.frame().span;
433 ecx.machine.loop_detector.observe_and_analyze(
442 fn tag_new_allocation(
443 _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
445 _kind: MemoryKind<Self::MemoryKinds>,
452 _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
453 ) -> EvalResult<'tcx> {
457 /// Called immediately before a stack frame gets popped.
460 _ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
462 ) -> EvalResult<'tcx> {
467 /// Projects to a field of a (variant of a) const.
468 pub fn const_field<'a, 'tcx>(
469 tcx: TyCtxt<'a, 'tcx, 'tcx>,
470 param_env: ty::ParamEnv<'tcx>,
471 variant: Option<VariantIdx>,
473 value: ty::Const<'tcx>,
474 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
475 trace!("const_field: {:?}, {:?}", field, value);
476 let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
478 // get the operand again
479 let op = ecx.lazy_const_to_op(ty::LazyConst::Evaluated(value), value.ty)?;
481 let down = match variant {
483 Some(variant) => ecx.operand_downcast(op, variant)?
486 let field = ecx.operand_field(down, field.index() as u64)?;
487 // and finally move back to the const world, always normalizing because
488 // this is not called for statics.
489 op_to_const(&ecx, field, true)
491 result.map_err(|error| {
492 let err = error_to_const_error(&ecx, error);
493 err.report_as_error(ecx.tcx, "could not access field of constant");
494 ErrorHandled::Reported
498 pub fn const_variant_index<'a, 'tcx>(
499 tcx: TyCtxt<'a, 'tcx, 'tcx>,
500 param_env: ty::ParamEnv<'tcx>,
501 val: ty::Const<'tcx>,
502 ) -> EvalResult<'tcx, VariantIdx> {
503 trace!("const_variant_index: {:?}", val);
504 let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
505 let op = ecx.lazy_const_to_op(ty::LazyConst::Evaluated(val), val.ty)?;
506 Ok(ecx.read_discriminant(op)?.1)
509 pub fn error_to_const_error<'a, 'mir, 'tcx>(
510 ecx: &EvalContext<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>,
511 mut error: EvalError<'tcx>
512 ) -> ConstEvalErr<'tcx> {
513 error.print_backtrace();
514 let stacktrace = ecx.generate_stacktrace(None);
515 ConstEvalErr { error: error.kind, stacktrace, span: ecx.tcx.span }
518 fn validate_and_turn_into_const<'a, 'tcx>(
519 tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
520 constant: RawConst<'tcx>,
521 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
522 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
524 let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env);
526 let op = ecx.raw_const_to_mplace(constant)?.into();
527 // FIXME: Once the visitor infrastructure landed, change validation to
528 // work directly on `MPlaceTy`.
529 let mut ref_tracking = RefTracking::new(op);
530 while let Some((op, path)) = ref_tracking.todo.pop() {
531 ecx.validate_operand(
534 Some(&mut ref_tracking),
538 // Now that we validated, turn this into a proper constant.
539 let def_id = cid.instance.def.def_id();
540 let normalize = tcx.is_static(def_id).is_none() && cid.promoted.is_none();
541 op_to_const(&ecx, op, normalize)
544 val.map_err(|error| {
545 let err = error_to_const_error(&ecx, error);
546 match err.struct_error(ecx.tcx, "it is undefined behavior to use this value") {
548 diag.note("The rules on what exactly is undefined behavior aren't clear, \
549 so this check might be overzealous. Please open an issue on the rust compiler \
550 repository if you believe it should not be considered undefined behavior",
553 ErrorHandled::Reported
560 pub fn const_eval_provider<'a, 'tcx>(
561 tcx: TyCtxt<'a, 'tcx, 'tcx>,
562 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
563 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
564 // see comment in const_eval_provider for what we're doing here
565 if key.param_env.reveal == Reveal::All {
566 let mut key = key.clone();
567 key.param_env.reveal = Reveal::UserFacing;
568 match tcx.const_eval(key) {
569 // try again with reveal all as requested
570 Err(ErrorHandled::TooGeneric) => {
571 // Promoteds should never be "too generic" when getting evaluated.
572 // They either don't get evaluated, or we are in a monomorphic context
573 assert!(key.value.promoted.is_none());
576 other => return other,
579 tcx.const_eval_raw(key).and_then(|val| {
580 validate_and_turn_into_const(tcx, val, key)
584 pub fn const_eval_raw_provider<'a, 'tcx>(
585 tcx: TyCtxt<'a, 'tcx, 'tcx>,
586 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
587 ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> {
588 // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
589 // reporting the same error twice here. To resolve this, we check whether we can evaluate the
590 // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
591 // computed. For a large percentage of constants that will already have succeeded. Only
592 // associated constants of generic functions will fail due to not enough monomorphization
593 // information being available.
595 // In case we fail in the `UserFacing` variant, we just do the real computation.
596 if key.param_env.reveal == Reveal::All {
597 let mut key = key.clone();
598 key.param_env.reveal = Reveal::UserFacing;
599 match tcx.const_eval_raw(key) {
600 // try again with reveal all as requested
601 Err(ErrorHandled::TooGeneric) => {},
603 other => return other,
606 // the first trace is for replicating an ice
607 // There's no tracking issue, but the next two lines concatenated link to the discussion on
608 // zulip. It's not really possible to test this, because it doesn't show up in diagnostics
610 // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
611 // subject/anon_const_instance_printing/near/135980032
612 trace!("const eval: {}", key.value.instance);
613 trace!("const eval: {:?}", key);
616 let def_id = cid.instance.def.def_id();
618 if let Some(id) = tcx.hir().as_local_node_id(def_id) {
619 let tables = tcx.typeck_tables_of(def_id);
621 // Do match-check before building MIR
622 if let Err(ErrorReported) = tcx.check_match(def_id) {
623 return Err(ErrorHandled::Reported)
626 if let hir::BodyOwnerKind::Const = tcx.hir().body_owner_kind(id) {
627 tcx.mir_const_qualif(def_id);
630 // Do not continue into miri if typeck errors occurred; it will fail horribly
631 if tables.tainted_by_errors {
632 return Err(ErrorHandled::Reported)
636 let (res, ecx) = eval_body_and_ecx(tcx, cid, None, key.param_env);
637 res.and_then(|place| {
639 alloc_id: place.to_ptr().expect("we allocated this ptr!").alloc_id,
643 let err = error_to_const_error(&ecx, error);
644 // errors in statics are always emitted as fatal errors
645 if tcx.is_static(def_id).is_some() {
646 let reported_err = err.report_as_error(ecx.tcx,
647 "could not evaluate static initializer");
648 // Ensure that if the above error was either `TooGeneric` or `Reported`
649 // an error must be reported.
650 if tcx.sess.err_count() == 0 {
651 tcx.sess.delay_span_bug(err.span,
652 &format!("static eval failure did not emit an error: {:#?}",
656 } else if def_id.is_local() {
657 // constant defined in this crate, we can figure out a lint level!
658 match tcx.describe_def(def_id) {
659 // constants never produce a hard error at the definition site. Anything else is
660 // a backwards compatibility hazard (and will break old versions of winapi for sure)
662 // note that validation may still cause a hard error on this very same constant,
663 // because any code that existed before validation could not have failed validation
664 // thus preventing such a hard error from being a backwards compatibility hazard
665 Some(Def::Const(_)) | Some(Def::AssociatedConst(_)) => {
666 let node_id = tcx.hir().as_local_node_id(def_id).unwrap();
668 tcx.at(tcx.def_span(def_id)),
669 "any use of this value will cause an error",
673 // promoting runtime code is only allowed to error if it references broken constants
674 // any other kind of error will be reported to the user as a deny-by-default lint
675 _ => if let Some(p) = cid.promoted {
676 let span = tcx.optimized_mir(def_id).promoted[p].span;
677 if let EvalErrorKind::ReferencedConstant = err.error {
680 "evaluation of constant expression failed",
685 "reaching this expression at runtime will panic or abort",
686 tcx.hir().as_local_node_id(def_id).unwrap(),
689 // anything else (array lengths, enum initializers, constant patterns) are reported
694 "evaluation of constant value failed",
699 // use of broken constant from other crate
700 err.report_as_error(ecx.tcx, "could not evaluate constant")