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;
8 use std::convert::TryInto;
10 use rustc::hir::def::DefKind;
11 use rustc::hir::def_id::DefId;
12 use rustc::mir::interpret::{ConstEvalErr, ErrorHandled};
14 use rustc::ty::{self, TyCtxt, query::TyCtxtAt};
15 use rustc::ty::layout::{self, LayoutOf, VariantIdx, Size};
16 use rustc::ty::subst::Subst;
17 use rustc::traits::Reveal;
18 use rustc::util::common::ErrorReported;
19 use rustc_data_structures::fx::FxHashMap;
21 use syntax::ast::Mutability;
22 use syntax::source_map::{Span, DUMMY_SP};
24 use crate::interpret::{self,
25 PlaceTy, MPlaceTy, MemPlace, OpTy, ImmTy, Immediate, Scalar,
27 EvalResult, EvalError, InterpError, GlobalId, InterpretCx, StackPopCleanup,
28 Allocation, AllocId, MemoryKind,
29 snapshot, RefTracking,
32 /// Number of steps until the detector even starts doing anything.
33 /// Also, a warning is shown to the user when this number is reached.
34 const STEPS_UNTIL_DETECTOR_ENABLED: isize = 1_000_000;
35 /// The number of steps between loop detector snapshots.
36 /// Should be a power of two for performance reasons.
37 const DETECTOR_SNAPSHOT_PERIOD: isize = 256;
39 /// The `InterpretCx` is only meant to be used to do field and index projections into constants for
40 /// `simd_shuffle` and const patterns in match arms.
42 /// The function containing the `match` that is currently being analyzed may have generic bounds
43 /// that inform us about the generic bounds of the constant. E.g., using an associated constant
44 /// of a function's generic parameter will require knowledge about the bounds on the generic
45 /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument.
46 pub(crate) fn mk_eval_cx<'a, 'mir, 'tcx>(
47 tcx: TyCtxt<'a, 'tcx, 'tcx>,
49 param_env: ty::ParamEnv<'tcx>,
50 ) -> CompileTimeEvalContext<'a, 'mir, 'tcx> {
51 debug!("mk_eval_cx: {:?}", param_env);
52 InterpretCx::new(tcx.at(span), param_env, CompileTimeInterpreter::new())
55 pub(crate) fn eval_promoted<'a, 'mir, 'tcx>(
56 tcx: TyCtxt<'a, 'tcx, 'tcx>,
58 mir: &'mir mir::Mir<'tcx>,
59 param_env: ty::ParamEnv<'tcx>,
60 ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
61 let span = tcx.def_span(cid.instance.def_id());
62 let mut ecx = mk_eval_cx(tcx, span, param_env);
63 eval_body_using_ecx(&mut ecx, cid, mir, param_env)
66 fn mplace_to_const<'tcx>(
67 ecx: &CompileTimeEvalContext<'_, '_, 'tcx>,
68 mplace: MPlaceTy<'tcx>,
69 ) -> &'tcx ty::Const<'tcx> {
70 let MemPlace { ptr, align, meta } = *mplace;
71 // extract alloc-offset pair
72 assert!(meta.is_none());
73 let ptr = ptr.to_ptr().unwrap();
74 let alloc = ecx.memory.get(ptr.alloc_id).unwrap();
75 assert!(alloc.align >= align);
76 assert!(alloc.bytes.len() as u64 - ptr.offset.bytes() >= mplace.layout.size.bytes());
77 let mut alloc = alloc.clone();
79 // FIXME shouldn't it be the case that `mark_static_initialized` has already
80 // interned this? I thought that is the entire point of that `FinishStatic` stuff?
81 let alloc = ecx.tcx.intern_const_alloc(alloc);
82 let val = ConstValue::ByRef(ptr, alloc);
83 ecx.tcx.mk_const(ty::Const { val, ty: mplace.layout.ty })
87 ecx: &CompileTimeEvalContext<'_, '_, 'tcx>,
89 ) -> &'tcx ty::Const<'tcx> {
90 // We do not normalize just any data. Only non-union scalars and slices.
91 let normalize = match op.layout.abi {
92 layout::Abi::Scalar(..) => op.layout.ty.ty_adt_def().map_or(true, |adt| !adt.is_union()),
93 layout::Abi::ScalarPair(..) => match op.layout.ty.sty {
94 ty::Ref(_, inner, _) => match inner.sty {
95 ty::Slice(elem) => elem == ecx.tcx.types.u8,
103 let normalized_op = if normalize {
104 Err(*ecx.read_immediate(op).expect("normalization works on validated constants"))
108 let val = match normalized_op {
109 Ok(mplace) => return mplace_to_const(ecx, mplace),
110 Err(Immediate::Scalar(x)) =>
111 ConstValue::Scalar(x.not_undef().unwrap()),
112 Err(Immediate::ScalarPair(a, b)) => {
113 let (data, start) = match a.not_undef().unwrap() {
114 Scalar::Ptr(ptr) => (
115 ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id),
118 Scalar::Bits { .. } => (
119 ecx.tcx.intern_const_alloc(Allocation::from_byte_aligned_bytes(b"", ())),
123 let len = b.to_usize(&ecx.tcx.tcx).unwrap();
124 let start = start.try_into().unwrap();
125 let len: usize = len.try_into().unwrap();
133 ecx.tcx.mk_const(ty::Const { val, ty: op.layout.ty })
136 // Returns a pointer to where the result lives
137 fn eval_body_using_ecx<'mir, 'tcx>(
138 ecx: &mut CompileTimeEvalContext<'_, 'mir, 'tcx>,
140 mir: &'mir mir::Mir<'tcx>,
141 param_env: ty::ParamEnv<'tcx>,
142 ) -> EvalResult<'tcx, MPlaceTy<'tcx>> {
143 debug!("eval_body_using_ecx: {:?}, {:?}", cid, param_env);
144 let tcx = ecx.tcx.tcx;
145 let layout = ecx.layout_of(mir.return_ty().subst(tcx, cid.instance.substs))?;
146 assert!(!layout.is_unsized());
147 let ret = ecx.allocate(layout, MemoryKind::Stack);
149 let name = ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id()));
150 let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p));
151 trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom);
152 assert!(mir.arg_count == 0);
153 ecx.push_stack_frame(
158 StackPopCleanup::None { cleanup: false },
161 // The main interpreter loop.
165 let mutability = if tcx.is_mutable_static(cid.instance.def_id()) ||
166 !layout.ty.is_freeze(tcx, param_env, mir.span) {
169 Mutability::Immutable
171 ecx.memory.intern_static(ret.ptr.to_ptr()?.alloc_id, mutability)?;
173 debug!("eval_body_using_ecx done: {:?}", *ret);
177 impl<'tcx> Into<EvalError<'tcx>> for ConstEvalError {
178 fn into(self) -> EvalError<'tcx> {
179 InterpError::MachineError(self.to_string()).into()
183 #[derive(Clone, Debug)]
184 enum ConstEvalError {
188 impl fmt::Display for ConstEvalError {
189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190 use self::ConstEvalError::*;
192 NeedsRfc(ref msg) => {
195 "\"{}\" needs an rfc before being allowed inside constants",
203 impl Error for ConstEvalError {
204 fn description(&self) -> &str {
205 use self::ConstEvalError::*;
207 NeedsRfc(_) => "this feature needs an rfc before being allowed inside constants",
211 fn cause(&self) -> Option<&dyn Error> {
216 // Extra machine state for CTFE, and the Machine instance
217 pub struct CompileTimeInterpreter<'a, 'mir, 'tcx: 'a+'mir> {
218 /// When this value is negative, it indicates the number of interpreter
219 /// steps *until* the loop detector is enabled. When it is positive, it is
220 /// the number of steps after the detector has been enabled modulo the loop
222 pub(super) steps_since_detector_enabled: isize,
224 /// Extra state to detect loops.
225 pub(super) loop_detector: snapshot::InfiniteLoopDetector<'a, 'mir, 'tcx>,
228 impl<'a, 'mir, 'tcx> CompileTimeInterpreter<'a, 'mir, 'tcx> {
230 CompileTimeInterpreter {
231 loop_detector: Default::default(),
232 steps_since_detector_enabled: -STEPS_UNTIL_DETECTOR_ENABLED,
237 impl<K: Hash + Eq, V> interpret::AllocMap<K, V> for FxHashMap<K, V> {
239 fn contains_key<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> bool
242 FxHashMap::contains_key(self, k)
246 fn insert(&mut self, k: K, v: V) -> Option<V>
248 FxHashMap::insert(self, k, v)
252 fn remove<Q: ?Sized + Hash + Eq>(&mut self, k: &Q) -> Option<V>
255 FxHashMap::remove(self, k)
259 fn filter_map_collect<T>(&self, mut f: impl FnMut(&K, &V) -> Option<T>) -> Vec<T> {
261 .filter_map(move |(k, v)| f(k, &*v))
269 vacant: impl FnOnce() -> Result<V, E>
276 bug!("The CTFE machine shouldn't ever need to extend the alloc_map when reading")
285 vacant: impl FnOnce() -> Result<V, E>
286 ) -> Result<&mut V, E>
288 match self.entry(k) {
289 Entry::Occupied(e) => Ok(e.into_mut()),
290 Entry::Vacant(e) => {
298 type CompileTimeEvalContext<'a, 'mir, 'tcx> =
299 InterpretCx<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>;
301 impl interpret::MayLeak for ! {
303 fn may_leak(self) -> bool {
304 // `self` is uninhabited
309 impl<'a, 'mir, 'tcx> interpret::Machine<'a, 'mir, 'tcx>
310 for CompileTimeInterpreter<'a, 'mir, 'tcx>
312 type MemoryKinds = !;
313 type PointerTag = ();
315 type FrameExtra = ();
316 type MemoryExtra = ();
317 type AllocExtra = ();
319 type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>;
321 const STATIC_KIND: Option<!> = None; // no copying of statics allowed
324 fn enforce_validity(_ecx: &InterpretCx<'a, 'mir, 'tcx, Self>) -> bool {
325 false // for now, we don't enforce validity
329 ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
330 instance: ty::Instance<'tcx>,
332 dest: Option<PlaceTy<'tcx>>,
333 ret: Option<mir::BasicBlock>,
334 ) -> EvalResult<'tcx, Option<&'mir mir::Mir<'tcx>>> {
335 debug!("eval_fn_call: {:?}", instance);
336 // Only check non-glue functions
337 if let ty::InstanceDef::Item(def_id) = instance.def {
338 // Execution might have wandered off into other crates, so we cannot to a stability-
339 // sensitive check here. But we can at least rule out functions that are not const
341 if !ecx.tcx.is_const_fn_raw(def_id) {
342 // Some functions we support even if they are non-const -- but avoid testing
343 // that for const fn! We certainly do *not* want to actually call the fn
344 // though, so be sure we return here.
345 return if ecx.hook_fn(instance, args, dest)? {
346 ecx.goto_block(ret)?; // fully evaluated and done
349 err!(MachineError(format!("calling non-const function `{}`", instance)))
353 // This is a const fn. Call it.
354 Ok(Some(match ecx.load_mir(instance.def) {
357 if let InterpError::NoMirFor(ref path) = err.kind {
359 ConstEvalError::NeedsRfc(format!("calling extern function `{}`", path))
369 ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
370 instance: ty::Instance<'tcx>,
373 ) -> EvalResult<'tcx> {
374 if ecx.emulate_intrinsic(instance, args, dest)? {
377 // An intrinsic that we do not support
378 let intrinsic_name = &ecx.tcx.item_name(instance.def_id()).as_str()[..];
380 ConstEvalError::NeedsRfc(format!("calling intrinsic `{}`", intrinsic_name)).into()
385 _ecx: &InterpretCx<'a, 'mir, 'tcx, Self>,
389 ) -> EvalResult<'tcx, (Scalar, bool)> {
391 ConstEvalError::NeedsRfc("pointer arithmetic or comparison".to_string()).into(),
395 fn find_foreign_static(
397 _tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
399 ) -> EvalResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag>>> {
400 err!(ReadForeignStatic)
404 fn adjust_static_allocation<'b>(
405 alloc: &'b Allocation,
407 ) -> Cow<'b, Allocation<Self::PointerTag>> {
408 // We do not use a tag so we can just cheaply forward the reference
415 _extra: &Self::MemoryExtra,
416 _kind: MemoryKind<!>,
417 ) -> (Self::AllocExtra, Self::PointerTag) {
422 _ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
423 _dest: PlaceTy<'tcx>,
424 ) -> EvalResult<'tcx> {
426 ConstEvalError::NeedsRfc("heap allocations via `box` keyword".to_string()).into(),
430 fn before_terminator(ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>) -> EvalResult<'tcx> {
432 let steps = &mut ecx.machine.steps_since_detector_enabled;
439 *steps %= DETECTOR_SNAPSHOT_PERIOD;
445 let span = ecx.frame().span;
446 ecx.machine.loop_detector.observe_and_analyze(
456 _ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
457 ) -> EvalResult<'tcx> {
461 /// Called immediately before a stack frame gets popped.
464 _ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
466 ) -> EvalResult<'tcx> {
471 /// Projects to a field of a (variant of a) const.
472 // this function uses `unwrap` copiously, because an already validated constant must have valid
473 // fields and can thus never fail outside of compiler bugs
474 pub fn const_field<'a, 'tcx>(
475 tcx: TyCtxt<'a, 'tcx, 'tcx>,
476 param_env: ty::ParamEnv<'tcx>,
477 variant: Option<VariantIdx>,
479 value: &'tcx ty::Const<'tcx>,
480 ) -> &'tcx ty::Const<'tcx> {
481 trace!("const_field: {:?}, {:?}", field, value);
482 let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
483 // get the operand again
484 let op = ecx.eval_const_to_op(value, None).unwrap();
486 let down = match variant {
488 Some(variant) => ecx.operand_downcast(op, variant).unwrap(),
491 let field = ecx.operand_field(down, field.index() as u64).unwrap();
492 // and finally move back to the const world, always normalizing because
493 // this is not called for statics.
494 op_to_const(&ecx, field)
497 // this function uses `unwrap` copiously, because an already validated constant must have valid
498 // fields and can thus never fail outside of compiler bugs
499 pub fn const_variant_index<'a, 'tcx>(
500 tcx: TyCtxt<'a, 'tcx, 'tcx>,
501 param_env: ty::ParamEnv<'tcx>,
502 val: &'tcx ty::Const<'tcx>,
504 trace!("const_variant_index: {:?}", val);
505 let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env);
506 let op = ecx.eval_const_to_op(val, None).unwrap();
507 ecx.read_discriminant(op).unwrap().1
510 pub fn error_to_const_error<'a, 'mir, 'tcx>(
511 ecx: &InterpretCx<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>,
512 mut error: EvalError<'tcx>
513 ) -> ConstEvalErr<'tcx> {
514 error.print_backtrace();
515 let stacktrace = ecx.generate_stacktrace(None);
516 ConstEvalErr { error: error.kind, stacktrace, span: ecx.tcx.span }
519 fn validate_and_turn_into_const<'a, 'tcx>(
520 tcx: TyCtxt<'a, 'tcx, 'tcx>,
521 constant: RawConst<'tcx>,
522 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
523 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
525 let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env);
527 let mplace = ecx.raw_const_to_mplace(constant)?;
528 let mut ref_tracking = RefTracking::new(mplace);
529 while let Some((mplace, path)) = ref_tracking.todo.pop() {
530 ecx.validate_operand(
533 Some(&mut ref_tracking),
537 // Now that we validated, turn this into a proper constant.
538 let def_id = cid.instance.def.def_id();
539 if tcx.is_static(def_id) || cid.promoted.is_some() {
540 Ok(mplace_to_const(&ecx, mplace))
542 Ok(op_to_const(&ecx, mplace.into()))
546 val.map_err(|error| {
547 let err = error_to_const_error(&ecx, error);
548 match err.struct_error(ecx.tcx, "it is undefined behavior to use this value") {
550 diag.note("The rules on what exactly is undefined behavior aren't clear, \
551 so this check might be overzealous. Please open an issue on the rust compiler \
552 repository if you believe it should not be considered undefined behavior",
555 ErrorHandled::Reported
562 pub fn const_eval_provider<'a, 'tcx>(
563 tcx: TyCtxt<'a, 'tcx, 'tcx>,
564 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
565 ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> {
566 // see comment in const_eval_provider for what we're doing here
567 if key.param_env.reveal == Reveal::All {
568 let mut key = key.clone();
569 key.param_env.reveal = Reveal::UserFacing;
570 match tcx.const_eval(key) {
571 // try again with reveal all as requested
572 Err(ErrorHandled::TooGeneric) => {
573 // Promoteds should never be "too generic" when getting evaluated.
574 // They either don't get evaluated, or we are in a monomorphic context
575 assert!(key.value.promoted.is_none());
578 other => return other,
581 tcx.const_eval_raw(key).and_then(|val| {
582 validate_and_turn_into_const(tcx, val, key)
586 pub fn const_eval_raw_provider<'a, 'tcx>(
587 tcx: TyCtxt<'a, 'tcx, 'tcx>,
588 key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>,
589 ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> {
590 // Because the constant is computed twice (once per value of `Reveal`), we are at risk of
591 // reporting the same error twice here. To resolve this, we check whether we can evaluate the
592 // constant in the more restrictive `Reveal::UserFacing`, which most likely already was
593 // computed. For a large percentage of constants that will already have succeeded. Only
594 // associated constants of generic functions will fail due to not enough monomorphization
595 // information being available.
597 // In case we fail in the `UserFacing` variant, we just do the real computation.
598 if key.param_env.reveal == Reveal::All {
599 let mut key = key.clone();
600 key.param_env.reveal = Reveal::UserFacing;
601 match tcx.const_eval_raw(key) {
602 // try again with reveal all as requested
603 Err(ErrorHandled::TooGeneric) => {},
605 other => return other,
608 if cfg!(debug_assertions) {
609 // Make sure we format the instance even if we do not print it.
610 // This serves as a regression test against an ICE on printing.
611 // The next two lines concatenated contain some discussion:
612 // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/
613 // subject/anon_const_instance_printing/near/135980032
614 let instance = key.value.instance.to_string();
615 trace!("const eval: {:?} ({})", key, instance);
619 let def_id = cid.instance.def.def_id();
621 if def_id.is_local() && tcx.typeck_tables_of(def_id).tainted_by_errors {
622 return Err(ErrorHandled::Reported);
625 let span = tcx.def_span(cid.instance.def_id());
626 let mut ecx = InterpretCx::new(tcx.at(span), key.param_env, CompileTimeInterpreter::new());
628 let res = ecx.load_mir(cid.instance.def);
630 if let Some(index) = cid.promoted {
636 |mir| eval_body_using_ecx(&mut ecx, cid, mir, key.param_env)
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) {
646 // Ensure that if the above error was either `TooGeneric` or `Reported`
647 // an error must be reported.
648 let reported_err = tcx.sess.track_errors(|| {
649 err.report_as_error(ecx.tcx,
650 "could not evaluate static initializer")
654 tcx.sess.delay_span_bug(err.span,
655 &format!("static eval failure did not emit an error: {:#?}",
659 Err(ErrorReported) => ErrorHandled::Reported,
661 } else if def_id.is_local() {
662 // constant defined in this crate, we can figure out a lint level!
663 match tcx.def_kind(def_id) {
664 // constants never produce a hard error at the definition site. Anything else is
665 // a backwards compatibility hazard (and will break old versions of winapi for sure)
667 // note that validation may still cause a hard error on this very same constant,
668 // because any code that existed before validation could not have failed validation
669 // thus preventing such a hard error from being a backwards compatibility hazard
670 Some(DefKind::Const) | Some(DefKind::AssociatedConst) => {
671 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
673 tcx.at(tcx.def_span(def_id)),
674 "any use of this value will cause an error",
679 // promoting runtime code is only allowed to error if it references broken constants
680 // any other kind of error will be reported to the user as a deny-by-default lint
681 _ => if let Some(p) = cid.promoted {
682 let span = tcx.optimized_mir(def_id).promoted[p].span;
683 if let InterpError::ReferencedConstant = err.error {
686 "evaluation of constant expression failed",
691 "reaching this expression at runtime will panic or abort",
692 tcx.hir().as_local_hir_id(def_id).unwrap(),
696 // anything else (array lengths, enum initializers, constant patterns) are reported
701 "evaluation of constant value failed",
706 // use of broken constant from other crate
707 err.report_as_error(ecx.tcx, "could not evaluate constant")