]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/const_prop.rs
Auto merge of #51732 - GuillaumeGomez:cmd-line-lint-rustdoc, r=QuietMisdreavus
[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, Literal, 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;
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                 let (frames, span) = self.ecx.generate_stacktrace(None);
149                 let err = ConstEvalErr {
150                     span,
151                     error: err,
152                     stacktrace: frames,
153                 };
154                 err.report_as_lint(
155                     self.ecx.tcx,
156                     "this expression will panic at runtime",
157                     lint_root,
158                 );
159                 None
160             },
161         };
162         self.ecx.tcx.span = DUMMY_SP;
163         r
164     }
165
166     fn eval_constant(
167         &mut self,
168         c: &Constant<'tcx>,
169         source_info: SourceInfo,
170     ) -> Option<Const<'tcx>> {
171         match c.literal {
172             Literal::Value { value } => {
173                 self.ecx.tcx.span = source_info.span;
174                 match self.ecx.const_to_value(value.val) {
175                     Ok(val) => Some((val, value.ty, c.span)),
176                     Err(error) => {
177                         let (stacktrace, span) = self.ecx.generate_stacktrace(None);
178                         let err = ConstEvalErr {
179                             span,
180                             error,
181                             stacktrace,
182                         };
183                         err.report_as_error(
184                             self.tcx.at(source_info.span),
185                             "could not evaluate constant",
186                         );
187                         None
188                     },
189                 }
190             },
191             // evaluate the promoted and replace the constant with the evaluated result
192             Literal::Promoted { index } => {
193                 let generics = self.tcx.generics_of(self.source.def_id);
194                 if generics.requires_monomorphization(self.tcx) {
195                     // FIXME: can't handle code with generics
196                     return None;
197                 }
198                 let substs = Substs::identity_for_item(self.tcx, self.source.def_id);
199                 let instance = Instance::new(self.source.def_id, substs);
200                 let cid = GlobalId {
201                     instance,
202                     promoted: Some(index),
203                 };
204                 // cannot use `const_eval` here, because that would require having the MIR
205                 // for the current function available, but we're producing said MIR right now
206                 let (value, _, ty) = self.use_ecx(source_info, |this| {
207                     eval_promoted(&mut this.ecx, cid, this.mir, this.param_env)
208                 })?;
209                 let val = (value, ty, c.span);
210                 trace!("evaluated {:?} to {:?}", c, val);
211                 Some(val)
212             }
213         }
214     }
215
216     fn eval_place(&mut self, place: &Place<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
217         match *place {
218             Place::Local(loc) => self.places[loc].clone(),
219             Place::Projection(ref proj) => match proj.elem {
220                 ProjectionElem::Field(field, _) => {
221                     trace!("field proj on {:?}", proj.base);
222                     let (base, ty, span) = self.eval_place(&proj.base, source_info)?;
223                     let valty = self.use_ecx(source_info, |this| {
224                         this.ecx.read_field(base, None, field, ty)
225                     })?;
226                     Some((valty.value, valty.ty, span))
227                 },
228                 _ => None,
229             },
230             _ => None,
231         }
232     }
233
234     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
235         match *op {
236             Operand::Constant(ref c) => self.eval_constant(c, source_info),
237             | Operand::Move(ref place)
238             | Operand::Copy(ref place) => self.eval_place(place, source_info),
239         }
240     }
241
242     fn const_prop(
243         &mut self,
244         rvalue: &Rvalue<'tcx>,
245         place_ty: ty::Ty<'tcx>,
246         source_info: SourceInfo,
247     ) -> Option<Const<'tcx>> {
248         let span = source_info.span;
249         match *rvalue {
250             // This branch exists for the sanity type check
251             Rvalue::Use(Operand::Constant(ref c)) => {
252                 assert_eq!(c.ty, place_ty);
253                 self.eval_constant(c, source_info)
254             },
255             Rvalue::Use(ref op) => {
256                 self.eval_operand(op, source_info)
257             },
258             Rvalue::Repeat(..) |
259             Rvalue::Ref(..) |
260             Rvalue::Cast(..) |
261             Rvalue::Aggregate(..) |
262             Rvalue::NullaryOp(NullOp::Box, _) |
263             Rvalue::Discriminant(..) => None,
264             // FIXME(oli-obk): evaluate static/constant slice lengths
265             Rvalue::Len(_) => None,
266             Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
267                 let param_env = self.tcx.param_env(self.source.def_id);
268                 type_size_of(self.tcx, param_env, ty).map(|n| (
269                     Value::Scalar(Scalar::Bits {
270                         bits: n as u128,
271                         defined: self.tcx.data_layout.pointer_size.bits() as u8,
272                     }),
273                     self.tcx.types.usize,
274                     span,
275                 ))
276             }
277             Rvalue::UnaryOp(op, ref arg) => {
278                 let def_id = if self.tcx.is_closure(self.source.def_id) {
279                     self.tcx.closure_base_def_id(self.source.def_id)
280                 } else {
281                     self.source.def_id
282                 };
283                 let generics = self.tcx.generics_of(def_id);
284                 if generics.requires_monomorphization(self.tcx) {
285                     // FIXME: can't handle code with generics
286                     return None;
287                 }
288
289                 let val = self.eval_operand(arg, source_info)?;
290                 let prim = self.use_ecx(source_info, |this| {
291                     this.ecx.value_to_scalar(ValTy { value: val.0, ty: val.1 })
292                 })?;
293                 let val = self.use_ecx(source_info, |this| this.ecx.unary_op(op, prim, val.1))?;
294                 Some((Value::Scalar(val), place_ty, span))
295             }
296             Rvalue::CheckedBinaryOp(op, ref left, ref right) |
297             Rvalue::BinaryOp(op, ref left, ref right) => {
298                 trace!("rvalue binop {:?} for {:?} and {:?}", op, left, right);
299                 let right = self.eval_operand(right, source_info)?;
300                 let def_id = if self.tcx.is_closure(self.source.def_id) {
301                     self.tcx.closure_base_def_id(self.source.def_id)
302                 } else {
303                     self.source.def_id
304                 };
305                 let generics = self.tcx.generics_of(def_id);
306                 if generics.requires_monomorphization(self.tcx) {
307                     // FIXME: can't handle code with generics
308                     return None;
309                 }
310
311                 let r = self.use_ecx(source_info, |this| {
312                     this.ecx.value_to_scalar(ValTy { value: right.0, ty: right.1 })
313                 })?;
314                 if op == BinOp::Shr || op == BinOp::Shl {
315                     let left_ty = left.ty(self.mir, self.tcx);
316                     let left_bits = self
317                         .tcx
318                         .layout_of(self.param_env.and(left_ty))
319                         .unwrap()
320                         .size
321                         .bits();
322                     let right_size = self.tcx.layout_of(self.param_env.and(right.1)).unwrap().size;
323                     if r.to_bits(right_size).ok().map_or(false, |b| b >= left_bits as u128) {
324                         let source_scope_local_data = match self.mir.source_scope_local_data {
325                             ClearCrossCrate::Set(ref data) => data,
326                             ClearCrossCrate::Clear => return None,
327                         };
328                         let dir = if op == BinOp::Shr {
329                             "right"
330                         } else {
331                             "left"
332                         };
333                         let node_id = source_scope_local_data[source_info.scope].lint_root;
334                         self.tcx.lint_node(
335                             ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
336                             node_id,
337                             span,
338                             &format!("attempt to shift {} with overflow", dir));
339                         return None;
340                     }
341                 }
342                 let left = self.eval_operand(left, source_info)?;
343                 let l = self.use_ecx(source_info, |this| {
344                     this.ecx.value_to_scalar(ValTy { value: left.0, ty: left.1 })
345                 })?;
346                 trace!("const evaluating {:?} for {:?} and {:?}", op, left, right);
347                 let (val, overflow) = self.use_ecx(source_info, |this| {
348                     this.ecx.binary_op(op, l, left.1, r, right.1)
349                 })?;
350                 let val = if let Rvalue::CheckedBinaryOp(..) = *rvalue {
351                     Value::ScalarPair(
352                         val,
353                         Scalar::from_bool(overflow),
354                     )
355                 } else {
356                     if overflow {
357                         use rustc::mir::interpret::EvalErrorKind;
358                         let err = EvalErrorKind::Overflow(op).into();
359                         let _: Option<()> = self.use_ecx(source_info, |_| Err(err));
360                         return None;
361                     }
362                     Value::Scalar(val)
363                 };
364                 Some((val, place_ty, span))
365             },
366         }
367     }
368 }
369
370 fn type_size_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
371                           param_env: ty::ParamEnv<'tcx>,
372                           ty: ty::Ty<'tcx>) -> Option<u64> {
373     tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
374 }
375
376 struct CanConstProp {
377     can_const_prop: IndexVec<Local, bool>,
378     // false at the beginning, once set, there are not allowed to be any more assignments
379     found_assignment: IndexVec<Local, bool>,
380 }
381
382 impl CanConstProp {
383     /// returns true if `local` can be propagated
384     fn check(mir: &Mir) -> IndexVec<Local, bool> {
385         let mut cpv = CanConstProp {
386             can_const_prop: IndexVec::from_elem(true, &mir.local_decls),
387             found_assignment: IndexVec::from_elem(false, &mir.local_decls),
388         };
389         for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
390             // cannot use args at all
391             // cannot use locals because if x < y { y - x } else { x - y } would
392             //        lint for x != y
393             // FIXME(oli-obk): lint variables until they are used in a condition
394             // FIXME(oli-obk): lint if return value is constant
395             *val = mir.local_kind(local) == LocalKind::Temp;
396         }
397         cpv.visit_mir(mir);
398         cpv.can_const_prop
399     }
400 }
401
402 impl<'tcx> Visitor<'tcx> for CanConstProp {
403     fn visit_local(
404         &mut self,
405         &local: &Local,
406         context: PlaceContext<'tcx>,
407         _: Location,
408     ) {
409         use rustc::mir::visit::PlaceContext::*;
410         match context {
411             // Constants must have at most one write
412             // FIXME(oli-obk): we could be more powerful here, if the multiple writes
413             // only occur in independent execution paths
414             Store => if self.found_assignment[local] {
415                 self.can_const_prop[local] = false;
416             } else {
417                 self.found_assignment[local] = true
418             },
419             // Reading constants is allowed an arbitrary number of times
420             Copy | Move |
421             StorageDead | StorageLive |
422             Validate |
423             Projection(_) |
424             Inspect => {},
425             _ => self.can_const_prop[local] = false,
426         }
427     }
428 }
429
430 impl<'b, 'a, 'tcx> Visitor<'tcx> for ConstPropagator<'b, 'a, 'tcx> {
431     fn visit_constant(
432         &mut self,
433         constant: &Constant<'tcx>,
434         location: Location,
435     ) {
436         trace!("visit_constant: {:?}", constant);
437         self.super_constant(constant, location);
438         let source_info = *self.mir.source_info(location);
439         self.eval_constant(constant, source_info);
440     }
441
442     fn visit_statement(
443         &mut self,
444         block: BasicBlock,
445         statement: &Statement<'tcx>,
446         location: Location,
447     ) {
448         trace!("visit_statement: {:?}", statement);
449         if let StatementKind::Assign(ref place, ref rval) = statement.kind {
450             let place_ty = place
451                 .ty(&self.mir.local_decls, self.tcx)
452                 .to_ty(self.tcx);
453             if let Some(value) = self.const_prop(rval, place_ty, statement.source_info) {
454                 if let Place::Local(local) = *place {
455                     trace!("checking whether {:?} can be stored to {:?}", value, local);
456                     if self.can_const_prop[local] {
457                         trace!("storing {:?} to {:?}", value, local);
458                         assert!(self.places[local].is_none());
459                         self.places[local] = Some(value);
460                     }
461                 }
462             }
463         }
464         self.super_statement(block, statement, location);
465     }
466
467     fn visit_terminator_kind(
468         &mut self,
469         block: BasicBlock,
470         kind: &TerminatorKind<'tcx>,
471         location: Location,
472     ) {
473         self.super_terminator_kind(block, kind, location);
474         let source_info = *self.mir.source_info(location);
475         if let TerminatorKind::Assert { expected, msg, cond, .. } = kind {
476             if let Some(value) = self.eval_operand(cond, source_info) {
477                 trace!("assertion on {:?} should be {:?}", value, expected);
478                 if Value::Scalar(Scalar::from_bool(*expected)) != value.0 {
479                     // poison all places this operand references so that further code
480                     // doesn't use the invalid value
481                     match cond {
482                         Operand::Move(ref place) | Operand::Copy(ref place) => {
483                             let mut place = place;
484                             while let Place::Projection(ref proj) = *place {
485                                 place = &proj.base;
486                             }
487                             if let Place::Local(local) = *place {
488                                 self.places[local] = None;
489                             }
490                         },
491                         Operand::Constant(_) => {}
492                     }
493                     let span = self.mir[block]
494                         .terminator
495                         .as_ref()
496                         .unwrap()
497                         .source_info
498                         .span;
499                     let node_id = self
500                         .tcx
501                         .hir
502                         .as_local_node_id(self.source.def_id)
503                         .expect("some part of a failing const eval must be local");
504                     use rustc::mir::interpret::EvalErrorKind::*;
505                     let msg = match msg {
506                         Overflow(_) |
507                         OverflowNeg |
508                         DivisionByZero |
509                         RemainderByZero => msg.description().to_owned(),
510                         BoundsCheck { ref len, ref index } => {
511                             let len = self
512                                 .eval_operand(len, source_info)
513                                 .expect("len must be const");
514                             let len = match len.0 {
515                                 Value::Scalar(Scalar::Bits { bits, ..}) => bits,
516                                 _ => bug!("const len not primitive: {:?}", len),
517                             };
518                             let index = self
519                                 .eval_operand(index, source_info)
520                                 .expect("index must be const");
521                             let index = match index.0 {
522                                 Value::Scalar(Scalar::Bits { bits, .. }) => bits,
523                                 _ => bug!("const index not primitive: {:?}", index),
524                             };
525                             format!(
526                                 "index out of bounds: \
527                                 the len is {} but the index is {}",
528                                 len,
529                                 index,
530                             )
531                         },
532                         // Need proper const propagator for these
533                         _ => return,
534                     };
535                     self.tcx.lint_node(
536                         ::rustc::lint::builtin::CONST_ERR,
537                         node_id,
538                         span,
539                         &msg,
540                     );
541                 }
542             }
543         }
544     }
545 }