]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/const_prop.rs
807a7e88498b8bfe092968f70cdd725ee5bf84eb
[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::cell::Cell;
5
6 use rustc::hir::def::DefKind;
7 use rustc::mir::{
8     AggregateKind, Constant, Location, Place, PlaceBase, Body, Operand, Rvalue,
9     Local, NullOp, UnOp, StatementKind, Statement, LocalKind, Static, StaticKind,
10     TerminatorKind, Terminator,  ClearCrossCrate, SourceInfo, BinOp, ProjectionElem,
11     SourceScope, SourceScopeLocalData, LocalDecl, Promoted,
12 };
13 use rustc::mir::visit::{
14     Visitor, PlaceContext, MutatingUseContext, MutVisitor, NonMutatingUseContext,
15 };
16 use rustc::mir::interpret::{Scalar, GlobalId, InterpResult, InterpError, PanicInfo};
17 use rustc::ty::{self, Instance, ParamEnv, Ty, TyCtxt};
18 use syntax_pos::{Span, DUMMY_SP};
19 use rustc::ty::subst::InternalSubsts;
20 use rustc_data_structures::indexed_vec::IndexVec;
21 use rustc::ty::layout::{
22     LayoutOf, TyLayout, LayoutError, HasTyCtxt, TargetDataLayout, HasDataLayout, Size,
23 };
24
25 use crate::interpret::{
26     self, InterpCx, ScalarMaybeUndef, Immediate, OpTy,
27     ImmTy, MemoryKind, StackPopCleanup, LocalValue, LocalState,
28 };
29 use crate::const_eval::{
30     CompileTimeInterpreter, error_to_const_error, eval_promoted, mk_eval_cx,
31 };
32 use crate::transform::{MirPass, MirSource};
33
34 pub struct ConstProp;
35
36 impl MirPass for ConstProp {
37     fn run_pass<'tcx>(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>) {
38         // will be evaluated by miri and produce its errors there
39         if source.promoted.is_some() {
40             return;
41         }
42
43         use rustc::hir::map::blocks::FnLikeNode;
44         let hir_id = tcx.hir().as_local_hir_id(source.def_id())
45                               .expect("Non-local call to local provider is_const_fn");
46
47         let is_fn_like = FnLikeNode::from_node(tcx.hir().get(hir_id)).is_some();
48         let is_assoc_const = match tcx.def_kind(source.def_id()) {
49             Some(DefKind::AssocConst) => true,
50             _ => false,
51         };
52
53         // Only run const prop on functions, methods, closures and associated constants
54         if !is_fn_like && !is_assoc_const  {
55             // skip anon_const/statics/consts because they'll be evaluated by miri anyway
56             trace!("ConstProp skipped for {:?}", source.def_id());
57             return
58         }
59
60         trace!("ConstProp starting for {:?}", source.def_id());
61
62         // Steal some data we need from `body`.
63         let source_scope_local_data = std::mem::replace(
64             &mut body.source_scope_local_data,
65             ClearCrossCrate::Clear
66         );
67         let promoted = std::mem::replace(
68             &mut body.promoted,
69             IndexVec::new()
70         );
71
72         let dummy_body =
73             &Body::new(
74                 body.basic_blocks().clone(),
75                 Default::default(),
76                 ClearCrossCrate::Clear,
77                 Default::default(),
78                 None,
79                 body.local_decls.clone(),
80                 Default::default(),
81                 body.arg_count,
82                 Default::default(),
83                 tcx.def_span(source.def_id()),
84                 Default::default(),
85             );
86
87         // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
88         // constants, instead of just checking for const-folding succeeding.
89         // That would require an uniform one-def no-mutation analysis
90         // and RPO (or recursing when needing the value of a local).
91         let mut optimization_finder = ConstPropagator::new(
92             body,
93             dummy_body,
94             source_scope_local_data,
95             promoted,
96             tcx,
97             source
98         );
99         optimization_finder.visit_body(body);
100
101         // put back the data we stole from `mir`
102         let (source_scope_local_data, promoted) = optimization_finder.release_stolen_data();
103         std::mem::replace(
104             &mut body.source_scope_local_data,
105             source_scope_local_data
106         );
107         std::mem::replace(
108             &mut body.promoted,
109             promoted
110         );
111
112         trace!("ConstProp done for {:?}", source.def_id());
113     }
114 }
115
116 type Const<'tcx> = OpTy<'tcx>;
117
118 /// Finds optimization opportunities on the MIR.
119 struct ConstPropagator<'mir, 'tcx> {
120     ecx: InterpCx<'mir, 'tcx, CompileTimeInterpreter<'mir, 'tcx>>,
121     tcx: TyCtxt<'tcx>,
122     source: MirSource<'tcx>,
123     can_const_prop: IndexVec<Local, bool>,
124     param_env: ParamEnv<'tcx>,
125     source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
126     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
127     promoted: IndexVec<Promoted, Body<'tcx>>,
128 }
129
130 impl<'mir, 'tcx> LayoutOf for ConstPropagator<'mir, 'tcx> {
131     type Ty = Ty<'tcx>;
132     type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
133
134     fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
135         self.tcx.layout_of(self.param_env.and(ty))
136     }
137 }
138
139 impl<'mir, 'tcx> HasDataLayout for ConstPropagator<'mir, 'tcx> {
140     #[inline]
141     fn data_layout(&self) -> &TargetDataLayout {
142         &self.tcx.data_layout
143     }
144 }
145
146 impl<'mir, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'mir, 'tcx> {
147     #[inline]
148     fn tcx(&self) -> TyCtxt<'tcx> {
149         self.tcx
150     }
151 }
152
153 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
154     fn new(
155         body: &Body<'tcx>,
156         dummy_body: &'mir Body<'tcx>,
157         source_scope_local_data: ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
158         promoted: IndexVec<Promoted, Body<'tcx>>,
159         tcx: TyCtxt<'tcx>,
160         source: MirSource<'tcx>,
161     ) -> ConstPropagator<'mir, 'tcx> {
162         let def_id = source.def_id();
163         let param_env = tcx.param_env(def_id);
164         let span = tcx.def_span(def_id);
165         let mut ecx = mk_eval_cx(tcx, span, param_env);
166         let can_const_prop = CanConstProp::check(body);
167
168         ecx.push_stack_frame(
169             Instance::new(def_id, &InternalSubsts::identity_for_item(tcx, def_id)),
170             span,
171             dummy_body,
172             None,
173             StackPopCleanup::None {
174                 cleanup: false,
175             },
176         ).expect("failed to push initial stack frame");
177
178         ConstPropagator {
179             ecx,
180             tcx,
181             source,
182             param_env,
183             can_const_prop,
184             source_scope_local_data,
185             //FIXME(wesleywiser) we can't steal this because `Visitor::super_visit_body()` needs it
186             local_decls: body.local_decls.clone(),
187             promoted,
188         }
189     }
190
191     fn release_stolen_data(
192         self,
193     ) -> (
194         ClearCrossCrate<IndexVec<SourceScope, SourceScopeLocalData>>,
195         IndexVec<Promoted, Body<'tcx>>,
196     ) {
197         (self.source_scope_local_data, self.promoted)
198     }
199
200     fn get_const(&self, local: Local) -> Option<Const<'tcx>> {
201         let l = &self.ecx.frame().locals[local];
202
203         // If the local is `Unitialized` or `Dead` then we haven't propagated a value into it.
204         //
205         // `InterpCx::access_local()` mostly takes care of this for us however, for ZSTs,
206         // it will synthesize a value for us. In doing so, that will cause the
207         // `get_const(l).is_empty()` assert right before we call `set_const()` in `visit_statement`
208         // to fail.
209         if let LocalValue::Uninitialized | LocalValue::Dead = l.value {
210             return None;
211         }
212
213         self.ecx.access_local(self.ecx.frame(), local, None).ok()
214     }
215
216     fn set_const(&mut self, local: Local, c: Const<'tcx>) {
217         let frame = self.ecx.frame_mut();
218
219         if let Some(layout) = frame.locals[local].layout.get() {
220             debug_assert_eq!(c.layout, layout);
221         }
222
223         frame.locals[local] = LocalState {
224             value: LocalValue::Live(*c),
225             layout: Cell::new(Some(c.layout)),
226         };
227     }
228
229     fn remove_const(&mut self, local: Local) {
230         self.ecx.frame_mut().locals[local] = LocalState {
231             value: LocalValue::Uninitialized,
232             layout: Cell::new(None),
233         };
234     }
235
236     fn use_ecx<F, T>(
237         &mut self,
238         source_info: SourceInfo,
239         f: F
240     ) -> Option<T>
241     where
242         F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
243     {
244         self.ecx.tcx.span = source_info.span;
245         let lint_root = match self.source_scope_local_data {
246             ClearCrossCrate::Set(ref ivs) => {
247                 //FIXME(#51314): remove this check
248                 if source_info.scope.index() >= ivs.len() {
249                     return None;
250                 }
251                 ivs[source_info.scope].lint_root
252             },
253             ClearCrossCrate::Clear => return None,
254         };
255         let r = match f(self) {
256             Ok(val) => Some(val),
257             Err(error) => {
258                 let diagnostic = error_to_const_error(&self.ecx, error);
259                 use rustc::mir::interpret::InterpError::*;
260                 match diagnostic.error {
261                     Exit(_) => bug!("the CTFE program cannot exit"),
262                     | Unsupported(_) => {},
263                     | UndefinedBehaviour(_) => {},
264                     | InvalidProgram(_) => {},
265                     | ResourceExhaustion(_) => {},
266                     | Panic(_)
267                     => {
268                         diagnostic.report_as_lint(
269                             self.ecx.tcx,
270                             "this expression will panic at runtime",
271                             lint_root,
272                             None,
273                         );
274                     }
275                 }
276                 None
277             },
278         };
279         self.ecx.tcx.span = DUMMY_SP;
280         r
281     }
282
283     fn eval_constant(
284         &mut self,
285         c: &Constant<'tcx>,
286     ) -> Option<Const<'tcx>> {
287         self.ecx.tcx.span = c.span;
288         match self.ecx.eval_const_to_op(c.literal, None) {
289             Ok(op) => {
290                 Some(op)
291             },
292             Err(error) => {
293                 let err = error_to_const_error(&self.ecx, error);
294                 err.report_as_error(self.ecx.tcx, "erroneous constant used");
295                 None
296             },
297         }
298     }
299
300     fn eval_place(&mut self, place: &Place<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
301         trace!("eval_place(place={:?})", place);
302         place.iterate(|place_base, place_projection| {
303             let mut eval = match place_base {
304                 PlaceBase::Local(loc) => self.get_const(*loc).clone()?,
305                 PlaceBase::Static(box Static {kind: StaticKind::Promoted(promoted), ..}) => {
306                     let generics = self.tcx.generics_of(self.source.def_id());
307                     if generics.requires_monomorphization(self.tcx) {
308                         // FIXME: can't handle code with generics
309                         return None;
310                     }
311                     let substs = InternalSubsts::identity_for_item(self.tcx, self.source.def_id());
312                     let instance = Instance::new(self.source.def_id(), substs);
313                     let cid = GlobalId {
314                         instance,
315                         promoted: Some(*promoted),
316                     };
317                     // cannot use `const_eval` here, because that would require having the MIR
318                     // for the current function available, but we're producing said MIR right now
319                     let res = self.use_ecx(source_info, |this| {
320                         let body = &this.promoted[*promoted];
321                         eval_promoted(this.tcx, cid, body, this.param_env)
322                     })?;
323                     trace!("evaluated promoted {:?} to {:?}", promoted, res);
324                     res.into()
325                 }
326                 _ => return None,
327             };
328
329             for proj in place_projection {
330                 match proj.elem {
331                     ProjectionElem::Field(field, _) => {
332                         trace!("field proj on {:?}", proj.base);
333                         eval = self.use_ecx(source_info, |this| {
334                             this.ecx.operand_field(eval, field.index() as u64)
335                         })?;
336                     },
337                     ProjectionElem::Deref => {
338                         trace!("processing deref");
339                         eval = self.use_ecx(source_info, |this| {
340                             this.ecx.deref_operand(eval)
341                         })?.into();
342                     }
343                     // We could get more projections by using e.g., `operand_projection`,
344                     // but we do not even have the stack frame set up properly so
345                     // an `Index` projection would throw us off-track.
346                     _ => return None,
347                 }
348             }
349
350             Some(eval)
351         })
352     }
353
354     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
355         match *op {
356             Operand::Constant(ref c) => self.eval_constant(c),
357             | Operand::Move(ref place)
358             | Operand::Copy(ref place) => self.eval_place(place, source_info),
359         }
360     }
361
362     fn const_prop(
363         &mut self,
364         rvalue: &Rvalue<'tcx>,
365         place_layout: TyLayout<'tcx>,
366         source_info: SourceInfo,
367     ) -> Option<Const<'tcx>> {
368         let span = source_info.span;
369         match *rvalue {
370             Rvalue::Use(ref op) => {
371                 self.eval_operand(op, source_info)
372             },
373             Rvalue::Ref(_, _, ref place) => {
374                 let src = self.eval_place(place, source_info)?;
375                 let mplace = src.try_as_mplace().ok()?;
376                 Some(ImmTy::from_scalar(mplace.ptr.into(), place_layout).into())
377             },
378             Rvalue::Repeat(..) |
379             Rvalue::Aggregate(..) |
380             Rvalue::NullaryOp(NullOp::Box, _) |
381             Rvalue::Discriminant(..) => None,
382
383             Rvalue::Cast(kind, ref operand, _) => {
384                 let op = self.eval_operand(operand, source_info)?;
385                 self.use_ecx(source_info, |this| {
386                     let dest = this.ecx.allocate(place_layout, MemoryKind::Stack);
387                     this.ecx.cast(op, kind, dest.into())?;
388                     Ok(dest.into())
389                 })
390             },
391             Rvalue::Len(ref place) => {
392                 let place = self.eval_place(&place, source_info)?;
393                 let mplace = place.try_as_mplace().ok()?;
394
395                 if let ty::Slice(_) = mplace.layout.ty.sty {
396                     let len = mplace.meta.unwrap().to_usize(&self.ecx).unwrap();
397
398                     Some(ImmTy {
399                         imm: Immediate::Scalar(
400                             Scalar::from_uint(
401                                 len,
402                                 Size::from_bits(
403                                     self.tcx.sess.target.usize_ty.bit_width().unwrap() as u64
404                                 )
405                             ).into(),
406                         ),
407                         layout: self.tcx.layout_of(self.param_env.and(self.tcx.types.usize)).ok()?,
408                     }.into())
409                 } else {
410                     trace!("not slice: {:?}", mplace.layout.ty.sty);
411                     None
412                 }
413             },
414             Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
415                 type_size_of(self.tcx, self.param_env, ty).and_then(|n| Some(
416                     ImmTy {
417                         imm: Immediate::Scalar(
418                             Scalar::from_uint(n, self.tcx.data_layout.pointer_size).into()
419                         ),
420                         layout: self.tcx.layout_of(self.param_env.and(self.tcx.types.usize)).ok()?,
421                     }.into()
422                 ))
423             }
424             Rvalue::UnaryOp(op, ref arg) => {
425                 let def_id = if self.tcx.is_closure(self.source.def_id()) {
426                     self.tcx.closure_base_def_id(self.source.def_id())
427                 } else {
428                     self.source.def_id()
429                 };
430                 let generics = self.tcx.generics_of(def_id);
431                 if generics.requires_monomorphization(self.tcx) {
432                     // FIXME: can't handle code with generics
433                     return None;
434                 }
435
436                 let arg = self.eval_operand(arg, source_info)?;
437                 let val = self.use_ecx(source_info, |this| {
438                     let prim = this.ecx.read_immediate(arg)?;
439                     match op {
440                         UnOp::Neg => {
441                             // Need to do overflow check here: For actual CTFE, MIR
442                             // generation emits code that does this before calling the op.
443                             if prim.to_bits()? == (1 << (prim.layout.size.bits() - 1)) {
444                                 throw_panic!(OverflowNeg)
445                             }
446                         }
447                         UnOp::Not => {
448                             // Cannot overflow
449                         }
450                     }
451                     // Now run the actual operation.
452                     this.ecx.unary_op(op, prim)
453                 })?;
454                 let res = ImmTy {
455                     imm: Immediate::Scalar(val.into()),
456                     layout: place_layout,
457                 };
458                 Some(res.into())
459             }
460             Rvalue::CheckedBinaryOp(op, ref left, ref right) |
461             Rvalue::BinaryOp(op, ref left, ref right) => {
462                 trace!("rvalue binop {:?} for {:?} and {:?}", op, left, right);
463                 let right = self.eval_operand(right, source_info)?;
464                 let def_id = if self.tcx.is_closure(self.source.def_id()) {
465                     self.tcx.closure_base_def_id(self.source.def_id())
466                 } else {
467                     self.source.def_id()
468                 };
469                 let generics = self.tcx.generics_of(def_id);
470                 if generics.requires_monomorphization(self.tcx) {
471                     // FIXME: can't handle code with generics
472                     return None;
473                 }
474
475                 let r = self.use_ecx(source_info, |this| {
476                     this.ecx.read_immediate(right)
477                 })?;
478                 if op == BinOp::Shr || op == BinOp::Shl {
479                     let left_ty = left.ty(&self.local_decls, self.tcx);
480                     let left_bits = self
481                         .tcx
482                         .layout_of(self.param_env.and(left_ty))
483                         .unwrap()
484                         .size
485                         .bits();
486                     let right_size = right.layout.size;
487                     let r_bits = r.to_scalar().and_then(|r| r.to_bits(right_size));
488                     if r_bits.ok().map_or(false, |b| b >= left_bits as u128) {
489                         let source_scope_local_data = match self.source_scope_local_data {
490                             ClearCrossCrate::Set(ref data) => data,
491                             ClearCrossCrate::Clear => return None,
492                         };
493                         let dir = if op == BinOp::Shr {
494                             "right"
495                         } else {
496                             "left"
497                         };
498                         let hir_id = source_scope_local_data[source_info.scope].lint_root;
499                         self.tcx.lint_hir(
500                             ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
501                             hir_id,
502                             span,
503                             &format!("attempt to shift {} with overflow", dir));
504                         return None;
505                     }
506                 }
507                 let left = self.eval_operand(left, source_info)?;
508                 let l = self.use_ecx(source_info, |this| {
509                     this.ecx.read_immediate(left)
510                 })?;
511                 trace!("const evaluating {:?} for {:?} and {:?}", op, left, right);
512                 let (val, overflow) = self.use_ecx(source_info, |this| {
513                     this.ecx.binary_op(op, l, r)
514                 })?;
515                 let val = if let Rvalue::CheckedBinaryOp(..) = *rvalue {
516                     Immediate::ScalarPair(
517                         val.into(),
518                         Scalar::from_bool(overflow).into(),
519                     )
520                 } else {
521                     if overflow {
522                         let err = InterpError::Panic(PanicInfo::Overflow(op)).into();
523                         let _: Option<()> = self.use_ecx(source_info, |_| Err(err));
524                         return None;
525                     }
526                     Immediate::Scalar(val.into())
527                 };
528                 let res = ImmTy {
529                     imm: val,
530                     layout: place_layout,
531                 };
532                 Some(res.into())
533             },
534         }
535     }
536
537     fn operand_from_scalar(&self, scalar: Scalar, ty: Ty<'tcx>, span: Span) -> Operand<'tcx> {
538         Operand::Constant(Box::new(
539             Constant {
540                 span,
541                 ty,
542                 user_ty: None,
543                 literal: self.tcx.mk_const(*ty::Const::from_scalar(
544                     self.tcx,
545                     scalar,
546                     ty,
547                 ))
548             }
549         ))
550     }
551
552     fn replace_with_const(
553         &mut self,
554         rval: &mut Rvalue<'tcx>,
555         value: Const<'tcx>,
556         source_info: SourceInfo,
557     ) {
558         trace!("attepting to replace {:?} with {:?}", rval, value);
559         if let Err(e) = self.ecx.validate_operand(
560             value,
561             vec![],
562             // FIXME: is ref tracking too expensive?
563             Some(&mut interpret::RefTracking::empty()),
564         ) {
565             trace!("validation error, attempt failed: {:?}", e);
566             return;
567         }
568
569         // FIXME> figure out what tho do when try_read_immediate fails
570         let imm = self.use_ecx(source_info, |this| {
571             this.ecx.try_read_immediate(value)
572         });
573
574         if let Some(Ok(imm)) = imm {
575             match *imm {
576                 interpret::Immediate::Scalar(ScalarMaybeUndef::Scalar(scalar)) => {
577                     *rval = Rvalue::Use(
578                         self.operand_from_scalar(scalar, value.layout.ty, source_info.span));
579                 },
580                 Immediate::ScalarPair(
581                     ScalarMaybeUndef::Scalar(one),
582                     ScalarMaybeUndef::Scalar(two)
583                 ) => {
584                     let ty = &value.layout.ty.sty;
585                     if let ty::Tuple(substs) = ty {
586                         *rval = Rvalue::Aggregate(
587                             Box::new(AggregateKind::Tuple),
588                             vec![
589                                 self.operand_from_scalar(
590                                     one, substs[0].expect_ty(), source_info.span
591                                 ),
592                                 self.operand_from_scalar(
593                                     two, substs[1].expect_ty(), source_info.span
594                                 ),
595                             ],
596                         );
597                     }
598                 },
599                 _ => { }
600             }
601         }
602     }
603
604     fn should_const_prop(&self) -> bool {
605         self.tcx.sess.opts.debugging_opts.mir_opt_level >= 2
606     }
607 }
608
609 fn type_size_of<'tcx>(
610     tcx: TyCtxt<'tcx>,
611     param_env: ty::ParamEnv<'tcx>,
612     ty: Ty<'tcx>,
613 ) -> Option<u64> {
614     tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
615 }
616
617 struct CanConstProp {
618     can_const_prop: IndexVec<Local, bool>,
619     // false at the beginning, once set, there are not allowed to be any more assignments
620     found_assignment: IndexVec<Local, bool>,
621 }
622
623 impl CanConstProp {
624     /// returns true if `local` can be propagated
625     fn check(body: &Body<'_>) -> IndexVec<Local, bool> {
626         let mut cpv = CanConstProp {
627             can_const_prop: IndexVec::from_elem(true, &body.local_decls),
628             found_assignment: IndexVec::from_elem(false, &body.local_decls),
629         };
630         for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
631             // cannot use args at all
632             // cannot use locals because if x < y { y - x } else { x - y } would
633             //        lint for x != y
634             // FIXME(oli-obk): lint variables until they are used in a condition
635             // FIXME(oli-obk): lint if return value is constant
636             *val = body.local_kind(local) == LocalKind::Temp;
637
638             if !*val {
639                 trace!("local {:?} can't be propagated because it's not a temporary", local);
640             }
641         }
642         cpv.visit_body(body);
643         cpv.can_const_prop
644     }
645 }
646
647 impl<'tcx> Visitor<'tcx> for CanConstProp {
648     fn visit_local(
649         &mut self,
650         &local: &Local,
651         context: PlaceContext,
652         _: Location,
653     ) {
654         use rustc::mir::visit::PlaceContext::*;
655         match context {
656             // Constants must have at most one write
657             // FIXME(oli-obk): we could be more powerful here, if the multiple writes
658             // only occur in independent execution paths
659             MutatingUse(MutatingUseContext::Store) => if self.found_assignment[local] {
660                 trace!("local {:?} can't be propagated because of multiple assignments", local);
661                 self.can_const_prop[local] = false;
662             } else {
663                 self.found_assignment[local] = true
664             },
665             // Reading constants is allowed an arbitrary number of times
666             NonMutatingUse(NonMutatingUseContext::Copy) |
667             NonMutatingUse(NonMutatingUseContext::Move) |
668             NonMutatingUse(NonMutatingUseContext::Inspect) |
669             NonMutatingUse(NonMutatingUseContext::Projection) |
670             MutatingUse(MutatingUseContext::Projection) |
671             NonUse(_) => {},
672             _ => {
673                 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
674                 self.can_const_prop[local] = false;
675             },
676         }
677     }
678 }
679
680 impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> {
681     fn visit_constant(
682         &mut self,
683         constant: &mut Constant<'tcx>,
684         location: Location,
685     ) {
686         trace!("visit_constant: {:?}", constant);
687         self.super_constant(constant, location);
688         self.eval_constant(constant);
689     }
690
691     fn visit_statement(
692         &mut self,
693         statement: &mut Statement<'tcx>,
694         location: Location,
695     ) {
696         trace!("visit_statement: {:?}", statement);
697         if let StatementKind::Assign(ref place, ref mut rval) = statement.kind {
698             let place_ty: Ty<'tcx> = place
699                 .ty(&self.local_decls, self.tcx)
700                 .ty;
701             if let Ok(place_layout) = self.tcx.layout_of(self.param_env.and(place_ty)) {
702                 if let Some(value) = self.const_prop(rval, place_layout, statement.source_info) {
703                     if let Place {
704                         base: PlaceBase::Local(local),
705                         projection: None,
706                     } = *place {
707                         trace!("checking whether {:?} can be stored to {:?}", value, local);
708                         if self.can_const_prop[local] {
709                             trace!("storing {:?} to {:?}", value, local);
710                             assert!(self.get_const(local).is_none());
711                             self.set_const(local, value);
712
713                             if self.should_const_prop() {
714                                 self.replace_with_const(
715                                     rval,
716                                     value,
717                                     statement.source_info,
718                                 );
719                             }
720                         }
721                     }
722                 }
723             }
724         }
725         self.super_statement(statement, location);
726     }
727
728     fn visit_terminator(
729         &mut self,
730         terminator: &mut Terminator<'tcx>,
731         location: Location,
732     ) {
733         self.super_terminator(terminator, location);
734         let source_info = terminator.source_info;
735         match &mut terminator.kind {
736             TerminatorKind::Assert { expected, ref msg, ref mut cond, .. } => {
737                 if let Some(value) = self.eval_operand(&cond, source_info) {
738                     trace!("assertion on {:?} should be {:?}", value, expected);
739                     let expected = ScalarMaybeUndef::from(Scalar::from_bool(*expected));
740                     let value_const = self.ecx.read_scalar(value).unwrap();
741                     if expected != value_const {
742                         // poison all places this operand references so that further code
743                         // doesn't use the invalid value
744                         match cond {
745                             Operand::Move(ref place) | Operand::Copy(ref place) => {
746                                 if let PlaceBase::Local(local) = place.base {
747                                     self.remove_const(local);
748                                 }
749                             },
750                             Operand::Constant(_) => {}
751                         }
752                         let span = terminator.source_info.span;
753                         let hir_id = self
754                             .tcx
755                             .hir()
756                             .as_local_hir_id(self.source.def_id())
757                             .expect("some part of a failing const eval must be local");
758                         let msg = match msg {
759                             PanicInfo::Overflow(_) |
760                             PanicInfo::OverflowNeg |
761                             PanicInfo::DivisionByZero |
762                             PanicInfo::RemainderByZero =>
763                                 msg.description().to_owned(),
764                             PanicInfo::BoundsCheck { ref len, ref index } => {
765                                 let len = self
766                                     .eval_operand(len, source_info)
767                                     .expect("len must be const");
768                                 let len = match self.ecx.read_scalar(len) {
769                                     Ok(ScalarMaybeUndef::Scalar(Scalar::Raw {
770                                         data, ..
771                                     })) => data,
772                                     other => bug!("const len not primitive: {:?}", other),
773                                 };
774                                 let index = self
775                                     .eval_operand(index, source_info)
776                                     .expect("index must be const");
777                                 let index = match self.ecx.read_scalar(index) {
778                                     Ok(ScalarMaybeUndef::Scalar(Scalar::Raw {
779                                         data, ..
780                                     })) => data,
781                                     other => bug!("const index not primitive: {:?}", other),
782                                 };
783                                 format!(
784                                     "index out of bounds: \
785                                     the len is {} but the index is {}",
786                                     len,
787                                     index,
788                                 )
789                             },
790                             // Need proper const propagator for these
791                             _ => return,
792                         };
793                         self.tcx.lint_hir(
794                             ::rustc::lint::builtin::CONST_ERR,
795                             hir_id,
796                             span,
797                             &msg,
798                         );
799                     } else {
800                         if self.should_const_prop() {
801                             if let ScalarMaybeUndef::Scalar(scalar) = value_const {
802                                 *cond = self.operand_from_scalar(
803                                     scalar,
804                                     self.tcx.types.bool,
805                                     source_info.span,
806                                 );
807                             }
808                         }
809                     }
810                 }
811             },
812             TerminatorKind::SwitchInt { ref mut discr, switch_ty, .. } => {
813                 if self.should_const_prop() {
814                     if let Some(value) = self.eval_operand(&discr, source_info) {
815                         if let ScalarMaybeUndef::Scalar(scalar) =
816                                 self.ecx.read_scalar(value).unwrap() {
817                             *discr = self.operand_from_scalar(scalar, switch_ty, source_info.span);
818                         }
819                     }
820                 }
821             },
822             //none of these have Operands to const-propagate
823             TerminatorKind::Goto { .. } |
824             TerminatorKind::Resume |
825             TerminatorKind::Abort |
826             TerminatorKind::Return |
827             TerminatorKind::Unreachable |
828             TerminatorKind::Drop { .. } |
829             TerminatorKind::DropAndReplace { .. } |
830             TerminatorKind::Yield { .. } |
831             TerminatorKind::GeneratorDrop |
832             TerminatorKind::FalseEdges { .. } |
833             TerminatorKind::FalseUnwind { .. } => { }
834             //FIXME(wesleywiser) Call does have Operands that could be const-propagated
835             TerminatorKind::Call { .. } => { }
836         }
837     }
838 }