1 //! Propagates constants for early reporting of statically known
8 use rustc::mir::interpret::{InterpResult, Scalar};
9 use rustc::mir::visit::{
10 MutVisitor, MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor,
13 read_only, AggregateKind, AssertKind, BasicBlock, BinOp, Body, BodyAndCache, ClearCrossCrate,
14 Constant, Local, LocalDecl, LocalKind, Location, Operand, Place, ReadOnlyBodyAndCache, Rvalue,
15 SourceInfo, SourceScope, SourceScopeData, Statement, StatementKind, Terminator, TerminatorKind,
18 use rustc::ty::layout::{
19 HasDataLayout, HasTyCtxt, LayoutError, LayoutOf, Size, TargetDataLayout, TyLayout,
21 use rustc::ty::subst::{InternalSubsts, Subst};
22 use rustc::ty::{self, ConstKind, Instance, ParamEnv, Ty, TyCtxt, TypeFoldable};
23 use rustc_ast::ast::Mutability;
24 use rustc_data_structures::fx::FxHashMap;
25 use rustc_hir::def::DefKind;
27 use rustc_index::vec::IndexVec;
28 use rustc_infer::traits;
31 use crate::const_eval::error_to_const_error;
32 use crate::interpret::{
33 self, intern_const_alloc_recursive, AllocId, Allocation, Frame, ImmTy, Immediate, InternKind,
34 InterpCx, LocalState, LocalValue, Memory, MemoryKind, OpTy, Operand as InterpOperand, PlaceTy,
35 Pointer, ScalarMaybeUndef, StackPopCleanup,
37 use crate::transform::{MirPass, MirSource};
39 /// The maximum number of bytes that we'll allocate space for a return value.
40 const MAX_ALLOC_LIMIT: u64 = 1024;
44 impl<'tcx> MirPass<'tcx> for ConstProp {
45 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut BodyAndCache<'tcx>) {
46 // will be evaluated by miri and produce its errors there
47 if source.promoted.is_some() {
51 use rustc::hir::map::blocks::FnLikeNode;
54 .as_local_hir_id(source.def_id())
55 .expect("Non-local call to local provider is_const_fn");
57 let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
58 let is_assoc_const = match tcx.def_kind(source.def_id()) {
59 Some(DefKind::AssocConst) => true,
63 // Only run const prop on functions, methods, closures and associated constants
64 if !is_fn_like && !is_assoc_const {
65 // skip anon_const/statics/consts because they'll be evaluated by miri anyway
66 trace!("ConstProp skipped for {:?}", source.def_id());
70 let is_generator = tcx.type_of(source.def_id()).is_generator();
71 // FIXME(welseywiser) const prop doesn't work on generators because of query cycles
72 // computing their layout.
74 trace!("ConstProp skipped for generator {:?}", source.def_id());
78 // Check if it's even possible to satisfy the 'where' clauses
80 // This branch will never be taken for any normal function.
81 // However, it's possible to `#!feature(trivial_bounds)]` to write
82 // a function with impossible to satisfy clauses, e.g.:
83 // `fn foo() where String: Copy {}`
85 // We don't usually need to worry about this kind of case,
86 // since we would get a compilation error if the user tried
87 // to call it. However, since we can do const propagation
88 // even without any calls to the function, we need to make
89 // sure that it even makes sense to try to evaluate the body.
90 // If there are unsatisfiable where clauses, then all bets are
91 // off, and we just give up.
93 // We manually filter the predicates, skipping anything that's not
94 // "global". We are in a potentially generic context
95 // (e.g. we are evaluating a function without substituting generic
96 // parameters, so this filtering serves two purposes:
98 // 1. We skip evaluating any predicates that we would
99 // never be able prove are unsatisfiable (e.g. `<T as Foo>`
100 // 2. We avoid trying to normalize predicates involving generic
101 // parameters (e.g. `<T as Foo>::MyItem`). This can confuse
102 // the normalization code (leading to cycle errors), since
103 // it's usually never invoked in this way.
105 .predicates_of(source.def_id())
108 .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None })
110 if !traits::normalize_and_test_predicates(
112 traits::elaborate_predicates(tcx, predicates).collect(),
114 trace!("ConstProp skipped for {:?}: found unsatisfiable predicates", source.def_id());
118 trace!("ConstProp starting for {:?}", source.def_id());
120 let dummy_body = &Body::new(
121 body.basic_blocks().clone(),
122 body.source_scopes.clone(),
123 body.local_decls.clone(),
127 tcx.def_span(source.def_id()),
132 // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
133 // constants, instead of just checking for const-folding succeeding.
134 // That would require an uniform one-def no-mutation analysis
135 // and RPO (or recursing when needing the value of a local).
136 let mut optimization_finder =
137 ConstPropagator::new(read_only!(body), dummy_body, tcx, source);
138 optimization_finder.visit_body(body);
140 trace!("ConstProp done for {:?}", source.def_id());
144 struct ConstPropMachine;
146 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine {
147 type MemoryKinds = !;
148 type PointerTag = ();
151 type FrameExtra = ();
152 type MemoryExtra = ();
153 type AllocExtra = ();
155 type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>;
157 const STATIC_KIND: Option<!> = None;
159 const CHECK_ALIGN: bool = false;
162 fn enforce_validity(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
166 fn find_mir_or_eval_fn(
167 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
169 _instance: ty::Instance<'tcx>,
170 _args: &[OpTy<'tcx>],
171 _ret: Option<(PlaceTy<'tcx>, BasicBlock)>,
172 _unwind: Option<BasicBlock>,
173 ) -> InterpResult<'tcx, Option<&'mir Body<'tcx>>> {
178 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
180 _args: &[OpTy<'tcx>],
181 _ret: Option<(PlaceTy<'tcx>, BasicBlock)>,
182 _unwind: Option<BasicBlock>,
183 ) -> InterpResult<'tcx> {
188 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
190 _instance: ty::Instance<'tcx>,
191 _args: &[OpTy<'tcx>],
192 _ret: Option<(PlaceTy<'tcx>, BasicBlock)>,
193 _unwind: Option<BasicBlock>,
194 ) -> InterpResult<'tcx> {
195 throw_unsup!(ConstPropUnsupported("calling intrinsics isn't supported in ConstProp"));
199 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
201 _msg: &rustc::mir::AssertMessage<'tcx>,
202 _unwind: Option<rustc::mir::BasicBlock>,
203 ) -> InterpResult<'tcx> {
204 bug!("panics terminators are not evaluated in ConstProp");
207 fn ptr_to_int(_mem: &Memory<'mir, 'tcx, Self>, _ptr: Pointer) -> InterpResult<'tcx, u64> {
208 throw_unsup!(ConstPropUnsupported("ptr-to-int casts aren't supported in ConstProp"));
212 _ecx: &InterpCx<'mir, 'tcx, Self>,
216 ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
217 // We can't do this because aliasing of memory can differ between const eval and llvm
218 throw_unsup!(ConstPropUnsupported(
219 "pointer arithmetic or comparisons aren't supported \
225 fn init_allocation_extra<'b>(
228 alloc: Cow<'b, Allocation>,
229 _kind: Option<MemoryKind<!>>,
230 ) -> (Cow<'b, Allocation<Self::PointerTag>>, Self::PointerTag) {
231 // We do not use a tag so we can just cheaply forward the allocation
236 fn tag_static_base_pointer(_memory_extra: &(), _id: AllocId) -> Self::PointerTag {
241 _ecx: &mut InterpCx<'mir, 'tcx, Self>,
242 _dest: PlaceTy<'tcx>,
243 ) -> InterpResult<'tcx> {
244 throw_unsup!(ConstPropUnsupported("can't const prop `box` keyword"));
248 _ecx: &InterpCx<'mir, 'tcx, Self>,
249 frame: &Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>,
251 ) -> InterpResult<'tcx, InterpOperand<Self::PointerTag>> {
252 let l = &frame.locals[local];
254 if l.value == LocalValue::Uninitialized {
255 throw_unsup!(ConstPropUnsupported("tried to access an uninitialized local"));
261 fn before_access_static(
263 allocation: &Allocation<Self::PointerTag, Self::AllocExtra>,
264 ) -> InterpResult<'tcx> {
265 // if the static allocation is mutable or if it has relocations (it may be legal to mutate
266 // the memory behind that in the future), then we can't const prop it
267 if allocation.mutability == Mutability::Mut || allocation.relocations().len() > 0 {
268 throw_unsup!(ConstPropUnsupported("can't eval mutable statics in ConstProp"));
275 fn stack_push(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
280 /// Finds optimization opportunities on the MIR.
281 struct ConstPropagator<'mir, 'tcx> {
282 ecx: InterpCx<'mir, 'tcx, ConstPropMachine>,
284 can_const_prop: IndexVec<Local, ConstPropMode>,
285 param_env: ParamEnv<'tcx>,
286 // FIXME(eddyb) avoid cloning these two fields more than once,
287 // by accessing them through `ecx` instead.
288 source_scopes: IndexVec<SourceScope, SourceScopeData>,
289 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
290 ret: Option<OpTy<'tcx, ()>>,
291 // Because we have `MutVisitor` we can't obtain the `SourceInfo` from a `Location`. So we store
292 // the last known `SourceInfo` here and just keep revisiting it.
293 source_info: Option<SourceInfo>,
296 impl<'mir, 'tcx> LayoutOf for ConstPropagator<'mir, 'tcx> {
298 type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
300 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
301 self.tcx.layout_of(self.param_env.and(ty))
305 impl<'mir, 'tcx> HasDataLayout for ConstPropagator<'mir, 'tcx> {
307 fn data_layout(&self) -> &TargetDataLayout {
308 &self.tcx.data_layout
312 impl<'mir, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'mir, 'tcx> {
314 fn tcx(&self) -> TyCtxt<'tcx> {
319 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
321 body: ReadOnlyBodyAndCache<'_, 'tcx>,
322 dummy_body: &'mir Body<'tcx>,
324 source: MirSource<'tcx>,
325 ) -> ConstPropagator<'mir, 'tcx> {
326 let def_id = source.def_id();
327 let substs = &InternalSubsts::identity_for_item(tcx, def_id);
328 let mut param_env = tcx.param_env(def_id);
330 // If we're evaluating inside a monomorphic function, then use `Reveal::All` because
331 // we want to see the same instances that codegen will see. This allows us to `resolve()`
333 if !substs.needs_subst() {
334 param_env = param_env.with_reveal_all();
337 let span = tcx.def_span(def_id);
338 let mut ecx = InterpCx::new(tcx.at(span), param_env, ConstPropMachine, ());
339 let can_const_prop = CanConstProp::check(body);
342 .layout_of(body.return_ty().subst(tcx, substs))
344 // Don't bother allocating memory for ZST types which have no values
345 // or for large values.
346 .filter(|ret_layout| {
347 !ret_layout.is_zst() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)
349 .map(|ret_layout| ecx.allocate(ret_layout, MemoryKind::Stack));
351 ecx.push_stack_frame(
352 Instance::new(def_id, substs),
356 StackPopCleanup::None { cleanup: false },
358 .expect("failed to push initial stack frame");
365 // FIXME(eddyb) avoid cloning these two fields more than once,
366 // by accessing them through `ecx` instead.
367 source_scopes: body.source_scopes.clone(),
368 //FIXME(wesleywiser) we can't steal this because `Visitor::super_visit_body()` needs it
369 local_decls: body.local_decls.clone(),
370 ret: ret.map(Into::into),
375 fn get_const(&self, local: Local) -> Option<OpTy<'tcx>> {
376 if local == RETURN_PLACE {
377 // Try to read the return place as an immediate so that if it is representable as a
378 // scalar, we can handle it as such, but otherwise, just return the value as is.
379 return match self.ret.map(|ret| self.ecx.try_read_immediate(ret)) {
380 Some(Ok(Ok(imm))) => Some(imm.into()),
385 self.ecx.access_local(self.ecx.frame(), local, None).ok()
388 fn remove_const(&mut self, local: Local) {
389 self.ecx.frame_mut().locals[local] =
390 LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) };
393 fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
394 match &self.source_scopes[source_info.scope].local_data {
395 ClearCrossCrate::Set(data) => Some(data.lint_root),
396 ClearCrossCrate::Clear => None,
400 fn use_ecx<F, T>(&mut self, f: F) -> Option<T>
402 F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
404 let r = match f(self) {
405 Ok(val) => Some(val),
407 // Some errors shouldn't come up because creating them causes
408 // an allocation, which we should avoid. When that happens,
409 // dedicated error variants should be introduced instead.
410 // Only test this in debug builds though to avoid disruptions.
412 !error.kind.allocates(),
413 "const-prop encountered allocating error: {}",
422 fn eval_constant(&mut self, c: &Constant<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
423 self.ecx.tcx.span = c.span;
425 // FIXME we need to revisit this for #67176
430 match self.ecx.eval_const_to_op(c.literal, None) {
433 let err = error_to_const_error(&self.ecx, error);
434 if let Some(lint_root) = self.lint_root(source_info) {
435 let lint_only = match c.literal.val {
436 // Promoteds must lint and not error as the user didn't ask for them
437 ConstKind::Unevaluated(_, _, Some(_)) => true,
438 // Out of backwards compatibility we cannot report hard errors in unused
439 // generic functions using associated constants of the generic parameters.
440 _ => c.literal.needs_subst(),
443 // Out of backwards compatibility we cannot report hard errors in unused
444 // generic functions using associated constants of the generic parameters.
447 "erroneous constant used",
452 err.report_as_error(self.ecx.tcx, "erroneous constant used");
455 err.report_as_error(self.ecx.tcx, "erroneous constant used");
462 fn eval_place(&mut self, place: &Place<'tcx>) -> Option<OpTy<'tcx>> {
463 trace!("eval_place(place={:?})", place);
464 self.use_ecx(|this| this.ecx.eval_place_to_op(place, None))
467 fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
469 Operand::Constant(ref c) => self.eval_constant(c, source_info),
470 Operand::Move(ref place) | Operand::Copy(ref place) => self.eval_place(place),
474 fn report_assert_as_lint(
476 lint: &'static lint::Lint,
477 source_info: SourceInfo,
478 message: &'static str,
479 panic: AssertKind<u64>,
481 let lint_root = self.lint_root(source_info)?;
482 self.tcx.struct_span_lint_hir(lint, lint_root, source_info.span, |lint| {
483 let mut err = lint.build(message);
484 err.span_label(source_info.span, format!("{:?}", panic));
494 source_info: SourceInfo,
496 if self.use_ecx(|this| {
497 let val = this.ecx.read_immediate(this.ecx.eval_operand(arg, None)?)?;
498 let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, val)?;
501 // `AssertKind` only has an `OverflowNeg` variant, so make sure that is
502 // appropriate to use.
503 assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
504 self.report_assert_as_lint(
505 lint::builtin::ARITHMETIC_OVERFLOW,
507 "this arithmetic operation will overflow",
508 AssertKind::OverflowNeg,
518 left: &Operand<'tcx>,
519 right: &Operand<'tcx>,
520 source_info: SourceInfo,
523 self.use_ecx(|this| this.ecx.read_immediate(this.ecx.eval_operand(right, None)?))?;
524 // Check for exceeding shifts *even if* we cannot evaluate the LHS.
525 if op == BinOp::Shr || op == BinOp::Shl {
526 // We need the type of the LHS. We cannot use `place_layout` as that is the type
527 // of the result, which for checked binops is not the same!
528 let left_ty = left.ty(&self.local_decls, self.tcx);
529 let left_size_bits = self.ecx.layout_of(left_ty).ok()?.size.bits();
530 let right_size = r.layout.size;
531 let r_bits = r.to_scalar().ok();
532 // This is basically `force_bits`.
533 let r_bits = r_bits.and_then(|r| r.to_bits_or_ptr(right_size, &self.tcx).ok());
534 if r_bits.map_or(false, |b| b >= left_size_bits as u128) {
535 self.report_assert_as_lint(
536 lint::builtin::ARITHMETIC_OVERFLOW,
538 "this arithmetic operation will overflow",
539 AssertKind::Overflow(op),
544 // The remaining operators are handled through `overflowing_binary_op`.
545 if self.use_ecx(|this| {
546 let l = this.ecx.read_immediate(this.ecx.eval_operand(left, None)?)?;
547 let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, l, r)?;
550 self.report_assert_as_lint(
551 lint::builtin::ARITHMETIC_OVERFLOW,
553 "this arithmetic operation will overflow",
554 AssertKind::Overflow(op),
563 rvalue: &Rvalue<'tcx>,
564 place_layout: TyLayout<'tcx>,
565 source_info: SourceInfo,
568 // #66397: Don't try to eval into large places as that can cause an OOM
569 if place_layout.size >= Size::from_bytes(MAX_ALLOC_LIMIT) {
573 // FIXME we need to revisit this for #67176
574 if rvalue.needs_subst() {
578 // Perform any special handling for specific Rvalue types.
579 // Generally, checks here fall into one of two categories:
580 // 1. Additional checking to provide useful lints to the user
581 // - In this case, we will do some validation and then fall through to the
582 // end of the function which evals the assignment.
583 // 2. Working around bugs in other parts of the compiler
584 // - In this case, we'll return `None` from this function to stop evaluation.
586 // Additional checking: give lints to the user if an overflow would occur.
587 // We do this here and not in the `Assert` terminator as that terminator is
588 // only sometimes emitted (overflow checks can be disabled), but we want to always
590 Rvalue::UnaryOp(op, arg) => {
591 trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
592 self.check_unary_op(*op, arg, source_info)?;
594 Rvalue::BinaryOp(op, left, right) => {
595 trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
596 self.check_binary_op(*op, left, right, source_info)?;
598 Rvalue::CheckedBinaryOp(op, left, right) => {
600 "checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
605 self.check_binary_op(*op, left, right, source_info)?;
608 // Do not try creating references (#67862)
609 Rvalue::Ref(_, _, place_ref) => {
610 trace!("skipping Ref({:?})", place_ref);
618 self.use_ecx(|this| {
619 trace!("calling eval_rvalue_into_place(rvalue = {:?}, place = {:?})", rvalue, place);
620 this.ecx.eval_rvalue_into_place(rvalue, place)?;
625 fn operand_from_scalar(&self, scalar: Scalar, ty: Ty<'tcx>, span: Span) -> Operand<'tcx> {
626 Operand::Constant(Box::new(Constant {
629 literal: self.tcx.mk_const(*ty::Const::from_scalar(self.tcx, scalar, ty)),
633 fn replace_with_const(
635 rval: &mut Rvalue<'tcx>,
637 source_info: SourceInfo,
639 trace!("attepting to replace {:?} with {:?}", rval, value);
640 if let Err(e) = self.ecx.validate_operand(
643 // FIXME: is ref tracking too expensive?
644 Some(&mut interpret::RefTracking::empty()),
646 trace!("validation error, attempt failed: {:?}", e);
650 // FIXME> figure out what to do when try_read_immediate fails
651 let imm = self.use_ecx(|this| this.ecx.try_read_immediate(value));
653 if let Some(Ok(imm)) = imm {
655 interpret::Immediate::Scalar(ScalarMaybeUndef::Scalar(scalar)) => {
656 *rval = Rvalue::Use(self.operand_from_scalar(
662 Immediate::ScalarPair(
663 ScalarMaybeUndef::Scalar(one),
664 ScalarMaybeUndef::Scalar(two),
666 // Found a value represented as a pair. For now only do cont-prop if type of
667 // Rvalue is also a pair with two scalars. The more general case is more
668 // complicated to implement so we'll do it later.
669 let ty = &value.layout.ty.kind;
670 // Only do it for tuples
671 if let ty::Tuple(substs) = ty {
672 // Only do it if tuple is also a pair with two scalars
673 if substs.len() == 2 {
674 let opt_ty1_ty2 = self.use_ecx(|this| {
675 let ty1 = substs[0].expect_ty();
676 let ty2 = substs[1].expect_ty();
677 let ty_is_scalar = |ty| {
678 this.ecx.layout_of(ty).ok().map(|ty| ty.details.abi.is_scalar())
681 if ty_is_scalar(ty1) && ty_is_scalar(ty2) {
688 if let Some(Some((ty1, ty2))) = opt_ty1_ty2 {
689 *rval = Rvalue::Aggregate(
690 Box::new(AggregateKind::Tuple),
692 self.operand_from_scalar(one, ty1, source_info.span),
693 self.operand_from_scalar(two, ty2, source_info.span),
705 fn should_const_prop(&mut self, op: OpTy<'tcx>) -> bool {
706 let mir_opt_level = self.tcx.sess.opts.debugging_opts.mir_opt_level;
708 if mir_opt_level == 0 {
713 interpret::Operand::Immediate(Immediate::Scalar(ScalarMaybeUndef::Scalar(s))) => {
716 interpret::Operand::Immediate(Immediate::ScalarPair(
717 ScalarMaybeUndef::Scalar(l),
718 ScalarMaybeUndef::Scalar(r),
719 )) => l.is_bits() && r.is_bits(),
720 interpret::Operand::Indirect(_) if mir_opt_level >= 2 => {
721 let mplace = op.assert_mem_place(&self.ecx);
722 intern_const_alloc_recursive(&mut self.ecx, InternKind::ConstProp, mplace, false)
723 .expect("failed to intern alloc");
731 /// The mode that `ConstProp` is allowed to run in for a given `Local`.
732 #[derive(Clone, Copy, Debug, PartialEq)]
734 /// The `Local` can be propagated into and reads of this `Local` can also be propagated.
736 /// The `Local` can be propagated into but reads cannot be propagated.
738 /// No propagation is allowed at all.
742 struct CanConstProp {
743 can_const_prop: IndexVec<Local, ConstPropMode>,
744 // false at the beginning, once set, there are not allowed to be any more assignments
745 found_assignment: IndexVec<Local, bool>,
749 /// returns true if `local` can be propagated
750 fn check(body: ReadOnlyBodyAndCache<'_, '_>) -> IndexVec<Local, ConstPropMode> {
751 let mut cpv = CanConstProp {
752 can_const_prop: IndexVec::from_elem(ConstPropMode::FullConstProp, &body.local_decls),
753 found_assignment: IndexVec::from_elem(false, &body.local_decls),
755 for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
756 // cannot use args at all
757 // cannot use locals because if x < y { y - x } else { x - y } would
759 // FIXME(oli-obk): lint variables until they are used in a condition
760 // FIXME(oli-obk): lint if return value is constant
761 let local_kind = body.local_kind(local);
763 if local_kind == LocalKind::Arg || local_kind == LocalKind::Var {
764 *val = ConstPropMode::OnlyPropagateInto;
765 trace!("local {:?} can't be const propagated because it's not a temporary", local);
768 cpv.visit_body(body);
773 impl<'tcx> Visitor<'tcx> for CanConstProp {
774 fn visit_local(&mut self, &local: &Local, context: PlaceContext, _: Location) {
775 use rustc::mir::visit::PlaceContext::*;
777 // Constants must have at most one write
778 // FIXME(oli-obk): we could be more powerful here, if the multiple writes
779 // only occur in independent execution paths
780 MutatingUse(MutatingUseContext::Store) => {
781 if self.found_assignment[local] {
782 trace!("local {:?} can't be propagated because of multiple assignments", local);
783 self.can_const_prop[local] = ConstPropMode::NoPropagation;
785 self.found_assignment[local] = true
788 // Reading constants is allowed an arbitrary number of times
789 NonMutatingUse(NonMutatingUseContext::Copy)
790 | NonMutatingUse(NonMutatingUseContext::Move)
791 | NonMutatingUse(NonMutatingUseContext::Inspect)
792 | NonMutatingUse(NonMutatingUseContext::Projection)
793 | MutatingUse(MutatingUseContext::Projection)
796 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
797 self.can_const_prop[local] = ConstPropMode::NoPropagation;
803 impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> {
804 fn tcx(&self) -> TyCtxt<'tcx> {
808 fn visit_constant(&mut self, constant: &mut Constant<'tcx>, location: Location) {
809 trace!("visit_constant: {:?}", constant);
810 self.super_constant(constant, location);
811 self.eval_constant(constant, self.source_info.unwrap());
814 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
815 trace!("visit_statement: {:?}", statement);
816 let source_info = statement.source_info;
817 self.source_info = Some(source_info);
818 if let StatementKind::Assign(box (ref place, ref mut rval)) = statement.kind {
819 let place_ty: Ty<'tcx> = place.ty(&self.local_decls, self.tcx).ty;
820 if let Ok(place_layout) = self.tcx.layout_of(self.param_env.and(place_ty)) {
821 if let Some(local) = place.as_local() {
822 let can_const_prop = self.can_const_prop[local];
823 if let Some(()) = self.const_prop(rval, place_layout, source_info, place) {
824 if can_const_prop == ConstPropMode::FullConstProp
825 || can_const_prop == ConstPropMode::OnlyPropagateInto
827 if let Some(value) = self.get_const(local) {
828 if self.should_const_prop(value) {
829 trace!("replacing {:?} with {:?}", rval, value);
830 self.replace_with_const(rval, value, statement.source_info);
832 if can_const_prop == ConstPropMode::FullConstProp {
833 trace!("propagated into {:?}", local);
839 if self.can_const_prop[local] != ConstPropMode::FullConstProp {
840 trace!("can't propagate into {:?}", local);
841 if local != RETURN_PLACE {
842 self.remove_const(local);
848 match statement.kind {
849 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
850 let frame = self.ecx.frame_mut();
851 frame.locals[local].value =
852 if let StatementKind::StorageLive(_) = statement.kind {
853 LocalValue::Uninitialized
862 self.super_statement(statement, location);
865 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
866 let source_info = terminator.source_info;
867 self.source_info = Some(source_info);
868 self.super_terminator(terminator, location);
869 match &mut terminator.kind {
870 TerminatorKind::Assert { expected, ref msg, ref mut cond, .. } => {
871 if let Some(value) = self.eval_operand(&cond, source_info) {
872 trace!("assertion on {:?} should be {:?}", value, expected);
873 let expected = ScalarMaybeUndef::from(Scalar::from_bool(*expected));
874 let value_const = self.ecx.read_scalar(value).unwrap();
875 if expected != value_const {
876 // poison all places this operand references so that further code
877 // doesn't use the invalid value
879 Operand::Move(ref place) | Operand::Copy(ref place) => {
880 self.remove_const(place.local);
882 Operand::Constant(_) => {}
884 let msg = match msg {
885 AssertKind::DivisionByZero => AssertKind::DivisionByZero,
886 AssertKind::RemainderByZero => AssertKind::RemainderByZero,
887 AssertKind::BoundsCheck { ref len, ref index } => {
889 self.eval_operand(len, source_info).expect("len must be const");
894 .to_machine_usize(&self.tcx)
897 .eval_operand(index, source_info)
898 .expect("index must be const");
903 .to_machine_usize(&self.tcx)
905 AssertKind::BoundsCheck { len, index }
907 // Overflow is are already covered by checks on the binary operators.
908 AssertKind::Overflow(_) | AssertKind::OverflowNeg => return,
909 // Need proper const propagator for these.
912 self.report_assert_as_lint(
913 lint::builtin::UNCONDITIONAL_PANIC,
915 "this operation will panic at runtime",
919 if self.should_const_prop(value) {
920 if let ScalarMaybeUndef::Scalar(scalar) = value_const {
921 *cond = self.operand_from_scalar(
931 TerminatorKind::SwitchInt { ref mut discr, switch_ty, .. } => {
932 if let Some(value) = self.eval_operand(&discr, source_info) {
933 if self.should_const_prop(value) {
934 if let ScalarMaybeUndef::Scalar(scalar) =
935 self.ecx.read_scalar(value).unwrap()
937 *discr = self.operand_from_scalar(scalar, switch_ty, source_info.span);
942 //none of these have Operands to const-propagate
943 TerminatorKind::Goto { .. }
944 | TerminatorKind::Resume
945 | TerminatorKind::Abort
946 | TerminatorKind::Return
947 | TerminatorKind::Unreachable
948 | TerminatorKind::Drop { .. }
949 | TerminatorKind::DropAndReplace { .. }
950 | TerminatorKind::Yield { .. }
951 | TerminatorKind::GeneratorDrop
952 | TerminatorKind::FalseEdges { .. }
953 | TerminatorKind::FalseUnwind { .. } => {}
954 //FIXME(wesleywiser) Call does have Operands that could be const-propagated
955 TerminatorKind::Call { .. } => {}