]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/const_prop.rs
`find_fn` -> `find_mir_or_eval_fn` rename
[rust.git] / src / librustc_mir / transform / const_prop.rs
1 //! Propagates constants for early reporting of statically known
2 //! assertion failures
3
4 use std::borrow::Cow;
5 use std::cell::Cell;
6
7 use rustc::hir::def::DefKind;
8 use rustc::hir::def_id::DefId;
9 use rustc::mir::{
10     AggregateKind, Constant, Location, Place, PlaceBase, Body, Operand, Rvalue, Local, UnOp,
11     StatementKind, Statement, LocalKind, TerminatorKind, Terminator,  ClearCrossCrate, SourceInfo,
12     BinOp, SourceScope, SourceScopeLocalData, LocalDecl, BasicBlock, RETURN_PLACE,
13 };
14 use rustc::mir::visit::{
15     Visitor, PlaceContext, MutatingUseContext, MutVisitor, NonMutatingUseContext,
16 };
17 use rustc::mir::interpret::{Scalar, InterpResult, PanicInfo};
18 use rustc::ty::{self, Instance, ParamEnv, Ty, TyCtxt};
19 use syntax::ast::Mutability;
20 use syntax_pos::{Span, DUMMY_SP};
21 use rustc::ty::subst::InternalSubsts;
22 use rustc_data_structures::fx::FxHashMap;
23 use rustc_index::vec::IndexVec;
24 use rustc::ty::layout::{
25     LayoutOf, TyLayout, LayoutError, HasTyCtxt, TargetDataLayout, HasDataLayout, Size,
26 };
27
28 use crate::rustc::ty::subst::Subst;
29 use crate::interpret::{
30     self, InterpCx, ScalarMaybeUndef, Immediate, OpTy,
31     StackPopCleanup, LocalValue, LocalState, AllocId, Frame,
32     Allocation, MemoryKind, ImmTy, Pointer, Memory, PlaceTy,
33     Operand as InterpOperand, intern_const_alloc_recursive,
34 };
35 use crate::const_eval::error_to_const_error;
36 use crate::transform::{MirPass, MirSource};
37
38 /// The maximum number of bytes that we'll allocate space for a return value.
39 const MAX_ALLOC_LIMIT: u64 = 1024;
40
41 pub struct ConstProp;
42
43 impl<'tcx> MirPass<'tcx> for ConstProp {
44     fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>) {
45         // will be evaluated by miri and produce its errors there
46         if source.promoted.is_some() {
47             return;
48         }
49
50         use rustc::hir::map::blocks::FnLikeNode;
51         let hir_id = tcx.hir().as_local_hir_id(source.def_id())
52                               .expect("Non-local call to local provider is_const_fn");
53
54         let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
55         let is_assoc_const = match tcx.def_kind(source.def_id()) {
56             Some(DefKind::AssocConst) => true,
57             _ => false,
58         };
59
60         // Only run const prop on functions, methods, closures and associated constants
61         if !is_fn_like && !is_assoc_const  {
62             // skip anon_const/statics/consts because they'll be evaluated by miri anyway
63             trace!("ConstProp skipped for {:?}", source.def_id());
64             return
65         }
66
67         let is_generator = tcx.type_of(source.def_id()).is_generator();
68         // FIXME(welseywiser) const prop doesn't work on generators because of query cycles
69         // computing their layout.
70         if is_generator {
71             trace!("ConstProp skipped for generator {:?}", source.def_id());
72             return
73         }
74
75         trace!("ConstProp starting for {:?}", source.def_id());
76
77         // Steal some data we need from `body`.
78         let source_scope_local_data = std::mem::replace(
79             &mut body.source_scope_local_data,
80             ClearCrossCrate::Clear
81         );
82
83         let dummy_body =
84             &Body::new(
85                 body.basic_blocks().clone(),
86                 Default::default(),
87                 ClearCrossCrate::Clear,
88                 body.local_decls.clone(),
89                 Default::default(),
90                 body.arg_count,
91                 Default::default(),
92                 tcx.def_span(source.def_id()),
93                 Default::default(),
94             );
95
96         // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
97         // constants, instead of just checking for const-folding succeeding.
98         // That would require an uniform one-def no-mutation analysis
99         // and RPO (or recursing when needing the value of a local).
100         let mut optimization_finder = ConstPropagator::new(
101             body,
102             dummy_body,
103             source_scope_local_data,
104             tcx,
105             source
106         );
107         optimization_finder.visit_body(body);
108
109         // put back the data we stole from `mir`
110         let source_scope_local_data = optimization_finder.release_stolen_data();
111         std::mem::replace(
112             &mut body.source_scope_local_data,
113             source_scope_local_data
114         );
115
116         trace!("ConstProp done for {:?}", source.def_id());
117     }
118 }
119
120 struct ConstPropMachine;
121
122 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine {
123     type MemoryKinds = !;
124     type PointerTag = ();
125     type ExtraFnVal = !;
126
127     type FrameExtra = ();
128     type MemoryExtra = ();
129     type AllocExtra = ();
130
131     type MemoryMap = FxHashMap<AllocId, (MemoryKind<!>, Allocation)>;
132
133     const STATIC_KIND: Option<!> = None;
134
135     const CHECK_ALIGN: bool = false;
136
137     #[inline(always)]
138     fn enforce_validity(_ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
139         false
140     }
141
142     fn find_mir_or_eval_fn(
143         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
144         _instance: ty::Instance<'tcx>,
145         _args: &[OpTy<'tcx>],
146         _ret: Option<(PlaceTy<'tcx>, BasicBlock)>,
147         _unwind: Option<BasicBlock>,
148     ) -> InterpResult<'tcx, Option<&'mir Body<'tcx>>> {
149         Ok(None)
150     }
151
152     fn call_extra_fn(
153         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
154         fn_val: !,
155         _args: &[OpTy<'tcx>],
156         _ret: Option<(PlaceTy<'tcx>, BasicBlock)>,
157         _unwind: Option<BasicBlock>
158     ) -> InterpResult<'tcx> {
159         match fn_val {}
160     }
161
162     fn call_intrinsic(
163         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
164         _span: Span,
165         _instance: ty::Instance<'tcx>,
166         _args: &[OpTy<'tcx>],
167         _ret: Option<(PlaceTy<'tcx>, BasicBlock)>,
168         _unwind: Option<BasicBlock>
169     ) -> InterpResult<'tcx> {
170         throw_unsup_format!("calling intrinsics isn't supported in ConstProp");
171     }
172
173     fn ptr_to_int(
174         _mem: &Memory<'mir, 'tcx, Self>,
175         _ptr: Pointer,
176     ) -> InterpResult<'tcx, u64> {
177         throw_unsup_format!("ptr-to-int casts aren't supported in ConstProp");
178     }
179
180     fn binary_ptr_op(
181         _ecx: &InterpCx<'mir, 'tcx, Self>,
182         _bin_op: BinOp,
183         _left: ImmTy<'tcx>,
184         _right: ImmTy<'tcx>,
185     ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
186         // We can't do this because aliasing of memory can differ between const eval and llvm
187         throw_unsup_format!("pointer arithmetic or comparisons aren't supported in ConstProp");
188     }
189
190     fn find_foreign_static(
191         _tcx: TyCtxt<'tcx>,
192         _def_id: DefId,
193     ) -> InterpResult<'tcx, Cow<'tcx, Allocation<Self::PointerTag>>> {
194         throw_unsup!(ReadForeignStatic)
195     }
196
197     #[inline(always)]
198     fn tag_allocation<'b>(
199         _memory_extra: &(),
200         _id: AllocId,
201         alloc: Cow<'b, Allocation>,
202         _kind: Option<MemoryKind<!>>,
203     ) -> (Cow<'b, Allocation<Self::PointerTag>>, Self::PointerTag) {
204         // We do not use a tag so we can just cheaply forward the allocation
205         (alloc, ())
206     }
207
208     #[inline(always)]
209     fn tag_static_base_pointer(
210         _memory_extra: &(),
211         _id: AllocId,
212     ) -> Self::PointerTag {
213         ()
214     }
215
216     fn box_alloc(
217         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
218         _dest: PlaceTy<'tcx>,
219     ) -> InterpResult<'tcx> {
220         throw_unsup_format!("can't const prop `box` keyword");
221     }
222
223     fn access_local(
224         _ecx: &InterpCx<'mir, 'tcx, Self>,
225         frame: &Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>,
226         local: Local,
227     ) -> InterpResult<'tcx, InterpOperand<Self::PointerTag>> {
228         let l = &frame.locals[local];
229
230         if l.value == LocalValue::Uninitialized {
231             throw_unsup_format!("tried to access an uninitialized local");
232         }
233
234         l.access()
235     }
236
237     fn before_access_static(
238         allocation: &Allocation<Self::PointerTag, Self::AllocExtra>,
239     ) -> InterpResult<'tcx> {
240         // if the static allocation is mutable or if it has relocations (it may be legal to mutate
241         // the memory behind that in the future), then we can't const prop it
242         if allocation.mutability == Mutability::Mutable || allocation.relocations().len() > 0 {
243             throw_unsup_format!("can't eval mutable statics in ConstProp");
244         }
245
246         Ok(())
247     }
248
249     fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
250         Ok(())
251     }
252
253     #[inline(always)]
254     fn stack_push(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
255         Ok(())
256     }
257 }
258
259 type Const<'tcx> = OpTy<'tcx>;
260
261 /// Finds optimization opportunities on the MIR.
262 struct ConstPropagator<'mir, 'tcx> {
263     ecx: InterpCx<'mir, 'tcx, ConstPropMachine>,
264     tcx: TyCtxt<'tcx>,
265     source: MirSource<'tcx>,
266     can_const_prop: IndexVec<Local, bool>,
267     param_env: ParamEnv<'tcx>,
268     source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
269     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
270     ret: Option<OpTy<'tcx, ()>>,
271 }
272
273 impl<'mir, 'tcx> LayoutOf for ConstPropagator<'mir, 'tcx> {
274     type Ty = Ty<'tcx>;
275     type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
276
277     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
278         self.tcx.layout_of(self.param_env.and(ty))
279     }
280 }
281
282 impl<'mir, 'tcx> HasDataLayout for ConstPropagator<'mir, 'tcx> {
283     #[inline]
284     fn data_layout(&self) -> &TargetDataLayout {
285         &self.tcx.data_layout
286     }
287 }
288
289 impl<'mir, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'mir, 'tcx> {
290     #[inline]
291     fn tcx(&self) -> TyCtxt<'tcx> {
292         self.tcx
293     }
294 }
295
296 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
297     fn new(
298         body: &Body<'tcx>,
299         dummy_body: &'mir Body<'tcx>,
300         source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
301         tcx: TyCtxt<'tcx>,
302         source: MirSource<'tcx>,
303     ) -> ConstPropagator<'mir, 'tcx> {
304         let def_id = source.def_id();
305         let param_env = tcx.param_env(def_id);
306         let span = tcx.def_span(def_id);
307         let mut ecx = InterpCx::new(tcx.at(span), param_env, ConstPropMachine, ());
308         let can_const_prop = CanConstProp::check(body);
309
310         let substs = &InternalSubsts::identity_for_item(tcx, def_id);
311
312         let ret =
313             ecx
314                 .layout_of(body.return_ty().subst(tcx, substs))
315                 .ok()
316                 // Don't bother allocating memory for ZST types which have no values
317                 // or for large values.
318                 .filter(|ret_layout| !ret_layout.is_zst() &&
319                                      ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT))
320                 .map(|ret_layout| ecx.allocate(ret_layout, MemoryKind::Stack));
321
322         ecx.push_stack_frame(
323             Instance::new(def_id, substs),
324             span,
325             dummy_body,
326             ret.map(Into::into),
327             StackPopCleanup::None {
328                 cleanup: false,
329             },
330         ).expect("failed to push initial stack frame");
331
332         ConstPropagator {
333             ecx,
334             tcx,
335             source,
336             param_env,
337             can_const_prop,
338             source_scope_local_data,
339             //FIXME(wesleywiser) we can't steal this because `Visitor::super_visit_body()` needs it
340             local_decls: body.local_decls.clone(),
341             ret: ret.map(Into::into),
342         }
343     }
344
345     fn release_stolen_data(self) -> ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>> {
346         self.source_scope_local_data
347     }
348
349     fn get_const(&self, local: Local) -> Option<Const<'tcx>> {
350         if local == RETURN_PLACE {
351             // Try to read the return place as an immediate so that if it is representable as a
352             // scalar, we can handle it as such, but otherwise, just return the value as is.
353             return match self.ret.map(|ret| self.ecx.try_read_immediate(ret)) {
354                 Some(Ok(Ok(imm))) => Some(imm.into()),
355                 _ => self.ret,
356             };
357         }
358
359         self.ecx.access_local(self.ecx.frame(), local, None).ok()
360     }
361
362     fn remove_const(&mut self, local: Local) {
363         self.ecx.frame_mut().locals[local] = LocalState {
364             value: LocalValue::Uninitialized,
365             layout: Cell::new(None),
366         };
367     }
368
369     fn use_ecx<F, T>(
370         &mut self,
371         source_info: SourceInfo,
372         f: F
373     ) -> Option<T>
374     where
375         F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
376     {
377         self.ecx.tcx.span = source_info.span;
378         let lint_root = match self.source_scope_local_data {
379             ClearCrossCrate::Set(ref ivs) => {
380                 //FIXME(#51314): remove this check
381                 if source_info.scope.index() >= ivs.len() {
382                     return None;
383                 }
384                 ivs[source_info.scope].lint_root
385             },
386             ClearCrossCrate::Clear => return None,
387         };
388         let r = match f(self) {
389             Ok(val) => Some(val),
390             Err(error) => {
391                 use rustc::mir::interpret::InterpError::*;
392                 match error.kind {
393                     Exit(_) => bug!("the CTFE program cannot exit"),
394                     Unsupported(_)
395                     | UndefinedBehavior(_)
396                     | InvalidProgram(_)
397                     | ResourceExhaustion(_) => {
398                         // Ignore these errors.
399                     }
400                     Panic(_) => {
401                         let diagnostic = error_to_const_error(&self.ecx, error);
402                         diagnostic.report_as_lint(
403                             self.ecx.tcx,
404                             "this expression will panic at runtime",
405                             lint_root,
406                             None,
407                         );
408                     }
409                 }
410                 None
411             },
412         };
413         self.ecx.tcx.span = DUMMY_SP;
414         r
415     }
416
417     fn eval_constant(
418         &mut self,
419         c: &Constant<'tcx>,
420     ) -> Option<Const<'tcx>> {
421         self.ecx.tcx.span = c.span;
422         match self.ecx.eval_const_to_op(c.literal, None) {
423             Ok(op) => {
424                 Some(op)
425             },
426             Err(error) => {
427                 let err = error_to_const_error(&self.ecx, error);
428                 err.report_as_error(self.ecx.tcx, "erroneous constant used");
429                 None
430             },
431         }
432     }
433
434     fn eval_place(&mut self, place: &Place<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
435         trace!("eval_place(place={:?})", place);
436         self.use_ecx(source_info, |this| {
437             this.ecx.eval_place_to_op(place, None)
438         })
439     }
440
441     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
442         match *op {
443             Operand::Constant(ref c) => self.eval_constant(c),
444             | Operand::Move(ref place)
445             | Operand::Copy(ref place) => self.eval_place(place, source_info),
446         }
447     }
448
449     fn const_prop(
450         &mut self,
451         rvalue: &Rvalue<'tcx>,
452         place_layout: TyLayout<'tcx>,
453         source_info: SourceInfo,
454         place: &Place<'tcx>,
455     ) -> Option<()> {
456         let span = source_info.span;
457
458         // #66397: Don't try to eval into large places as that can cause an OOM
459         if place_layout.size >= Size::from_bytes(MAX_ALLOC_LIMIT) {
460             return None;
461         }
462
463         let overflow_check = self.tcx.sess.overflow_checks();
464
465         // Perform any special handling for specific Rvalue types.
466         // Generally, checks here fall into one of two categories:
467         //   1. Additional checking to provide useful lints to the user
468         //        - In this case, we will do some validation and then fall through to the
469         //          end of the function which evals the assignment.
470         //   2. Working around bugs in other parts of the compiler
471         //        - In this case, we'll return `None` from this function to stop evaluation.
472         match rvalue {
473             // Additional checking: if overflow checks are disabled (which is usually the case in
474             // release mode), then we need to do additional checking here to give lints to the user
475             // if an overflow would occur.
476             Rvalue::UnaryOp(UnOp::Neg, arg) if !overflow_check => {
477                 trace!("checking UnaryOp(op = Neg, arg = {:?})", arg);
478
479                 self.use_ecx(source_info, |this| {
480                     let ty = arg.ty(&this.local_decls, this.tcx);
481
482                     if ty.is_integral() {
483                         let arg = this.ecx.eval_operand(arg, None)?;
484                         let prim = this.ecx.read_immediate(arg)?;
485                         // Need to do overflow check here: For actual CTFE, MIR
486                         // generation emits code that does this before calling the op.
487                         if prim.to_bits()? == (1 << (prim.layout.size.bits() - 1)) {
488                             throw_panic!(OverflowNeg)
489                         }
490                     }
491
492                     Ok(())
493                 })?;
494             }
495
496             // Additional checking: check for overflows on integer binary operations and report
497             // them to the user as lints.
498             Rvalue::BinaryOp(op, left, right) => {
499                 trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
500
501                 let r = self.use_ecx(source_info, |this| {
502                     this.ecx.read_immediate(this.ecx.eval_operand(right, None)?)
503                 })?;
504                 if *op == BinOp::Shr || *op == BinOp::Shl {
505                     let left_bits = place_layout.size.bits();
506                     let right_size = r.layout.size;
507                     let r_bits = r.to_scalar().and_then(|r| r.to_bits(right_size));
508                     if r_bits.ok().map_or(false, |b| b >= left_bits as u128) {
509                         let source_scope_local_data = match self.source_scope_local_data {
510                             ClearCrossCrate::Set(ref data) => data,
511                             ClearCrossCrate::Clear => return None,
512                         };
513                         let dir = if *op == BinOp::Shr {
514                             "right"
515                         } else {
516                             "left"
517                         };
518                         let hir_id = source_scope_local_data[source_info.scope].lint_root;
519                         self.tcx.lint_hir(
520                             ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
521                             hir_id,
522                             span,
523                             &format!("attempt to shift {} with overflow", dir));
524                         return None;
525                     }
526                 }
527
528                 // If overflow checking is enabled (like in debug mode by default),
529                 // then we'll already catch overflow when we evaluate the `Assert` statement
530                 // in MIR. However, if overflow checking is disabled, then there won't be any
531                 // `Assert` statement and so we have to do additional checking here.
532                 if !overflow_check {
533                     self.use_ecx(source_info, |this| {
534                         let l = this.ecx.read_immediate(this.ecx.eval_operand(left, None)?)?;
535                         let (_, overflow, _ty) = this.ecx.overflowing_binary_op(*op, l, r)?;
536
537                         if overflow {
538                             let err = err_panic!(Overflow(*op)).into();
539                             return Err(err);
540                         }
541
542                         Ok(())
543                     })?;
544                 }
545             }
546
547             // Work around: avoid ICE in miri. FIXME(wesleywiser)
548             // The Miri engine ICEs when taking a reference to an uninitialized unsized
549             // local. There's nothing it can do here: taking a reference needs an allocation
550             // which needs to know the size. Normally that's okay as during execution
551             // (e.g. for CTFE) it can never happen. But here in const_prop
552             // unknown data is uninitialized, so if e.g. a function argument is unsized
553             // and has a reference taken, we get an ICE.
554             Rvalue::Ref(_, _, place_ref) => {
555                 trace!("checking Ref({:?})", place_ref);
556
557                 if let Some(local) = place_ref.as_local() {
558                     let alive =
559                         if let LocalValue::Live(_) = self.ecx.frame().locals[local].value {
560                             true
561                         } else {
562                             false
563                         };
564
565                     if !alive {
566                         trace!("skipping Ref({:?}) to uninitialized local", place);
567                         return None;
568                     }
569                 }
570             }
571
572             _ => { }
573         }
574
575         self.use_ecx(source_info, |this| {
576             trace!("calling eval_rvalue_into_place(rvalue = {:?}, place = {:?})", rvalue, place);
577             this.ecx.eval_rvalue_into_place(rvalue, place)?;
578             Ok(())
579         })
580     }
581
582     fn operand_from_scalar(&self, scalar: Scalar, ty: Ty<'tcx>, span: Span) -> Operand<'tcx> {
583         Operand::Constant(Box::new(
584             Constant {
585                 span,
586                 user_ty: None,
587                 literal: self.tcx.mk_const(*ty::Const::from_scalar(
588                     self.tcx,
589                     scalar,
590                     ty,
591                 ))
592             }
593         ))
594     }
595
596     fn replace_with_const(
597         &mut self,
598         rval: &mut Rvalue<'tcx>,
599         value: Const<'tcx>,
600         source_info: SourceInfo,
601     ) {
602         trace!("attepting to replace {:?} with {:?}", rval, value);
603         if let Err(e) = self.ecx.validate_operand(
604             value,
605             vec![],
606             // FIXME: is ref tracking too expensive?
607             Some(&mut interpret::RefTracking::empty()),
608         ) {
609             trace!("validation error, attempt failed: {:?}", e);
610             return;
611         }
612
613         // FIXME> figure out what tho do when try_read_immediate fails
614         let imm = self.use_ecx(source_info, |this| {
615             this.ecx.try_read_immediate(value)
616         });
617
618         if let Some(Ok(imm)) = imm {
619             match *imm {
620                 interpret::Immediate::Scalar(ScalarMaybeUndef::Scalar(scalar)) => {
621                     *rval = Rvalue::Use(
622                         self.operand_from_scalar(scalar, value.layout.ty, source_info.span));
623                 },
624                 Immediate::ScalarPair(
625                     ScalarMaybeUndef::Scalar(one),
626                     ScalarMaybeUndef::Scalar(two)
627                 ) => {
628                     let ty = &value.layout.ty.kind;
629                     if let ty::Tuple(substs) = ty {
630                         *rval = Rvalue::Aggregate(
631                             Box::new(AggregateKind::Tuple),
632                             vec![
633                                 self.operand_from_scalar(
634                                     one, substs[0].expect_ty(), source_info.span
635                                 ),
636                                 self.operand_from_scalar(
637                                     two, substs[1].expect_ty(), source_info.span
638                                 ),
639                             ],
640                         );
641                     }
642                 },
643                 _ => { }
644             }
645         }
646     }
647
648     fn should_const_prop(&mut self, op: OpTy<'tcx>) -> bool {
649         let mir_opt_level = self.tcx.sess.opts.debugging_opts.mir_opt_level;
650
651         if mir_opt_level == 0 {
652             return false;
653         }
654
655         match *op {
656             interpret::Operand::Immediate(Immediate::Scalar(ScalarMaybeUndef::Scalar(s))) =>
657                 s.is_bits(),
658             interpret::Operand::Immediate(Immediate::ScalarPair(ScalarMaybeUndef::Scalar(l),
659                                                                 ScalarMaybeUndef::Scalar(r))) =>
660                 l.is_bits() && r.is_bits(),
661             interpret::Operand::Indirect(_) if mir_opt_level >= 2 => {
662                 intern_const_alloc_recursive(
663                     &mut self.ecx,
664                     None,
665                     op.assert_mem_place()
666                 ).expect("failed to intern alloc");
667                 true
668             },
669             _ => false
670         }
671     }
672 }
673
674 struct CanConstProp {
675     can_const_prop: IndexVec<Local, bool>,
676     // false at the beginning, once set, there are not allowed to be any more assignments
677     found_assignment: IndexVec<Local, bool>,
678 }
679
680 impl CanConstProp {
681     /// returns true if `local` can be propagated
682     fn check(body: &Body<'_>) -> IndexVec<Local, bool> {
683         let mut cpv = CanConstProp {
684             can_const_prop: IndexVec::from_elem(true, &body.local_decls),
685             found_assignment: IndexVec::from_elem(false, &body.local_decls),
686         };
687         for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
688             // cannot use args at all
689             // cannot use locals because if x < y { y - x } else { x - y } would
690             //        lint for x != y
691             // FIXME(oli-obk): lint variables until they are used in a condition
692             // FIXME(oli-obk): lint if return value is constant
693             let local_kind = body.local_kind(local);
694             *val = local_kind == LocalKind::Temp || local_kind == LocalKind::ReturnPointer;
695
696             if !*val {
697                 trace!("local {:?} can't be propagated because it's not a temporary", local);
698             }
699         }
700         cpv.visit_body(body);
701         cpv.can_const_prop
702     }
703 }
704
705 impl<'tcx> Visitor<'tcx> for CanConstProp {
706     fn visit_local(
707         &mut self,
708         &local: &Local,
709         context: PlaceContext,
710         _: Location,
711     ) {
712         use rustc::mir::visit::PlaceContext::*;
713         match context {
714             // Constants must have at most one write
715             // FIXME(oli-obk): we could be more powerful here, if the multiple writes
716             // only occur in independent execution paths
717             MutatingUse(MutatingUseContext::Store) => if self.found_assignment[local] {
718                 trace!("local {:?} can't be propagated because of multiple assignments", local);
719                 self.can_const_prop[local] = false;
720             } else {
721                 self.found_assignment[local] = true
722             },
723             // Reading constants is allowed an arbitrary number of times
724             NonMutatingUse(NonMutatingUseContext::Copy) |
725             NonMutatingUse(NonMutatingUseContext::Move) |
726             NonMutatingUse(NonMutatingUseContext::Inspect) |
727             NonMutatingUse(NonMutatingUseContext::Projection) |
728             MutatingUse(MutatingUseContext::Projection) |
729             NonUse(_) => {},
730             _ => {
731                 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
732                 self.can_const_prop[local] = false;
733             },
734         }
735     }
736 }
737
738 impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> {
739     fn tcx(&self) -> TyCtxt<'tcx> {
740         self.tcx
741     }
742
743     fn visit_constant(
744         &mut self,
745         constant: &mut Constant<'tcx>,
746         location: Location,
747     ) {
748         trace!("visit_constant: {:?}", constant);
749         self.super_constant(constant, location);
750         self.eval_constant(constant);
751     }
752
753     fn visit_statement(
754         &mut self,
755         statement: &mut Statement<'tcx>,
756         location: Location,
757     ) {
758         trace!("visit_statement: {:?}", statement);
759         if let StatementKind::Assign(box(ref place, ref mut rval)) = statement.kind {
760             let place_ty: Ty<'tcx> = place
761                 .ty(&self.local_decls, self.tcx)
762                 .ty;
763             if let Ok(place_layout) = self.tcx.layout_of(self.param_env.and(place_ty)) {
764                 if let Some(local) = place.as_local() {
765                     let source = statement.source_info;
766                     if let Some(()) = self.const_prop(rval, place_layout, source, place) {
767                         if self.can_const_prop[local] {
768                             trace!("propagated into {:?}", local);
769
770                             if let Some(value) = self.get_const(local) {
771                                 if self.should_const_prop(value) {
772                                     trace!("replacing {:?} with {:?}", rval, value);
773                                     self.replace_with_const(
774                                         rval,
775                                         value,
776                                         statement.source_info,
777                                     );
778                                 }
779                             }
780                         } else {
781                             trace!("can't propagate into {:?}", local);
782                             if local != RETURN_PLACE {
783                                 self.remove_const(local);
784                             }
785                         }
786                     }
787                 }
788             }
789         } else {
790             match statement.kind {
791                 StatementKind::StorageLive(local) |
792                 StatementKind::StorageDead(local) if self.can_const_prop[local] => {
793                     let frame = self.ecx.frame_mut();
794                     frame.locals[local].value =
795                         if let StatementKind::StorageLive(_) = statement.kind {
796                             LocalValue::Uninitialized
797                         } else {
798                             LocalValue::Dead
799                         };
800                 }
801                 _ => {}
802             }
803         }
804
805         self.super_statement(statement, location);
806     }
807
808     fn visit_terminator(
809         &mut self,
810         terminator: &mut Terminator<'tcx>,
811         location: Location,
812     ) {
813         self.super_terminator(terminator, location);
814         let source_info = terminator.source_info;
815         match &mut terminator.kind {
816             TerminatorKind::Assert { expected, ref msg, ref mut cond, .. } => {
817                 if let Some(value) = self.eval_operand(&cond, source_info) {
818                     trace!("assertion on {:?} should be {:?}", value, expected);
819                     let expected = ScalarMaybeUndef::from(Scalar::from_bool(*expected));
820                     let value_const = self.ecx.read_scalar(value).unwrap();
821                     if expected != value_const {
822                         // poison all places this operand references so that further code
823                         // doesn't use the invalid value
824                         match cond {
825                             Operand::Move(ref place) | Operand::Copy(ref place) => {
826                                 if let PlaceBase::Local(local) = place.base {
827                                     self.remove_const(local);
828                                 }
829                             },
830                             Operand::Constant(_) => {}
831                         }
832                         let span = terminator.source_info.span;
833                         let hir_id = self
834                             .tcx
835                             .hir()
836                             .as_local_hir_id(self.source.def_id())
837                             .expect("some part of a failing const eval must be local");
838                         let msg = match msg {
839                             PanicInfo::Overflow(_) |
840                             PanicInfo::OverflowNeg |
841                             PanicInfo::DivisionByZero |
842                             PanicInfo::RemainderByZero =>
843                                 msg.description().to_owned(),
844                             PanicInfo::BoundsCheck { ref len, ref index } => {
845                                 let len = self
846                                     .eval_operand(len, source_info)
847                                     .expect("len must be const");
848                                 let len = match self.ecx.read_scalar(len) {
849                                     Ok(ScalarMaybeUndef::Scalar(Scalar::Raw {
850                                         data, ..
851                                     })) => data,
852                                     other => bug!("const len not primitive: {:?}", other),
853                                 };
854                                 let index = self
855                                     .eval_operand(index, source_info)
856                                     .expect("index must be const");
857                                 let index = match self.ecx.read_scalar(index) {
858                                     Ok(ScalarMaybeUndef::Scalar(Scalar::Raw {
859                                         data, ..
860                                     })) => data,
861                                     other => bug!("const index not primitive: {:?}", other),
862                                 };
863                                 format!(
864                                     "index out of bounds: \
865                                     the len is {} but the index is {}",
866                                     len,
867                                     index,
868                                 )
869                             },
870                             // Need proper const propagator for these
871                             _ => return,
872                         };
873                         self.tcx.lint_hir(
874                             ::rustc::lint::builtin::CONST_ERR,
875                             hir_id,
876                             span,
877                             &msg,
878                         );
879                     } else {
880                         if self.should_const_prop(value) {
881                             if let ScalarMaybeUndef::Scalar(scalar) = value_const {
882                                 *cond = self.operand_from_scalar(
883                                     scalar,
884                                     self.tcx.types.bool,
885                                     source_info.span,
886                                 );
887                             }
888                         }
889                     }
890                 }
891             },
892             TerminatorKind::SwitchInt { ref mut discr, switch_ty, .. } => {
893                 if let Some(value) = self.eval_operand(&discr, source_info) {
894                     if self.should_const_prop(value) {
895                         if let ScalarMaybeUndef::Scalar(scalar) =
896                                 self.ecx.read_scalar(value).unwrap() {
897                             *discr = self.operand_from_scalar(scalar, switch_ty, source_info.span);
898                         }
899                     }
900                 }
901             },
902             //none of these have Operands to const-propagate
903             TerminatorKind::Goto { .. } |
904             TerminatorKind::Resume |
905             TerminatorKind::Abort |
906             TerminatorKind::Return |
907             TerminatorKind::Unreachable |
908             TerminatorKind::Drop { .. } |
909             TerminatorKind::DropAndReplace { .. } |
910             TerminatorKind::Yield { .. } |
911             TerminatorKind::GeneratorDrop |
912             TerminatorKind::FalseEdges { .. } |
913             TerminatorKind::FalseUnwind { .. } => { }
914             //FIXME(wesleywiser) Call does have Operands that could be const-propagated
915             TerminatorKind::Call { .. } => { }
916         }
917     }
918 }