]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/const_prop.rs
9918356d355b84858937098c83c37a50fa347649
[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, PanicMessage};
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                 use rustc::mir::interpret::UnsupportedInfo::*;
261                 match diagnostic.error {
262                     Exit(_) => {},
263
264                     | Unsupported(OutOfTls)
265                     | Unsupported(TlsOutOfBounds)
266                     | Unsupported(PathNotFound(_))
267                     => bug!("these should not be in rustc, but in miri's machine errors"),
268
269                     | Unsupported(_) => {},
270                     | UndefinedBehaviour(_) => {},
271                     | InvalidProgram(_) => {},
272                     | ResourceExhaustion(_) => {},
273                     | Panic(_)
274                     => {
275                         diagnostic.report_as_lint(
276                             self.ecx.tcx,
277                             "this expression will panic at runtime",
278                             lint_root,
279                             None,
280                         );
281                     }
282                 }
283                 None
284             },
285         };
286         self.ecx.tcx.span = DUMMY_SP;
287         r
288     }
289
290     fn eval_constant(
291         &mut self,
292         c: &Constant<'tcx>,
293     ) -> Option<Const<'tcx>> {
294         self.ecx.tcx.span = c.span;
295         match self.ecx.eval_const_to_op(c.literal, None) {
296             Ok(op) => {
297                 Some(op)
298             },
299             Err(error) => {
300                 let err = error_to_const_error(&self.ecx, error);
301                 err.report_as_error(self.ecx.tcx, "erroneous constant used");
302                 None
303             },
304         }
305     }
306
307     fn eval_place(&mut self, place: &Place<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
308         trace!("eval_place(place={:?})", place);
309         place.iterate(|place_base, place_projection| {
310             let mut eval = match place_base {
311                 PlaceBase::Local(loc) => self.get_const(*loc).clone()?,
312                 PlaceBase::Static(box Static {kind: StaticKind::Promoted(promoted), ..}) => {
313                     let generics = self.tcx.generics_of(self.source.def_id());
314                     if generics.requires_monomorphization(self.tcx) {
315                         // FIXME: can't handle code with generics
316                         return None;
317                     }
318                     let substs = InternalSubsts::identity_for_item(self.tcx, self.source.def_id());
319                     let instance = Instance::new(self.source.def_id(), substs);
320                     let cid = GlobalId {
321                         instance,
322                         promoted: Some(*promoted),
323                     };
324                     // cannot use `const_eval` here, because that would require having the MIR
325                     // for the current function available, but we're producing said MIR right now
326                     let res = self.use_ecx(source_info, |this| {
327                         let body = &this.promoted[*promoted];
328                         eval_promoted(this.tcx, cid, body, this.param_env)
329                     })?;
330                     trace!("evaluated promoted {:?} to {:?}", promoted, res);
331                     res.into()
332                 }
333                 _ => return None,
334             };
335
336             for proj in place_projection {
337                 match proj.elem {
338                     ProjectionElem::Field(field, _) => {
339                         trace!("field proj on {:?}", proj.base);
340                         eval = self.use_ecx(source_info, |this| {
341                             this.ecx.operand_field(eval, field.index() as u64)
342                         })?;
343                     },
344                     ProjectionElem::Deref => {
345                         trace!("processing deref");
346                         eval = self.use_ecx(source_info, |this| {
347                             this.ecx.deref_operand(eval)
348                         })?.into();
349                     }
350                     // We could get more projections by using e.g., `operand_projection`,
351                     // but we do not even have the stack frame set up properly so
352                     // an `Index` projection would throw us off-track.
353                     _ => return None,
354                 }
355             }
356
357             Some(eval)
358         })
359     }
360
361     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
362         match *op {
363             Operand::Constant(ref c) => self.eval_constant(c),
364             | Operand::Move(ref place)
365             | Operand::Copy(ref place) => self.eval_place(place, source_info),
366         }
367     }
368
369     fn const_prop(
370         &mut self,
371         rvalue: &Rvalue<'tcx>,
372         place_layout: TyLayout<'tcx>,
373         source_info: SourceInfo,
374     ) -> Option<Const<'tcx>> {
375         let span = source_info.span;
376         match *rvalue {
377             Rvalue::Use(ref op) => {
378                 self.eval_operand(op, source_info)
379             },
380             Rvalue::Ref(_, _, ref place) => {
381                 let src = self.eval_place(place, source_info)?;
382                 let mplace = src.try_as_mplace().ok()?;
383                 Some(ImmTy::from_scalar(mplace.ptr.into(), place_layout).into())
384             },
385             Rvalue::Repeat(..) |
386             Rvalue::Aggregate(..) |
387             Rvalue::NullaryOp(NullOp::Box, _) |
388             Rvalue::Discriminant(..) => None,
389
390             Rvalue::Cast(kind, ref operand, _) => {
391                 let op = self.eval_operand(operand, source_info)?;
392                 self.use_ecx(source_info, |this| {
393                     let dest = this.ecx.allocate(place_layout, MemoryKind::Stack);
394                     this.ecx.cast(op, kind, dest.into())?;
395                     Ok(dest.into())
396                 })
397             },
398             Rvalue::Len(ref place) => {
399                 let place = self.eval_place(&place, source_info)?;
400                 let mplace = place.try_as_mplace().ok()?;
401
402                 if let ty::Slice(_) = mplace.layout.ty.sty {
403                     let len = mplace.meta.unwrap().to_usize(&self.ecx).unwrap();
404
405                     Some(ImmTy {
406                         imm: Immediate::Scalar(
407                             Scalar::from_uint(
408                                 len,
409                                 Size::from_bits(
410                                     self.tcx.sess.target.usize_ty.bit_width().unwrap() as u64
411                                 )
412                             ).into(),
413                         ),
414                         layout: self.tcx.layout_of(self.param_env.and(self.tcx.types.usize)).ok()?,
415                     }.into())
416                 } else {
417                     trace!("not slice: {:?}", mplace.layout.ty.sty);
418                     None
419                 }
420             },
421             Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
422                 type_size_of(self.tcx, self.param_env, ty).and_then(|n| Some(
423                     ImmTy {
424                         imm: Immediate::Scalar(
425                             Scalar::from_uint(n, self.tcx.data_layout.pointer_size).into()
426                         ),
427                         layout: self.tcx.layout_of(self.param_env.and(self.tcx.types.usize)).ok()?,
428                     }.into()
429                 ))
430             }
431             Rvalue::UnaryOp(op, ref arg) => {
432                 let def_id = if self.tcx.is_closure(self.source.def_id()) {
433                     self.tcx.closure_base_def_id(self.source.def_id())
434                 } else {
435                     self.source.def_id()
436                 };
437                 let generics = self.tcx.generics_of(def_id);
438                 if generics.requires_monomorphization(self.tcx) {
439                     // FIXME: can't handle code with generics
440                     return None;
441                 }
442
443                 let arg = self.eval_operand(arg, source_info)?;
444                 let val = self.use_ecx(source_info, |this| {
445                     let prim = this.ecx.read_immediate(arg)?;
446                     match op {
447                         UnOp::Neg => {
448                             // Need to do overflow check here: For actual CTFE, MIR
449                             // generation emits code that does this before calling the op.
450                             if prim.to_bits()? == (1 << (prim.layout.size.bits() - 1)) {
451                                 return err_panic!(OverflowNeg);
452                             }
453                         }
454                         UnOp::Not => {
455                             // Cannot overflow
456                         }
457                     }
458                     // Now run the actual operation.
459                     this.ecx.unary_op(op, prim)
460                 })?;
461                 let res = ImmTy {
462                     imm: Immediate::Scalar(val.into()),
463                     layout: place_layout,
464                 };
465                 Some(res.into())
466             }
467             Rvalue::CheckedBinaryOp(op, ref left, ref right) |
468             Rvalue::BinaryOp(op, ref left, ref right) => {
469                 trace!("rvalue binop {:?} for {:?} and {:?}", op, left, right);
470                 let right = self.eval_operand(right, source_info)?;
471                 let def_id = if self.tcx.is_closure(self.source.def_id()) {
472                     self.tcx.closure_base_def_id(self.source.def_id())
473                 } else {
474                     self.source.def_id()
475                 };
476                 let generics = self.tcx.generics_of(def_id);
477                 if generics.requires_monomorphization(self.tcx) {
478                     // FIXME: can't handle code with generics
479                     return None;
480                 }
481
482                 let r = self.use_ecx(source_info, |this| {
483                     this.ecx.read_immediate(right)
484                 })?;
485                 if op == BinOp::Shr || op == BinOp::Shl {
486                     let left_ty = left.ty(&self.local_decls, self.tcx);
487                     let left_bits = self
488                         .tcx
489                         .layout_of(self.param_env.and(left_ty))
490                         .unwrap()
491                         .size
492                         .bits();
493                     let right_size = right.layout.size;
494                     let r_bits = r.to_scalar().and_then(|r| r.to_bits(right_size));
495                     if r_bits.ok().map_or(false, |b| b >= left_bits as u128) {
496                         let source_scope_local_data = match self.source_scope_local_data {
497                             ClearCrossCrate::Set(ref data) => data,
498                             ClearCrossCrate::Clear => return None,
499                         };
500                         let dir = if op == BinOp::Shr {
501                             "right"
502                         } else {
503                             "left"
504                         };
505                         let hir_id = source_scope_local_data[source_info.scope].lint_root;
506                         self.tcx.lint_hir(
507                             ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
508                             hir_id,
509                             span,
510                             &format!("attempt to shift {} with overflow", dir));
511                         return None;
512                     }
513                 }
514                 let left = self.eval_operand(left, source_info)?;
515                 let l = self.use_ecx(source_info, |this| {
516                     this.ecx.read_immediate(left)
517                 })?;
518                 trace!("const evaluating {:?} for {:?} and {:?}", op, left, right);
519                 let (val, overflow) = self.use_ecx(source_info, |this| {
520                     this.ecx.binary_op(op, l, r)
521                 })?;
522                 let val = if let Rvalue::CheckedBinaryOp(..) = *rvalue {
523                     Immediate::ScalarPair(
524                         val.into(),
525                         Scalar::from_bool(overflow).into(),
526                     )
527                 } else {
528                     if overflow {
529                         let err = InterpError::Panic(PanicMessage::Overflow(op)).into();
530                         let _: Option<()> = self.use_ecx(source_info, |_| Err(err));
531                         return None;
532                     }
533                     Immediate::Scalar(val.into())
534                 };
535                 let res = ImmTy {
536                     imm: val,
537                     layout: place_layout,
538                 };
539                 Some(res.into())
540             },
541         }
542     }
543
544     fn operand_from_scalar(&self, scalar: Scalar, ty: Ty<'tcx>, span: Span) -> Operand<'tcx> {
545         Operand::Constant(Box::new(
546             Constant {
547                 span,
548                 ty,
549                 user_ty: None,
550                 literal: self.tcx.mk_const(*ty::Const::from_scalar(
551                     self.tcx,
552                     scalar,
553                     ty,
554                 ))
555             }
556         ))
557     }
558
559     fn replace_with_const(
560         &mut self,
561         rval: &mut Rvalue<'tcx>,
562         value: Const<'tcx>,
563         source_info: SourceInfo,
564     ) {
565         trace!("attepting to replace {:?} with {:?}", rval, value);
566         if let Err(e) = self.ecx.validate_operand(
567             value,
568             vec![],
569             // FIXME: is ref tracking too expensive?
570             Some(&mut interpret::RefTracking::empty()),
571         ) {
572             trace!("validation error, attempt failed: {:?}", e);
573             return;
574         }
575
576         // FIXME> figure out what tho do when try_read_immediate fails
577         let imm = self.use_ecx(source_info, |this| {
578             this.ecx.try_read_immediate(value)
579         });
580
581         if let Some(Ok(imm)) = imm {
582             match *imm {
583                 interpret::Immediate::Scalar(ScalarMaybeUndef::Scalar(scalar)) => {
584                     *rval = Rvalue::Use(
585                         self.operand_from_scalar(scalar, value.layout.ty, source_info.span));
586                 },
587                 Immediate::ScalarPair(
588                     ScalarMaybeUndef::Scalar(one),
589                     ScalarMaybeUndef::Scalar(two)
590                 ) => {
591                     let ty = &value.layout.ty.sty;
592                     if let ty::Tuple(substs) = ty {
593                         *rval = Rvalue::Aggregate(
594                             Box::new(AggregateKind::Tuple),
595                             vec![
596                                 self.operand_from_scalar(
597                                     one, substs[0].expect_ty(), source_info.span
598                                 ),
599                                 self.operand_from_scalar(
600                                     two, substs[1].expect_ty(), source_info.span
601                                 ),
602                             ],
603                         );
604                     }
605                 },
606                 _ => { }
607             }
608         }
609     }
610
611     fn should_const_prop(&self) -> bool {
612         self.tcx.sess.opts.debugging_opts.mir_opt_level >= 2
613     }
614 }
615
616 fn type_size_of<'tcx>(
617     tcx: TyCtxt<'tcx>,
618     param_env: ty::ParamEnv<'tcx>,
619     ty: Ty<'tcx>,
620 ) -> Option<u64> {
621     tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
622 }
623
624 struct CanConstProp {
625     can_const_prop: IndexVec<Local, bool>,
626     // false at the beginning, once set, there are not allowed to be any more assignments
627     found_assignment: IndexVec<Local, bool>,
628 }
629
630 impl CanConstProp {
631     /// returns true if `local` can be propagated
632     fn check(body: &Body<'_>) -> IndexVec<Local, bool> {
633         let mut cpv = CanConstProp {
634             can_const_prop: IndexVec::from_elem(true, &body.local_decls),
635             found_assignment: IndexVec::from_elem(false, &body.local_decls),
636         };
637         for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
638             // cannot use args at all
639             // cannot use locals because if x < y { y - x } else { x - y } would
640             //        lint for x != y
641             // FIXME(oli-obk): lint variables until they are used in a condition
642             // FIXME(oli-obk): lint if return value is constant
643             *val = body.local_kind(local) == LocalKind::Temp;
644
645             if !*val {
646                 trace!("local {:?} can't be propagated because it's not a temporary", local);
647             }
648         }
649         cpv.visit_body(body);
650         cpv.can_const_prop
651     }
652 }
653
654 impl<'tcx> Visitor<'tcx> for CanConstProp {
655     fn visit_local(
656         &mut self,
657         &local: &Local,
658         context: PlaceContext,
659         _: Location,
660     ) {
661         use rustc::mir::visit::PlaceContext::*;
662         match context {
663             // Constants must have at most one write
664             // FIXME(oli-obk): we could be more powerful here, if the multiple writes
665             // only occur in independent execution paths
666             MutatingUse(MutatingUseContext::Store) => if self.found_assignment[local] {
667                 trace!("local {:?} can't be propagated because of multiple assignments", local);
668                 self.can_const_prop[local] = false;
669             } else {
670                 self.found_assignment[local] = true
671             },
672             // Reading constants is allowed an arbitrary number of times
673             NonMutatingUse(NonMutatingUseContext::Copy) |
674             NonMutatingUse(NonMutatingUseContext::Move) |
675             NonMutatingUse(NonMutatingUseContext::Inspect) |
676             NonMutatingUse(NonMutatingUseContext::Projection) |
677             MutatingUse(MutatingUseContext::Projection) |
678             NonUse(_) => {},
679             _ => {
680                 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
681                 self.can_const_prop[local] = false;
682             },
683         }
684     }
685 }
686
687 impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> {
688     fn visit_constant(
689         &mut self,
690         constant: &mut Constant<'tcx>,
691         location: Location,
692     ) {
693         trace!("visit_constant: {:?}", constant);
694         self.super_constant(constant, location);
695         self.eval_constant(constant);
696     }
697
698     fn visit_statement(
699         &mut self,
700         statement: &mut Statement<'tcx>,
701         location: Location,
702     ) {
703         trace!("visit_statement: {:?}", statement);
704         if let StatementKind::Assign(ref place, ref mut rval) = statement.kind {
705             let place_ty: Ty<'tcx> = place
706                 .ty(&self.local_decls, self.tcx)
707                 .ty;
708             if let Ok(place_layout) = self.tcx.layout_of(self.param_env.and(place_ty)) {
709                 if let Some(value) = self.const_prop(rval, place_layout, statement.source_info) {
710                     if let Place {
711                         base: PlaceBase::Local(local),
712                         projection: None,
713                     } = *place {
714                         trace!("checking whether {:?} can be stored to {:?}", value, local);
715                         if self.can_const_prop[local] {
716                             trace!("storing {:?} to {:?}", value, local);
717                             assert!(self.get_const(local).is_none());
718                             self.set_const(local, value);
719
720                             if self.should_const_prop() {
721                                 self.replace_with_const(
722                                     rval,
723                                     value,
724                                     statement.source_info,
725                                 );
726                             }
727                         }
728                     }
729                 }
730             }
731         }
732         self.super_statement(statement, location);
733     }
734
735     fn visit_terminator(
736         &mut self,
737         terminator: &mut Terminator<'tcx>,
738         location: Location,
739     ) {
740         self.super_terminator(terminator, location);
741         let source_info = terminator.source_info;
742         match &mut terminator.kind {
743             TerminatorKind::Assert { expected, ref msg, ref mut cond, .. } => {
744                 if let Some(value) = self.eval_operand(&cond, source_info) {
745                     trace!("assertion on {:?} should be {:?}", value, expected);
746                     let expected = ScalarMaybeUndef::from(Scalar::from_bool(*expected));
747                     let value_const = self.ecx.read_scalar(value).unwrap();
748                     if expected != value_const {
749                         // poison all places this operand references so that further code
750                         // doesn't use the invalid value
751                         match cond {
752                             Operand::Move(ref place) | Operand::Copy(ref place) => {
753                                 if let PlaceBase::Local(local) = place.base {
754                                     self.remove_const(local);
755                                 }
756                             },
757                             Operand::Constant(_) => {}
758                         }
759                         let span = terminator.source_info.span;
760                         let hir_id = self
761                             .tcx
762                             .hir()
763                             .as_local_hir_id(self.source.def_id())
764                             .expect("some part of a failing const eval must be local");
765                         let msg = match msg {
766                             PanicMessage::Overflow(_) |
767                             PanicMessage::OverflowNeg |
768                             PanicMessage::DivisionByZero |
769                             PanicMessage::RemainderByZero =>
770                                 msg.description().to_owned(),
771                             PanicMessage::BoundsCheck { ref len, ref index } => {
772                                 let len = self
773                                     .eval_operand(len, source_info)
774                                     .expect("len must be const");
775                                 let len = match self.ecx.read_scalar(len) {
776                                     Ok(ScalarMaybeUndef::Scalar(Scalar::Raw {
777                                         data, ..
778                                     })) => data,
779                                     other => bug!("const len not primitive: {:?}", other),
780                                 };
781                                 let index = self
782                                     .eval_operand(index, source_info)
783                                     .expect("index must be const");
784                                 let index = match self.ecx.read_scalar(index) {
785                                     Ok(ScalarMaybeUndef::Scalar(Scalar::Raw {
786                                         data, ..
787                                     })) => data,
788                                     other => bug!("const index not primitive: {:?}", other),
789                                 };
790                                 format!(
791                                     "index out of bounds: \
792                                     the len is {} but the index is {}",
793                                     len,
794                                     index,
795                                 )
796                             },
797                             // Need proper const propagator for these
798                             _ => return,
799                         };
800                         self.tcx.lint_hir(
801                             ::rustc::lint::builtin::CONST_ERR,
802                             hir_id,
803                             span,
804                             &msg,
805                         );
806                     } else {
807                         if self.should_const_prop() {
808                             if let ScalarMaybeUndef::Scalar(scalar) = value_const {
809                                 *cond = self.operand_from_scalar(
810                                     scalar,
811                                     self.tcx.types.bool,
812                                     source_info.span,
813                                 );
814                             }
815                         }
816                     }
817                 }
818             },
819             TerminatorKind::SwitchInt { ref mut discr, switch_ty, .. } => {
820                 if self.should_const_prop() {
821                     if let Some(value) = self.eval_operand(&discr, source_info) {
822                         if let ScalarMaybeUndef::Scalar(scalar) =
823                                 self.ecx.read_scalar(value).unwrap() {
824                             *discr = self.operand_from_scalar(scalar, switch_ty, source_info.span);
825                         }
826                     }
827                 }
828             },
829             //none of these have Operands to const-propagate
830             TerminatorKind::Goto { .. } |
831             TerminatorKind::Resume |
832             TerminatorKind::Abort |
833             TerminatorKind::Return |
834             TerminatorKind::Unreachable |
835             TerminatorKind::Drop { .. } |
836             TerminatorKind::DropAndReplace { .. } |
837             TerminatorKind::Yield { .. } |
838             TerminatorKind::GeneratorDrop |
839             TerminatorKind::FalseEdges { .. } |
840             TerminatorKind::FalseUnwind { .. } => { }
841             //FIXME(wesleywiser) Call does have Operands that could be const-propagated
842             TerminatorKind::Call { .. } => { }
843         }
844     }
845 }