]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/const_prop.rs
Rollup merge of #52647 - csmoe:closure_arg_ignore, r=estebank
[rust.git] / src / librustc_mir / transform / const_prop.rs
1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Propagates constants for early reporting of statically known
12 //! assertion failures
13
14
15 use rustc::hir::def::Def;
16 use rustc::mir::{Constant, Location, Place, Mir, Operand, Rvalue, Local};
17 use rustc::mir::{NullOp, StatementKind, Statement, BasicBlock, LocalKind};
18 use rustc::mir::{TerminatorKind, ClearCrossCrate, SourceInfo, BinOp, ProjectionElem};
19 use rustc::mir::visit::{Visitor, PlaceContext};
20 use rustc::mir::interpret::{ConstEvalErr, EvalErrorKind};
21 use rustc::ty::{TyCtxt, self, Instance};
22 use rustc::mir::interpret::{Value, Scalar, GlobalId, EvalResult};
23 use interpret::EvalContext;
24 use interpret::CompileTimeEvaluator;
25 use interpret::{eval_promoted, mk_borrowck_eval_cx, ValTy};
26 use transform::{MirPass, MirSource};
27 use syntax::codemap::{Span, DUMMY_SP};
28 use rustc::ty::subst::Substs;
29 use rustc_data_structures::indexed_vec::IndexVec;
30 use rustc::ty::ParamEnv;
31 use rustc::ty::layout::{
32     LayoutOf, TyLayout, LayoutError,
33     HasTyCtxt, TargetDataLayout, HasDataLayout,
34 };
35
36 pub struct ConstProp;
37
38 impl MirPass for ConstProp {
39     fn run_pass<'a, 'tcx>(&self,
40                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
41                           source: MirSource,
42                           mir: &mut Mir<'tcx>) {
43         // will be evaluated by miri and produce its errors there
44         if source.promoted.is_some() {
45             return;
46         }
47         match tcx.describe_def(source.def_id) {
48             // skip statics/consts because they'll be evaluated by miri anyway
49             Some(Def::Const(..)) |
50             Some(Def::Static(..)) => return,
51             // we still run on associated constants, because they might not get evaluated
52             // within the current crate
53             _ => {},
54         }
55         trace!("ConstProp starting for {:?}", source.def_id);
56
57         // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
58         // constants, instead of just checking for const-folding succeeding.
59         // That would require an uniform one-def no-mutation analysis
60         // and RPO (or recursing when needing the value of a local).
61         let mut optimization_finder = ConstPropagator::new(mir, tcx, source);
62         optimization_finder.visit_mir(mir);
63
64         trace!("ConstProp done for {:?}", source.def_id);
65     }
66 }
67
68 type Const<'tcx> = (Value, ty::Ty<'tcx>, Span);
69
70 /// Finds optimization opportunities on the MIR.
71 struct ConstPropagator<'b, 'a, 'tcx:'a+'b> {
72     ecx: EvalContext<'a, 'b, 'tcx, CompileTimeEvaluator>,
73     mir: &'b Mir<'tcx>,
74     tcx: TyCtxt<'a, 'tcx, 'tcx>,
75     source: MirSource,
76     places: IndexVec<Local, Option<Const<'tcx>>>,
77     can_const_prop: IndexVec<Local, bool>,
78     param_env: ParamEnv<'tcx>,
79 }
80
81 impl<'a, 'b, 'tcx> LayoutOf for &'a ConstPropagator<'a, 'b, 'tcx> {
82     type Ty = ty::Ty<'tcx>;
83     type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
84
85     fn layout_of(self, ty: ty::Ty<'tcx>) -> Self::TyLayout {
86         self.tcx.layout_of(self.param_env.and(ty))
87     }
88 }
89
90 impl<'a, 'b, 'tcx> HasDataLayout for &'a ConstPropagator<'a, 'b, 'tcx> {
91     #[inline]
92     fn data_layout(&self) -> &TargetDataLayout {
93         &self.tcx.data_layout
94     }
95 }
96
97 impl<'a, 'b, 'tcx> HasTyCtxt<'tcx> for &'a ConstPropagator<'a, 'b, 'tcx> {
98     #[inline]
99     fn tcx<'c>(&'c self) -> TyCtxt<'c, 'tcx, 'tcx> {
100         self.tcx
101     }
102 }
103
104 impl<'b, 'a, 'tcx:'b> ConstPropagator<'b, 'a, 'tcx> {
105     fn new(
106         mir: &'b Mir<'tcx>,
107         tcx: TyCtxt<'a, 'tcx, 'tcx>,
108         source: MirSource,
109     ) -> ConstPropagator<'b, 'a, 'tcx> {
110         let param_env = tcx.param_env(source.def_id);
111         let substs = Substs::identity_for_item(tcx, source.def_id);
112         let instance = Instance::new(source.def_id, substs);
113         let ecx = mk_borrowck_eval_cx(tcx, instance, mir, DUMMY_SP).unwrap();
114         ConstPropagator {
115             ecx,
116             mir,
117             tcx,
118             source,
119             param_env,
120             can_const_prop: CanConstProp::check(mir),
121             places: IndexVec::from_elem(None, &mir.local_decls),
122         }
123     }
124
125     fn use_ecx<F, T>(
126         &mut self,
127         source_info: SourceInfo,
128         f: F
129     ) -> Option<T>
130     where
131         F: FnOnce(&mut Self) -> EvalResult<'tcx, T>,
132     {
133         self.ecx.tcx.span = source_info.span;
134         let lint_root = match self.mir.source_scope_local_data {
135             ClearCrossCrate::Set(ref ivs) => {
136                 use rustc_data_structures::indexed_vec::Idx;
137                 //FIXME(#51314): remove this check
138                 if source_info.scope.index() >= ivs.len() {
139                     return None;
140                 }
141                 ivs[source_info.scope].lint_root
142             },
143             ClearCrossCrate::Clear => return None,
144         };
145         let r = match f(self) {
146             Ok(val) => Some(val),
147             Err(err) => {
148                 match err.kind {
149                     // don't report these, they make no sense in a const prop context
150                     EvalErrorKind::MachineError(_) => {},
151                     _ => {
152                         let (frames, span) = self.ecx.generate_stacktrace(None);
153                         let err = ConstEvalErr {
154                             span,
155                             error: err,
156                             stacktrace: frames,
157                         };
158                         err.report_as_lint(
159                             self.ecx.tcx,
160                             "this expression will panic at runtime",
161                             lint_root,
162                         );
163                     }
164                 }
165                 None
166             },
167         };
168         self.ecx.tcx.span = DUMMY_SP;
169         r
170     }
171
172     fn eval_constant(
173         &mut self,
174         c: &Constant<'tcx>,
175         source_info: SourceInfo,
176     ) -> Option<Const<'tcx>> {
177         self.ecx.tcx.span = source_info.span;
178         match self.ecx.const_to_value(c.literal.val) {
179             Ok(val) => Some((val, c.literal.ty, c.span)),
180             Err(error) => {
181                 let (stacktrace, span) = self.ecx.generate_stacktrace(None);
182                 let err = ConstEvalErr {
183                     span,
184                     error,
185                     stacktrace,
186                 };
187                 err.report_as_error(
188                     self.tcx.at(source_info.span),
189                     "could not evaluate constant",
190                 );
191                 None
192             },
193         }
194     }
195
196     fn eval_place(&mut self, place: &Place<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
197         match *place {
198             Place::Local(loc) => self.places[loc].clone(),
199             Place::Projection(ref proj) => match proj.elem {
200                 ProjectionElem::Field(field, _) => {
201                     trace!("field proj on {:?}", proj.base);
202                     let (base, ty, span) = self.eval_place(&proj.base, source_info)?;
203                     let valty = self.use_ecx(source_info, |this| {
204                         this.ecx.read_field(base, None, field, ty)
205                     })?;
206                     Some((valty.value, valty.ty, span))
207                 },
208                 _ => None,
209             },
210             Place::Promoted(ref promoted) => {
211                 let generics = self.tcx.generics_of(self.source.def_id);
212                 if generics.requires_monomorphization(self.tcx) {
213                     // FIXME: can't handle code with generics
214                     return None;
215                 }
216                 let substs = Substs::identity_for_item(self.tcx, self.source.def_id);
217                 let instance = Instance::new(self.source.def_id, substs);
218                 let cid = GlobalId {
219                     instance,
220                     promoted: Some(promoted.0),
221                 };
222                 // cannot use `const_eval` here, because that would require having the MIR
223                 // for the current function available, but we're producing said MIR right now
224                 let (value, _, ty) = self.use_ecx(source_info, |this| {
225                     eval_promoted(&mut this.ecx, cid, this.mir, this.param_env)
226                 })?;
227                 let val = (value, ty, source_info.span);
228                 trace!("evaluated promoted {:?} to {:?}", promoted, val);
229                 Some(val)
230             },
231             _ => None,
232         }
233     }
234
235     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
236         match *op {
237             Operand::Constant(ref c) => self.eval_constant(c, source_info),
238             | Operand::Move(ref place)
239             | Operand::Copy(ref place) => self.eval_place(place, source_info),
240         }
241     }
242
243     fn const_prop(
244         &mut self,
245         rvalue: &Rvalue<'tcx>,
246         place_ty: ty::Ty<'tcx>,
247         source_info: SourceInfo,
248     ) -> Option<Const<'tcx>> {
249         let span = source_info.span;
250         match *rvalue {
251             // This branch exists for the sanity type check
252             Rvalue::Use(Operand::Constant(ref c)) => {
253                 assert_eq!(c.ty, place_ty);
254                 self.eval_constant(c, source_info)
255             },
256             Rvalue::Use(ref op) => {
257                 self.eval_operand(op, source_info)
258             },
259             Rvalue::Repeat(..) |
260             Rvalue::Ref(..) |
261             Rvalue::Aggregate(..) |
262             Rvalue::NullaryOp(NullOp::Box, _) |
263             Rvalue::Discriminant(..) => None,
264
265             Rvalue::Cast(kind, ref operand, _) => {
266                 let (value, ty, span) = self.eval_operand(operand, source_info)?;
267                 self.use_ecx(source_info, |this| {
268                     let dest_ptr = this.ecx.alloc_ptr(place_ty)?;
269                     let place_align = this.ecx.layout_of(place_ty)?.align;
270                     let dest = ::interpret::Place::from_ptr(dest_ptr, place_align);
271                     this.ecx.cast(ValTy { value, ty }, kind, place_ty, dest)?;
272                     Ok((
273                         Value::ByRef(dest_ptr.into(), place_align),
274                         place_ty,
275                         span,
276                     ))
277                 })
278             }
279
280             // FIXME(oli-obk): evaluate static/constant slice lengths
281             Rvalue::Len(_) => None,
282             Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
283                 let param_env = self.tcx.param_env(self.source.def_id);
284                 type_size_of(self.tcx, param_env, ty).map(|n| (
285                     Value::Scalar(Scalar::Bits {
286                         bits: n as u128,
287                         defined: self.tcx.data_layout.pointer_size.bits() as u8,
288                     }),
289                     self.tcx.types.usize,
290                     span,
291                 ))
292             }
293             Rvalue::UnaryOp(op, ref arg) => {
294                 let def_id = if self.tcx.is_closure(self.source.def_id) {
295                     self.tcx.closure_base_def_id(self.source.def_id)
296                 } else {
297                     self.source.def_id
298                 };
299                 let generics = self.tcx.generics_of(def_id);
300                 if generics.requires_monomorphization(self.tcx) {
301                     // FIXME: can't handle code with generics
302                     return None;
303                 }
304
305                 let val = self.eval_operand(arg, source_info)?;
306                 let prim = self.use_ecx(source_info, |this| {
307                     this.ecx.value_to_scalar(ValTy { value: val.0, ty: val.1 })
308                 })?;
309                 let val = self.use_ecx(source_info, |this| this.ecx.unary_op(op, prim, val.1))?;
310                 Some((Value::Scalar(val), place_ty, span))
311             }
312             Rvalue::CheckedBinaryOp(op, ref left, ref right) |
313             Rvalue::BinaryOp(op, ref left, ref right) => {
314                 trace!("rvalue binop {:?} for {:?} and {:?}", op, left, right);
315                 let right = self.eval_operand(right, source_info)?;
316                 let def_id = if self.tcx.is_closure(self.source.def_id) {
317                     self.tcx.closure_base_def_id(self.source.def_id)
318                 } else {
319                     self.source.def_id
320                 };
321                 let generics = self.tcx.generics_of(def_id);
322                 if generics.requires_monomorphization(self.tcx) {
323                     // FIXME: can't handle code with generics
324                     return None;
325                 }
326
327                 let r = self.use_ecx(source_info, |this| {
328                     this.ecx.value_to_scalar(ValTy { value: right.0, ty: right.1 })
329                 })?;
330                 if op == BinOp::Shr || op == BinOp::Shl {
331                     let left_ty = left.ty(self.mir, self.tcx);
332                     let left_bits = self
333                         .tcx
334                         .layout_of(self.param_env.and(left_ty))
335                         .unwrap()
336                         .size
337                         .bits();
338                     let right_size = self.tcx.layout_of(self.param_env.and(right.1)).unwrap().size;
339                     if r.to_bits(right_size).ok().map_or(false, |b| b >= left_bits as u128) {
340                         let source_scope_local_data = match self.mir.source_scope_local_data {
341                             ClearCrossCrate::Set(ref data) => data,
342                             ClearCrossCrate::Clear => return None,
343                         };
344                         let dir = if op == BinOp::Shr {
345                             "right"
346                         } else {
347                             "left"
348                         };
349                         let node_id = source_scope_local_data[source_info.scope].lint_root;
350                         self.tcx.lint_node(
351                             ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
352                             node_id,
353                             span,
354                             &format!("attempt to shift {} with overflow", dir));
355                         return None;
356                     }
357                 }
358                 let left = self.eval_operand(left, source_info)?;
359                 let l = self.use_ecx(source_info, |this| {
360                     this.ecx.value_to_scalar(ValTy { value: left.0, ty: left.1 })
361                 })?;
362                 trace!("const evaluating {:?} for {:?} and {:?}", op, left, right);
363                 let (val, overflow) = self.use_ecx(source_info, |this| {
364                     this.ecx.binary_op(op, l, left.1, r, right.1)
365                 })?;
366                 let val = if let Rvalue::CheckedBinaryOp(..) = *rvalue {
367                     Value::ScalarPair(
368                         val,
369                         Scalar::from_bool(overflow),
370                     )
371                 } else {
372                     if overflow {
373                         let err = EvalErrorKind::Overflow(op).into();
374                         let _: Option<()> = self.use_ecx(source_info, |_| Err(err));
375                         return None;
376                     }
377                     Value::Scalar(val)
378                 };
379                 Some((val, place_ty, span))
380             },
381         }
382     }
383 }
384
385 fn type_size_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
386                           param_env: ty::ParamEnv<'tcx>,
387                           ty: ty::Ty<'tcx>) -> Option<u64> {
388     tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
389 }
390
391 struct CanConstProp {
392     can_const_prop: IndexVec<Local, bool>,
393     // false at the beginning, once set, there are not allowed to be any more assignments
394     found_assignment: IndexVec<Local, bool>,
395 }
396
397 impl CanConstProp {
398     /// returns true if `local` can be propagated
399     fn check(mir: &Mir) -> IndexVec<Local, bool> {
400         let mut cpv = CanConstProp {
401             can_const_prop: IndexVec::from_elem(true, &mir.local_decls),
402             found_assignment: IndexVec::from_elem(false, &mir.local_decls),
403         };
404         for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
405             // cannot use args at all
406             // cannot use locals because if x < y { y - x } else { x - y } would
407             //        lint for x != y
408             // FIXME(oli-obk): lint variables until they are used in a condition
409             // FIXME(oli-obk): lint if return value is constant
410             *val = mir.local_kind(local) == LocalKind::Temp;
411         }
412         cpv.visit_mir(mir);
413         cpv.can_const_prop
414     }
415 }
416
417 impl<'tcx> Visitor<'tcx> for CanConstProp {
418     fn visit_local(
419         &mut self,
420         &local: &Local,
421         context: PlaceContext<'tcx>,
422         _: Location,
423     ) {
424         use rustc::mir::visit::PlaceContext::*;
425         match context {
426             // Constants must have at most one write
427             // FIXME(oli-obk): we could be more powerful here, if the multiple writes
428             // only occur in independent execution paths
429             Store => if self.found_assignment[local] {
430                 self.can_const_prop[local] = false;
431             } else {
432                 self.found_assignment[local] = true
433             },
434             // Reading constants is allowed an arbitrary number of times
435             Copy | Move |
436             StorageDead | StorageLive |
437             Validate |
438             Projection(_) |
439             Inspect => {},
440             _ => self.can_const_prop[local] = false,
441         }
442     }
443 }
444
445 impl<'b, 'a, 'tcx> Visitor<'tcx> for ConstPropagator<'b, 'a, 'tcx> {
446     fn visit_constant(
447         &mut self,
448         constant: &Constant<'tcx>,
449         location: Location,
450     ) {
451         trace!("visit_constant: {:?}", constant);
452         self.super_constant(constant, location);
453         let source_info = *self.mir.source_info(location);
454         self.eval_constant(constant, source_info);
455     }
456
457     fn visit_statement(
458         &mut self,
459         block: BasicBlock,
460         statement: &Statement<'tcx>,
461         location: Location,
462     ) {
463         trace!("visit_statement: {:?}", statement);
464         if let StatementKind::Assign(ref place, ref rval) = statement.kind {
465             let place_ty = place
466                 .ty(&self.mir.local_decls, self.tcx)
467                 .to_ty(self.tcx);
468             if let Some(value) = self.const_prop(rval, place_ty, statement.source_info) {
469                 if let Place::Local(local) = *place {
470                     trace!("checking whether {:?} can be stored to {:?}", value, local);
471                     if self.can_const_prop[local] {
472                         trace!("storing {:?} to {:?}", value, local);
473                         assert!(self.places[local].is_none());
474                         self.places[local] = Some(value);
475                     }
476                 }
477             }
478         }
479         self.super_statement(block, statement, location);
480     }
481
482     fn visit_terminator_kind(
483         &mut self,
484         block: BasicBlock,
485         kind: &TerminatorKind<'tcx>,
486         location: Location,
487     ) {
488         self.super_terminator_kind(block, kind, location);
489         let source_info = *self.mir.source_info(location);
490         if let TerminatorKind::Assert { expected, msg, cond, .. } = kind {
491             if let Some(value) = self.eval_operand(cond, source_info) {
492                 trace!("assertion on {:?} should be {:?}", value, expected);
493                 if Value::Scalar(Scalar::from_bool(*expected)) != value.0 {
494                     // poison all places this operand references so that further code
495                     // doesn't use the invalid value
496                     match cond {
497                         Operand::Move(ref place) | Operand::Copy(ref place) => {
498                             let mut place = place;
499                             while let Place::Projection(ref proj) = *place {
500                                 place = &proj.base;
501                             }
502                             if let Place::Local(local) = *place {
503                                 self.places[local] = None;
504                             }
505                         },
506                         Operand::Constant(_) => {}
507                     }
508                     let span = self.mir[block]
509                         .terminator
510                         .as_ref()
511                         .unwrap()
512                         .source_info
513                         .span;
514                     let node_id = self
515                         .tcx
516                         .hir
517                         .as_local_node_id(self.source.def_id)
518                         .expect("some part of a failing const eval must be local");
519                     use rustc::mir::interpret::EvalErrorKind::*;
520                     let msg = match msg {
521                         Overflow(_) |
522                         OverflowNeg |
523                         DivisionByZero |
524                         RemainderByZero => msg.description().to_owned(),
525                         BoundsCheck { ref len, ref index } => {
526                             let len = self
527                                 .eval_operand(len, source_info)
528                                 .expect("len must be const");
529                             let len = match len.0 {
530                                 Value::Scalar(Scalar::Bits { bits, ..}) => bits,
531                                 _ => bug!("const len not primitive: {:?}", len),
532                             };
533                             let index = self
534                                 .eval_operand(index, source_info)
535                                 .expect("index must be const");
536                             let index = match index.0 {
537                                 Value::Scalar(Scalar::Bits { bits, .. }) => bits,
538                                 _ => bug!("const index not primitive: {:?}", index),
539                             };
540                             format!(
541                                 "index out of bounds: \
542                                 the len is {} but the index is {}",
543                                 len,
544                                 index,
545                             )
546                         },
547                         // Need proper const propagator for these
548                         _ => return,
549                     };
550                     self.tcx.lint_node(
551                         ::rustc::lint::builtin::CONST_ERR,
552                         node_id,
553                         span,
554                         &msg,
555                     );
556                 }
557             }
558         }
559     }
560 }