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.
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.
11 //! Propagates constants for early reporting of statically known
12 //! assertion failures
15 use rustc::hir::def::Def;
16 use rustc::mir::{Constant, Location, Place, Mir, Operand, Rvalue, Local};
17 use rustc::mir::{NullOp, UnOp, StatementKind, Statement, BasicBlock, LocalKind};
18 use rustc::mir::{TerminatorKind, ClearCrossCrate, SourceInfo, BinOp, ProjectionElem};
19 use rustc::mir::visit::{Visitor, PlaceContext, MutatingUseContext, NonMutatingUseContext};
20 use rustc::mir::interpret::{EvalErrorKind, Scalar, GlobalId, EvalResult};
21 use rustc::ty::{TyCtxt, self, Instance};
22 use syntax::source_map::{Span, DUMMY_SP};
23 use rustc::ty::subst::Substs;
24 use rustc_data_structures::indexed_vec::IndexVec;
25 use rustc::ty::ParamEnv;
26 use rustc::ty::layout::{
27 LayoutOf, TyLayout, LayoutError,
28 HasTyCtxt, TargetDataLayout, HasDataLayout,
31 use interpret::{self, EvalContext, ScalarMaybeUndef, Immediate, OpTy, MemoryKind};
32 use const_eval::{CompileTimeInterpreter, error_to_const_error, eval_promoted, mk_borrowck_eval_cx};
33 use transform::{MirPass, MirSource};
37 impl MirPass for ConstProp {
38 fn run_pass<'a, 'tcx>(&self,
39 tcx: TyCtxt<'a, 'tcx, 'tcx>,
41 mir: &mut Mir<'tcx>) {
42 // will be evaluated by miri and produce its errors there
43 if source.promoted.is_some() {
47 use rustc::hir::map::blocks::FnLikeNode;
48 let node_id = tcx.hir.as_local_node_id(source.def_id)
49 .expect("Non-local call to local provider is_const_fn");
51 let is_fn_like = FnLikeNode::from_node(tcx.hir.get(node_id)).is_some();
52 let is_assoc_const = match tcx.describe_def(source.def_id) {
53 Some(Def::AssociatedConst(_)) => true,
57 // Only run const prop on functions, methods, closures and associated constants
58 if !is_fn_like && !is_assoc_const {
59 // skip anon_const/statics/consts because they'll be evaluated by miri anyway
60 trace!("ConstProp skipped for {:?}", source.def_id);
64 trace!("ConstProp starting for {:?}", source.def_id);
66 // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
67 // constants, instead of just checking for const-folding succeeding.
68 // That would require an uniform one-def no-mutation analysis
69 // and RPO (or recursing when needing the value of a local).
70 let mut optimization_finder = ConstPropagator::new(mir, tcx, source);
71 optimization_finder.visit_mir(mir);
73 trace!("ConstProp done for {:?}", source.def_id);
77 type Const<'tcx> = (OpTy<'tcx>, Span);
79 /// Finds optimization opportunities on the MIR.
80 struct ConstPropagator<'a, 'mir, 'tcx:'a+'mir> {
81 ecx: EvalContext<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>,
83 tcx: TyCtxt<'a, 'tcx, 'tcx>,
85 places: IndexVec<Local, Option<Const<'tcx>>>,
86 can_const_prop: IndexVec<Local, bool>,
87 param_env: ParamEnv<'tcx>,
90 impl<'a, 'b, 'tcx> LayoutOf for ConstPropagator<'a, 'b, 'tcx> {
91 type Ty = ty::Ty<'tcx>;
92 type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
94 fn layout_of(&self, ty: ty::Ty<'tcx>) -> Self::TyLayout {
95 self.tcx.layout_of(self.param_env.and(ty))
99 impl<'a, 'b, 'tcx> HasDataLayout for ConstPropagator<'a, 'b, 'tcx> {
101 fn data_layout(&self) -> &TargetDataLayout {
102 &self.tcx.data_layout
106 impl<'a, 'b, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'a, 'b, 'tcx> {
108 fn tcx<'c>(&'c self) -> TyCtxt<'c, 'tcx, 'tcx> {
113 impl<'a, 'mir, 'tcx> ConstPropagator<'a, 'mir, 'tcx> {
115 mir: &'mir Mir<'tcx>,
116 tcx: TyCtxt<'a, 'tcx, 'tcx>,
118 ) -> ConstPropagator<'a, 'mir, 'tcx> {
119 let param_env = tcx.param_env(source.def_id);
120 let substs = Substs::identity_for_item(tcx, source.def_id);
121 let instance = Instance::new(source.def_id, substs);
122 let ecx = mk_borrowck_eval_cx(tcx, instance, mir, DUMMY_SP).unwrap();
129 can_const_prop: CanConstProp::check(mir),
130 places: IndexVec::from_elem(None, &mir.local_decls),
136 source_info: SourceInfo,
140 F: FnOnce(&mut Self) -> EvalResult<'tcx, T>,
142 self.ecx.tcx.span = source_info.span;
143 let lint_root = match self.mir.source_scope_local_data {
144 ClearCrossCrate::Set(ref ivs) => {
145 //FIXME(#51314): remove this check
146 if source_info.scope.index() >= ivs.len() {
149 ivs[source_info.scope].lint_root
151 ClearCrossCrate::Clear => return None,
153 let r = match f(self) {
154 Ok(val) => Some(val),
156 let diagnostic = error_to_const_error(&self.ecx, error);
157 use rustc::mir::interpret::EvalErrorKind::*;
158 match diagnostic.error {
159 // don't report these, they make no sense in a const prop context
161 // at runtime these transformations might make sense
162 // FIXME: figure out the rules and start linting
163 | FunctionAbiMismatch(..)
164 | FunctionArgMismatch(..)
165 | FunctionRetMismatch(..)
166 | FunctionArgCountMismatch
167 // fine at runtime, might be a register address or sth
172 // don't report const evaluator limits
173 | StackFrameLimitReached
178 | InvalidMemoryAccess
179 | DanglingPointerDeref
181 | InvalidFunctionPointer
183 | InvalidDiscriminant(..)
184 | PointerOutOfBounds { .. }
185 | InvalidNullPointerUsage
186 | ValidationFailure(..)
191 | DerefFunctionPointer
196 | AlignmentCheckFailed{..}
197 | CalledClosureAsFunction
198 | VtableForArgumentlessMethod
199 | ModifiedConstantMemory
201 // FIXME: should probably be removed and turned into a bug! call
202 | TypeNotPrimitive(_)
203 | ReallocatedWrongMemoryKind(_, _)
204 | DeallocatedWrongMemoryKind(_, _)
205 | ReallocateNonBasePtr
206 | DeallocateNonBasePtr
207 | IncorrectAllocationInformation(..)
208 | UnterminatedCString(_)
210 | HeapAllocNonPowerOfTwoAlignment(_)
212 | ReadFromReturnPointer
213 | GeneratorResumedAfterReturn
214 | GeneratorResumedAfterPanic
218 // FIXME: report UB here
224 => bug!("these should not be in rustc, but in miri's machine errors"),
227 | UnimplementedTraitSelection
230 // these are just noise
245 diagnostic.report_as_lint(
247 "this expression will panic at runtime",
255 self.ecx.tcx.span = DUMMY_SP;
262 source_info: SourceInfo,
263 ) -> Option<Const<'tcx>> {
264 self.ecx.tcx.span = source_info.span;
265 match self.ecx.const_to_op(c.literal) {
270 let err = error_to_const_error(&self.ecx, error);
271 err.report_as_error(self.ecx.tcx, "erroneous constant used");
277 fn eval_place(&mut self, place: &Place<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
279 Place::Local(loc) => self.places[loc].clone(),
280 Place::Projection(ref proj) => match proj.elem {
281 ProjectionElem::Field(field, _) => {
282 trace!("field proj on {:?}", proj.base);
283 let (base, span) = self.eval_place(&proj.base, source_info)?;
284 let res = self.use_ecx(source_info, |this| {
285 this.ecx.operand_field(base, field.index() as u64)
289 // We could get more projections by using e.g. `operand_projection`,
290 // but we do not even have the stack frame set up properly so
291 // an `Index` projection would throw us off-track.
294 Place::Promoted(ref promoted) => {
295 let generics = self.tcx.generics_of(self.source.def_id);
296 if generics.requires_monomorphization(self.tcx) {
297 // FIXME: can't handle code with generics
300 let substs = Substs::identity_for_item(self.tcx, self.source.def_id);
301 let instance = Instance::new(self.source.def_id, substs);
304 promoted: Some(promoted.0),
306 // cannot use `const_eval` here, because that would require having the MIR
307 // for the current function available, but we're producing said MIR right now
308 let res = self.use_ecx(source_info, |this| {
309 eval_promoted(this.tcx, cid, this.mir, this.param_env)
311 trace!("evaluated promoted {:?} to {:?}", promoted, res);
312 Some((res, source_info.span))
318 fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
320 Operand::Constant(ref c) => self.eval_constant(c, source_info),
321 | Operand::Move(ref place)
322 | Operand::Copy(ref place) => self.eval_place(place, source_info),
328 rvalue: &Rvalue<'tcx>,
329 place_layout: TyLayout<'tcx>,
330 source_info: SourceInfo,
331 ) -> Option<Const<'tcx>> {
332 let span = source_info.span;
334 Rvalue::Use(ref op) => {
335 self.eval_operand(op, source_info)
339 Rvalue::Aggregate(..) |
340 Rvalue::NullaryOp(NullOp::Box, _) |
341 Rvalue::Discriminant(..) => None,
343 Rvalue::Cast(kind, ref operand, _) => {
344 let (op, span) = self.eval_operand(operand, source_info)?;
345 self.use_ecx(source_info, |this| {
346 let dest = this.ecx.allocate(place_layout, MemoryKind::Stack)?;
347 this.ecx.cast(op, kind, dest.into())?;
348 Ok((dest.into(), span))
352 // FIXME(oli-obk): evaluate static/constant slice lengths
353 Rvalue::Len(_) => None,
354 Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
355 type_size_of(self.tcx, self.param_env, ty).and_then(|n| Some((
357 op: interpret::Operand::Immediate(Immediate::Scalar(
360 size: self.tcx.data_layout.pointer_size.bytes() as u8,
363 layout: self.tcx.layout_of(self.param_env.and(self.tcx.types.usize)).ok()?,
368 Rvalue::UnaryOp(op, ref arg) => {
369 let def_id = if self.tcx.is_closure(self.source.def_id) {
370 self.tcx.closure_base_def_id(self.source.def_id)
374 let generics = self.tcx.generics_of(def_id);
375 if generics.requires_monomorphization(self.tcx) {
376 // FIXME: can't handle code with generics
380 let (arg, _) = self.eval_operand(arg, source_info)?;
381 let val = self.use_ecx(source_info, |this| {
382 let prim = this.ecx.read_scalar(arg)?.not_undef()?;
385 // Need to do overflow check here: For actual CTFE, MIR
386 // generation emits code that does this before calling the op.
387 let size = arg.layout.size;
388 if prim.to_bits(size)? == (1 << (size.bits() - 1)) {
389 return err!(OverflowNeg);
396 // Now run the actual operation.
397 this.ecx.unary_op(op, prim, arg.layout)
400 op: interpret::Operand::Immediate(Immediate::Scalar(val.into())),
401 layout: place_layout,
405 Rvalue::CheckedBinaryOp(op, ref left, ref right) |
406 Rvalue::BinaryOp(op, ref left, ref right) => {
407 trace!("rvalue binop {:?} for {:?} and {:?}", op, left, right);
408 let right = self.eval_operand(right, source_info)?;
409 let def_id = if self.tcx.is_closure(self.source.def_id) {
410 self.tcx.closure_base_def_id(self.source.def_id)
414 let generics = self.tcx.generics_of(def_id);
415 if generics.requires_monomorphization(self.tcx) {
416 // FIXME: can't handle code with generics
420 let r = self.use_ecx(source_info, |this| {
421 this.ecx.read_immediate(right.0)
423 if op == BinOp::Shr || op == BinOp::Shl {
424 let left_ty = left.ty(self.mir, self.tcx);
427 .layout_of(self.param_env.and(left_ty))
431 let right_size = right.0.layout.size;
432 let r_bits = r.to_scalar().and_then(|r| r.to_bits(right_size));
433 if r_bits.ok().map_or(false, |b| b >= left_bits as u128) {
434 let source_scope_local_data = match self.mir.source_scope_local_data {
435 ClearCrossCrate::Set(ref data) => data,
436 ClearCrossCrate::Clear => return None,
438 let dir = if op == BinOp::Shr {
443 let node_id = source_scope_local_data[source_info.scope].lint_root;
445 ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
448 &format!("attempt to shift {} with overflow", dir));
452 let left = self.eval_operand(left, source_info)?;
453 let l = self.use_ecx(source_info, |this| {
454 this.ecx.read_immediate(left.0)
456 trace!("const evaluating {:?} for {:?} and {:?}", op, left, right);
457 let (val, overflow) = self.use_ecx(source_info, |this| {
458 this.ecx.binary_op_imm(op, l, r)
460 let val = if let Rvalue::CheckedBinaryOp(..) = *rvalue {
461 Immediate::ScalarPair(
463 Scalar::from_bool(overflow).into(),
467 let err = EvalErrorKind::Overflow(op).into();
468 let _: Option<()> = self.use_ecx(source_info, |_| Err(err));
471 Immediate::Scalar(val.into())
474 op: interpret::Operand::Immediate(val),
475 layout: place_layout,
483 fn type_size_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
484 param_env: ty::ParamEnv<'tcx>,
485 ty: ty::Ty<'tcx>) -> Option<u64> {
486 tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
489 struct CanConstProp {
490 can_const_prop: IndexVec<Local, bool>,
491 // false at the beginning, once set, there are not allowed to be any more assignments
492 found_assignment: IndexVec<Local, bool>,
496 /// returns true if `local` can be propagated
497 fn check(mir: &Mir) -> IndexVec<Local, bool> {
498 let mut cpv = CanConstProp {
499 can_const_prop: IndexVec::from_elem(true, &mir.local_decls),
500 found_assignment: IndexVec::from_elem(false, &mir.local_decls),
502 for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
503 // cannot use args at all
504 // cannot use locals because if x < y { y - x } else { x - y } would
506 // FIXME(oli-obk): lint variables until they are used in a condition
507 // FIXME(oli-obk): lint if return value is constant
508 *val = mir.local_kind(local) == LocalKind::Temp;
515 impl<'tcx> Visitor<'tcx> for CanConstProp {
519 context: PlaceContext<'tcx>,
522 use rustc::mir::visit::PlaceContext::*;
524 // Constants must have at most one write
525 // FIXME(oli-obk): we could be more powerful here, if the multiple writes
526 // only occur in independent execution paths
527 MutatingUse(MutatingUseContext::Store) => if self.found_assignment[local] {
528 self.can_const_prop[local] = false;
530 self.found_assignment[local] = true
532 // Reading constants is allowed an arbitrary number of times
533 NonMutatingUse(NonMutatingUseContext::Copy) |
534 NonMutatingUse(NonMutatingUseContext::Move) |
535 NonMutatingUse(NonMutatingUseContext::Inspect) |
536 NonMutatingUse(NonMutatingUseContext::Projection) |
537 MutatingUse(MutatingUseContext::Projection) |
539 _ => self.can_const_prop[local] = false,
544 impl<'b, 'a, 'tcx> Visitor<'tcx> for ConstPropagator<'b, 'a, 'tcx> {
547 constant: &Constant<'tcx>,
550 trace!("visit_constant: {:?}", constant);
551 self.super_constant(constant, location);
552 let source_info = *self.mir.source_info(location);
553 self.eval_constant(constant, source_info);
559 statement: &Statement<'tcx>,
562 trace!("visit_statement: {:?}", statement);
563 if let StatementKind::Assign(ref place, ref rval) = statement.kind {
564 let place_ty: ty::Ty<'tcx> = place
565 .ty(&self.mir.local_decls, self.tcx)
567 if let Ok(place_layout) = self.tcx.layout_of(self.param_env.and(place_ty)) {
568 if let Some(value) = self.const_prop(rval, place_layout, statement.source_info) {
569 if let Place::Local(local) = *place {
570 trace!("checking whether {:?} can be stored to {:?}", value, local);
571 if self.can_const_prop[local] {
572 trace!("storing {:?} to {:?}", value, local);
573 assert!(self.places[local].is_none());
574 self.places[local] = Some(value);
580 self.super_statement(block, statement, location);
583 fn visit_terminator_kind(
586 kind: &TerminatorKind<'tcx>,
589 self.super_terminator_kind(block, kind, location);
590 let source_info = *self.mir.source_info(location);
591 if let TerminatorKind::Assert { expected, msg, cond, .. } = kind {
592 if let Some(value) = self.eval_operand(cond, source_info) {
593 trace!("assertion on {:?} should be {:?}", value, expected);
594 let expected = ScalarMaybeUndef::from(Scalar::from_bool(*expected));
595 if expected != self.ecx.read_scalar(value.0).unwrap() {
596 // poison all places this operand references so that further code
597 // doesn't use the invalid value
599 Operand::Move(ref place) | Operand::Copy(ref place) => {
600 let mut place = place;
601 while let Place::Projection(ref proj) = *place {
604 if let Place::Local(local) = *place {
605 self.places[local] = None;
608 Operand::Constant(_) => {}
610 let span = self.mir[block]
619 .as_local_node_id(self.source.def_id)
620 .expect("some part of a failing const eval must be local");
621 use rustc::mir::interpret::EvalErrorKind::*;
622 let msg = match msg {
626 RemainderByZero => msg.description().to_owned(),
627 BoundsCheck { ref len, ref index } => {
629 .eval_operand(len, source_info)
630 .expect("len must be const");
631 let len = match self.ecx.read_scalar(len.0) {
632 Ok(ScalarMaybeUndef::Scalar(Scalar::Bits {
635 other => bug!("const len not primitive: {:?}", other),
638 .eval_operand(index, source_info)
639 .expect("index must be const");
640 let index = match self.ecx.read_scalar(index.0) {
641 Ok(ScalarMaybeUndef::Scalar(Scalar::Bits {
644 other => bug!("const index not primitive: {:?}", other),
647 "index out of bounds: \
648 the len is {} but the index is {}",
653 // Need proper const propagator for these
657 ::rustc::lint::builtin::CONST_ERR,