]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/const_prop.rs
[const-prop] Replace `Cast` handling with use of `InterpCx`
[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,
10     TerminatorKind, Terminator,  ClearCrossCrate, SourceInfo, BinOp,
11     SourceScope, SourceScopeLocalData, LocalDecl,
12 };
13 use rustc::mir::visit::{
14     Visitor, PlaceContext, MutatingUseContext, MutVisitor, NonMutatingUseContext,
15 };
16 use rustc::mir::interpret::{Scalar, 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, StackPopCleanup, LocalValue, LocalState,
28 };
29 use crate::const_eval::{
30     CompileTimeInterpreter, error_to_const_error, 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                 use rustc::mir::interpret::InterpError::*;
241                 match error.kind {
242                     Exit(_) => bug!("the CTFE program cannot exit"),
243                     Unsupported(_)
244                     | UndefinedBehavior(_)
245                     | InvalidProgram(_)
246                     | ResourceExhaustion(_) => {
247                         // Ignore these errors.
248                     }
249                     Panic(_) => {
250                         let diagnostic = error_to_const_error(&self.ecx, error);
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         self.use_ecx(source_info, |this| {
286             this.ecx.eval_place_to_op(place, None)
287         })
288     }
289
290     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
291         match *op {
292             Operand::Constant(ref c) => self.eval_constant(c),
293             | Operand::Move(ref place)
294             | Operand::Copy(ref place) => self.eval_place(place, source_info),
295         }
296     }
297
298     fn const_prop(
299         &mut self,
300         rvalue: &Rvalue<'tcx>,
301         place_layout: TyLayout<'tcx>,
302         source_info: SourceInfo,
303         place: &Place<'tcx>,
304     ) -> Option<Const<'tcx>> {
305         let span = source_info.span;
306         match *rvalue {
307             Rvalue::Use(_) |
308             Rvalue::Len(_) |
309             Rvalue::Cast(..) => {
310                 self.use_ecx(source_info, |this| {
311                     this.ecx.eval_rvalue_into_place(rvalue, place)?;
312                     this.ecx.eval_place_to_op(place, Some(place_layout))
313                 })
314             },
315             Rvalue::Ref(_, _, ref place) => {
316                 let src = self.eval_place(place, source_info)?;
317                 let mplace = src.try_as_mplace().ok()?;
318                 Some(ImmTy::from_scalar(mplace.ptr.into(), place_layout).into())
319             },
320             Rvalue::Repeat(..) |
321             Rvalue::Aggregate(..) |
322             Rvalue::NullaryOp(NullOp::Box, _) |
323             Rvalue::Discriminant(..) => None,
324
325             Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
326                 type_size_of(self.tcx, self.param_env, ty).and_then(|n| Some(
327                     ImmTy::from_uint(
328                         n,
329                         self.tcx.layout_of(self.param_env.and(self.tcx.types.usize)).ok()?,
330                     ).into()
331                 ))
332             }
333             Rvalue::UnaryOp(op, ref arg) => {
334                 let def_id = if self.tcx.is_closure(self.source.def_id()) {
335                     self.tcx.closure_base_def_id(self.source.def_id())
336                 } else {
337                     self.source.def_id()
338                 };
339                 let generics = self.tcx.generics_of(def_id);
340                 if generics.requires_monomorphization(self.tcx) {
341                     // FIXME: can't handle code with generics
342                     return None;
343                 }
344
345                 let arg = self.eval_operand(arg, source_info)?;
346                 let oflo_check = self.tcx.sess.overflow_checks();
347                 let val = self.use_ecx(source_info, |this| {
348                     let prim = this.ecx.read_immediate(arg)?;
349                     match op {
350                         UnOp::Neg => {
351                             // We check overflow in debug mode already
352                             // so should only check in release mode.
353                             if !oflo_check
354                             && prim.layout.ty.is_signed()
355                             && prim.to_bits()? == (1 << (prim.layout.size.bits() - 1)) {
356                                 throw_panic!(OverflowNeg)
357                             }
358                         }
359                         UnOp::Not => {
360                             // Cannot overflow
361                         }
362                     }
363                     // Now run the actual operation.
364                     this.ecx.unary_op(op, prim)
365                 })?;
366                 Some(val.into())
367             }
368             Rvalue::CheckedBinaryOp(op, ref left, ref right) |
369             Rvalue::BinaryOp(op, ref left, ref right) => {
370                 trace!("rvalue binop {:?} for {:?} and {:?}", op, left, right);
371                 let right = self.eval_operand(right, source_info)?;
372                 let def_id = if self.tcx.is_closure(self.source.def_id()) {
373                     self.tcx.closure_base_def_id(self.source.def_id())
374                 } else {
375                     self.source.def_id()
376                 };
377                 let generics = self.tcx.generics_of(def_id);
378                 if generics.requires_monomorphization(self.tcx) {
379                     // FIXME: can't handle code with generics
380                     return None;
381                 }
382
383                 let r = self.use_ecx(source_info, |this| {
384                     this.ecx.read_immediate(right)
385                 })?;
386                 if op == BinOp::Shr || op == BinOp::Shl {
387                     let left_ty = left.ty(&self.local_decls, self.tcx);
388                     let left_bits = self
389                         .tcx
390                         .layout_of(self.param_env.and(left_ty))
391                         .unwrap()
392                         .size
393                         .bits();
394                     let right_size = right.layout.size;
395                     let r_bits = r.to_scalar().and_then(|r| r.to_bits(right_size));
396                     if r_bits.ok().map_or(false, |b| b >= left_bits as u128) {
397                         let source_scope_local_data = match self.source_scope_local_data {
398                             ClearCrossCrate::Set(ref data) => data,
399                             ClearCrossCrate::Clear => return None,
400                         };
401                         let dir = if op == BinOp::Shr {
402                             "right"
403                         } else {
404                             "left"
405                         };
406                         let hir_id = source_scope_local_data[source_info.scope].lint_root;
407                         self.tcx.lint_hir(
408                             ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
409                             hir_id,
410                             span,
411                             &format!("attempt to shift {} with overflow", dir));
412                         return None;
413                     }
414                 }
415                 let left = self.eval_operand(left, source_info)?;
416                 let l = self.use_ecx(source_info, |this| {
417                     this.ecx.read_immediate(left)
418                 })?;
419                 trace!("const evaluating {:?} for {:?} and {:?}", op, left, right);
420                 let (val, overflow, _ty) = self.use_ecx(source_info, |this| {
421                     this.ecx.overflowing_binary_op(op, l, r)
422                 })?;
423                 let val = if let Rvalue::CheckedBinaryOp(..) = *rvalue {
424                     Immediate::ScalarPair(
425                         val.into(),
426                         Scalar::from_bool(overflow).into(),
427                     )
428                 } else {
429                     // We check overflow in debug mode already
430                     // so should only check in release mode.
431                     if !self.tcx.sess.overflow_checks() && overflow {
432                         let err = err_panic!(Overflow(op)).into();
433                         let _: Option<()> = self.use_ecx(source_info, |_| Err(err));
434                         return None;
435                     }
436                     Immediate::Scalar(val.into())
437                 };
438                 let res = ImmTy {
439                     imm: val,
440                     layout: place_layout,
441                 };
442                 Some(res.into())
443             },
444         }
445     }
446
447     fn operand_from_scalar(&self, scalar: Scalar, ty: Ty<'tcx>, span: Span) -> Operand<'tcx> {
448         Operand::Constant(Box::new(
449             Constant {
450                 span,
451                 user_ty: None,
452                 literal: self.tcx.mk_const(*ty::Const::from_scalar(
453                     self.tcx,
454                     scalar,
455                     ty,
456                 ))
457             }
458         ))
459     }
460
461     fn replace_with_const(
462         &mut self,
463         rval: &mut Rvalue<'tcx>,
464         value: Const<'tcx>,
465         source_info: SourceInfo,
466     ) {
467         trace!("attepting to replace {:?} with {:?}", rval, value);
468         if let Err(e) = self.ecx.validate_operand(
469             value,
470             vec![],
471             // FIXME: is ref tracking too expensive?
472             Some(&mut interpret::RefTracking::empty()),
473         ) {
474             trace!("validation error, attempt failed: {:?}", e);
475             return;
476         }
477
478         // FIXME> figure out what tho do when try_read_immediate fails
479         let imm = self.use_ecx(source_info, |this| {
480             this.ecx.try_read_immediate(value)
481         });
482
483         if let Some(Ok(imm)) = imm {
484             match *imm {
485                 interpret::Immediate::Scalar(ScalarMaybeUndef::Scalar(scalar)) => {
486                     *rval = Rvalue::Use(
487                         self.operand_from_scalar(scalar, value.layout.ty, source_info.span));
488                 },
489                 Immediate::ScalarPair(
490                     ScalarMaybeUndef::Scalar(one),
491                     ScalarMaybeUndef::Scalar(two)
492                 ) => {
493                     let ty = &value.layout.ty.kind;
494                     if let ty::Tuple(substs) = ty {
495                         *rval = Rvalue::Aggregate(
496                             Box::new(AggregateKind::Tuple),
497                             vec![
498                                 self.operand_from_scalar(
499                                     one, substs[0].expect_ty(), source_info.span
500                                 ),
501                                 self.operand_from_scalar(
502                                     two, substs[1].expect_ty(), source_info.span
503                                 ),
504                             ],
505                         );
506                     }
507                 },
508                 _ => { }
509             }
510         }
511     }
512
513     fn should_const_prop(&self) -> bool {
514         self.tcx.sess.opts.debugging_opts.mir_opt_level >= 2
515     }
516 }
517
518 fn type_size_of<'tcx>(
519     tcx: TyCtxt<'tcx>,
520     param_env: ty::ParamEnv<'tcx>,
521     ty: Ty<'tcx>,
522 ) -> Option<u64> {
523     tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
524 }
525
526 struct CanConstProp {
527     can_const_prop: IndexVec<Local, bool>,
528     // false at the beginning, once set, there are not allowed to be any more assignments
529     found_assignment: IndexVec<Local, bool>,
530 }
531
532 impl CanConstProp {
533     /// returns true if `local` can be propagated
534     fn check(body: &Body<'_>) -> IndexVec<Local, bool> {
535         let mut cpv = CanConstProp {
536             can_const_prop: IndexVec::from_elem(true, &body.local_decls),
537             found_assignment: IndexVec::from_elem(false, &body.local_decls),
538         };
539         for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
540             // cannot use args at all
541             // cannot use locals because if x < y { y - x } else { x - y } would
542             //        lint for x != y
543             // FIXME(oli-obk): lint variables until they are used in a condition
544             // FIXME(oli-obk): lint if return value is constant
545             *val = body.local_kind(local) == LocalKind::Temp;
546
547             if !*val {
548                 trace!("local {:?} can't be propagated because it's not a temporary", local);
549             }
550         }
551         cpv.visit_body(body);
552         cpv.can_const_prop
553     }
554 }
555
556 impl<'tcx> Visitor<'tcx> for CanConstProp {
557     fn visit_local(
558         &mut self,
559         &local: &Local,
560         context: PlaceContext,
561         _: Location,
562     ) {
563         use rustc::mir::visit::PlaceContext::*;
564         match context {
565             // Constants must have at most one write
566             // FIXME(oli-obk): we could be more powerful here, if the multiple writes
567             // only occur in independent execution paths
568             MutatingUse(MutatingUseContext::Store) => if self.found_assignment[local] {
569                 trace!("local {:?} can't be propagated because of multiple assignments", local);
570                 self.can_const_prop[local] = false;
571             } else {
572                 self.found_assignment[local] = true
573             },
574             // Reading constants is allowed an arbitrary number of times
575             NonMutatingUse(NonMutatingUseContext::Copy) |
576             NonMutatingUse(NonMutatingUseContext::Move) |
577             NonMutatingUse(NonMutatingUseContext::Inspect) |
578             NonMutatingUse(NonMutatingUseContext::Projection) |
579             MutatingUse(MutatingUseContext::Projection) |
580             NonUse(_) => {},
581             _ => {
582                 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
583                 self.can_const_prop[local] = false;
584             },
585         }
586     }
587 }
588
589 impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> {
590     fn visit_constant(
591         &mut self,
592         constant: &mut Constant<'tcx>,
593         location: Location,
594     ) {
595         trace!("visit_constant: {:?}", constant);
596         self.super_constant(constant, location);
597         self.eval_constant(constant);
598     }
599
600     fn visit_statement(
601         &mut self,
602         statement: &mut Statement<'tcx>,
603         location: Location,
604     ) {
605         trace!("visit_statement: {:?}", statement);
606         if let StatementKind::Assign(box(ref place, ref mut rval)) = statement.kind {
607             let place_ty: Ty<'tcx> = place
608                 .ty(&self.local_decls, self.tcx)
609                 .ty;
610             if let Ok(place_layout) = self.tcx.layout_of(self.param_env.and(place_ty)) {
611                 if let Place {
612                     base: PlaceBase::Local(local),
613                     projection: box [],
614                 } = *place {
615                     if let Some(value) = self.const_prop(rval, place_layout, statement.source_info, place) {
616                         trace!("checking whether {:?} can be stored to {:?}", value, local);
617                         if self.can_const_prop[local] {
618                             trace!("storing {:?} to {:?}", value, local);
619                             assert!(self.get_const(local).is_none() || self.get_const(local) == Some(value));
620                             self.set_const(local, value);
621
622                             if self.should_const_prop() {
623                                 self.replace_with_const(
624                                     rval,
625                                     value,
626                                     statement.source_info,
627                                 );
628                             }
629                         }
630                     }
631                 }
632             }
633         } else if let StatementKind::StorageLive(local) = statement.kind {
634             if self.can_const_prop[local] {
635                 let frame = self.ecx.frame_mut();
636
637                 frame.locals[local].value = LocalValue::Uninitialized;
638             }
639         } else if let StatementKind::StorageDead(local) = statement.kind {
640             if self.can_const_prop[local] {
641                 let frame = self.ecx.frame_mut();
642
643                 frame.locals[local].value = LocalValue::Dead;
644             }
645         }
646         self.super_statement(statement, location);
647     }
648
649     fn visit_terminator(
650         &mut self,
651         terminator: &mut Terminator<'tcx>,
652         location: Location,
653     ) {
654         self.super_terminator(terminator, location);
655         let source_info = terminator.source_info;
656         match &mut terminator.kind {
657             TerminatorKind::Assert { expected, ref msg, ref mut cond, .. } => {
658                 if let Some(value) = self.eval_operand(&cond, source_info) {
659                     trace!("assertion on {:?} should be {:?}", value, expected);
660                     let expected = ScalarMaybeUndef::from(Scalar::from_bool(*expected));
661                     let value_const = self.ecx.read_scalar(value).unwrap();
662                     if expected != value_const {
663                         // poison all places this operand references so that further code
664                         // doesn't use the invalid value
665                         match cond {
666                             Operand::Move(ref place) | Operand::Copy(ref place) => {
667                                 if let PlaceBase::Local(local) = place.base {
668                                     self.remove_const(local);
669                                 }
670                             },
671                             Operand::Constant(_) => {}
672                         }
673                         let span = terminator.source_info.span;
674                         let hir_id = self
675                             .tcx
676                             .hir()
677                             .as_local_hir_id(self.source.def_id())
678                             .expect("some part of a failing const eval must be local");
679                         let msg = match msg {
680                             PanicInfo::Overflow(_) |
681                             PanicInfo::OverflowNeg |
682                             PanicInfo::DivisionByZero |
683                             PanicInfo::RemainderByZero =>
684                                 msg.description().to_owned(),
685                             PanicInfo::BoundsCheck { ref len, ref index } => {
686                                 let len = self
687                                     .eval_operand(len, source_info)
688                                     .expect("len must be const");
689                                 let len = match self.ecx.read_scalar(len) {
690                                     Ok(ScalarMaybeUndef::Scalar(Scalar::Raw {
691                                         data, ..
692                                     })) => data,
693                                     other => bug!("const len not primitive: {:?}", other),
694                                 };
695                                 let index = self
696                                     .eval_operand(index, source_info)
697                                     .expect("index must be const");
698                                 let index = match self.ecx.read_scalar(index) {
699                                     Ok(ScalarMaybeUndef::Scalar(Scalar::Raw {
700                                         data, ..
701                                     })) => data,
702                                     other => bug!("const index not primitive: {:?}", other),
703                                 };
704                                 format!(
705                                     "index out of bounds: \
706                                     the len is {} but the index is {}",
707                                     len,
708                                     index,
709                                 )
710                             },
711                             // Need proper const propagator for these
712                             _ => return,
713                         };
714                         self.tcx.lint_hir(
715                             ::rustc::lint::builtin::CONST_ERR,
716                             hir_id,
717                             span,
718                             &msg,
719                         );
720                     } else {
721                         if self.should_const_prop() {
722                             if let ScalarMaybeUndef::Scalar(scalar) = value_const {
723                                 *cond = self.operand_from_scalar(
724                                     scalar,
725                                     self.tcx.types.bool,
726                                     source_info.span,
727                                 );
728                             }
729                         }
730                     }
731                 }
732             },
733             TerminatorKind::SwitchInt { ref mut discr, switch_ty, .. } => {
734                 if self.should_const_prop() {
735                     if let Some(value) = self.eval_operand(&discr, source_info) {
736                         if let ScalarMaybeUndef::Scalar(scalar) =
737                                 self.ecx.read_scalar(value).unwrap() {
738                             *discr = self.operand_from_scalar(scalar, switch_ty, source_info.span);
739                         }
740                     }
741                 }
742             },
743             //none of these have Operands to const-propagate
744             TerminatorKind::Goto { .. } |
745             TerminatorKind::Resume |
746             TerminatorKind::Abort |
747             TerminatorKind::Return |
748             TerminatorKind::Unreachable |
749             TerminatorKind::Drop { .. } |
750             TerminatorKind::DropAndReplace { .. } |
751             TerminatorKind::Yield { .. } |
752             TerminatorKind::GeneratorDrop |
753             TerminatorKind::FalseEdges { .. } |
754             TerminatorKind::FalseUnwind { .. } => { }
755             //FIXME(wesleywiser) Call does have Operands that could be const-propagated
756             TerminatorKind::Call { .. } => { }
757         }
758     }
759 }