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