]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/const_prop.rs
885d70dc4304dee3e3cd02c3118df7555aab58b6
[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, 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,
29 };
30
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};
34
35 pub struct ConstProp;
36
37 impl MirPass for ConstProp {
38     fn run_pass<'a, 'tcx>(&self,
39                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
40                           source: MirSource,
41                           mir: &mut Mir<'tcx>) {
42         // will be evaluated by miri and produce its errors there
43         if source.promoted.is_some() {
44             return;
45         }
46
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");
50
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,
54             _ => false,
55         };
56
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);
61             return
62         }
63
64         trace!("ConstProp starting for {:?}", source.def_id);
65
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);
72
73         trace!("ConstProp done for {:?}", source.def_id);
74     }
75 }
76
77 type Const<'tcx> = (OpTy<'tcx>, Span);
78
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>>,
82     mir: &'mir Mir<'tcx>,
83     tcx: TyCtxt<'a, 'tcx, 'tcx>,
84     source: MirSource,
85     places: IndexVec<Local, Option<Const<'tcx>>>,
86     can_const_prop: IndexVec<Local, bool>,
87     param_env: ParamEnv<'tcx>,
88 }
89
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>>;
93
94     fn layout_of(&self, ty: ty::Ty<'tcx>) -> Self::TyLayout {
95         self.tcx.layout_of(self.param_env.and(ty))
96     }
97 }
98
99 impl<'a, 'b, 'tcx> HasDataLayout for ConstPropagator<'a, 'b, 'tcx> {
100     #[inline]
101     fn data_layout(&self) -> &TargetDataLayout {
102         &self.tcx.data_layout
103     }
104 }
105
106 impl<'a, 'b, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'a, 'b, 'tcx> {
107     #[inline]
108     fn tcx<'c>(&'c self) -> TyCtxt<'c, 'tcx, 'tcx> {
109         self.tcx
110     }
111 }
112
113 impl<'a, 'mir, 'tcx> ConstPropagator<'a, 'mir, 'tcx> {
114     fn new(
115         mir: &'mir Mir<'tcx>,
116         tcx: TyCtxt<'a, 'tcx, 'tcx>,
117         source: MirSource,
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();
123         ConstPropagator {
124             ecx,
125             mir,
126             tcx,
127             source,
128             param_env,
129             can_const_prop: CanConstProp::check(mir),
130             places: IndexVec::from_elem(None, &mir.local_decls),
131         }
132     }
133
134     fn use_ecx<F, T>(
135         &mut self,
136         source_info: SourceInfo,
137         f: F
138     ) -> Option<T>
139     where
140         F: FnOnce(&mut Self) -> EvalResult<'tcx, T>,
141     {
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() {
147                     return None;
148                 }
149                 ivs[source_info.scope].lint_root
150             },
151             ClearCrossCrate::Clear => return None,
152         };
153         let r = match f(self) {
154             Ok(val) => Some(val),
155             Err(error) => {
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
160                     | MachineError(_)
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
168                     | ReadBytesAsPointer
169                     // fine at runtime
170                     | ReadForeignStatic
171                     | Unimplemented(_)
172                     // don't report const evaluator limits
173                     | StackFrameLimitReached
174                     | NoMirFor(..)
175                     | InlineAsm
176                     => {},
177
178                     | InvalidMemoryAccess
179                     | DanglingPointerDeref
180                     | DoubleFree
181                     | InvalidFunctionPointer
182                     | InvalidBool
183                     | InvalidDiscriminant(..)
184                     | PointerOutOfBounds { .. }
185                     | InvalidNullPointerUsage
186                     | ValidationFailure(..)
187                     | InvalidPointerMath
188                     | ReadUndefBytes(_)
189                     | DeadLocal
190                     | InvalidBoolOp(_)
191                     | DerefFunctionPointer
192                     | ExecuteMemory
193                     | Intrinsic(..)
194                     | InvalidChar(..)
195                     | AbiViolation(_)
196                     | AlignmentCheckFailed{..}
197                     | CalledClosureAsFunction
198                     | VtableForArgumentlessMethod
199                     | ModifiedConstantMemory
200                     | AssumptionNotHeld
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(_)
209                     | HeapAllocZeroBytes
210                     | HeapAllocNonPowerOfTwoAlignment(_)
211                     | Unreachable
212                     | ReadFromReturnPointer
213                     | GeneratorResumedAfterReturn
214                     | GeneratorResumedAfterPanic
215                     | ReferencedConstant
216                     | InfiniteLoop
217                     => {
218                         // FIXME: report UB here
219                     },
220
221                     | OutOfTls
222                     | TlsOutOfBounds
223                     | PathNotFound(_)
224                     => bug!("these should not be in rustc, but in miri's machine errors"),
225
226                     | Layout(_)
227                     | UnimplementedTraitSelection
228                     | TypeckError
229                     | TooGeneric
230                     // these are just noise
231                     => {},
232
233                     // non deterministic
234                     | ReadPointerAsBytes
235                     // FIXME: implement
236                     => {},
237
238                     | Panic { .. }
239                     | BoundsCheck{..}
240                     | Overflow(_)
241                     | OverflowNeg
242                     | DivisionByZero
243                     | RemainderByZero
244                     => {
245                         diagnostic.report_as_lint(
246                             self.ecx.tcx,
247                             "this expression will panic at runtime",
248                             lint_root,
249                         );
250                     }
251                 }
252                 None
253             },
254         };
255         self.ecx.tcx.span = DUMMY_SP;
256         r
257     }
258
259     fn eval_constant(
260         &mut self,
261         c: &Constant<'tcx>,
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) {
266             Ok(op) => {
267                 Some((op, c.span))
268             },
269             Err(error) => {
270                 let err = error_to_const_error(&self.ecx, error);
271                 err.report_as_error(self.ecx.tcx, "erroneous constant used");
272                 None
273             },
274         }
275     }
276
277     fn eval_place(&mut self, place: &Place<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
278         match *place {
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)
286                     })?;
287                     Some((res, span))
288                 },
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.
292                 _ => None,
293             },
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
298                     return None;
299                 }
300                 let substs = Substs::identity_for_item(self.tcx, self.source.def_id);
301                 let instance = Instance::new(self.source.def_id, substs);
302                 let cid = GlobalId {
303                     instance,
304                     promoted: Some(promoted.0),
305                 };
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)
310                 })?;
311                 trace!("evaluated promoted {:?} to {:?}", promoted, res);
312                 Some((res, source_info.span))
313             },
314             _ => None,
315         }
316     }
317
318     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
319         match *op {
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),
323         }
324     }
325
326     fn const_prop(
327         &mut self,
328         rvalue: &Rvalue<'tcx>,
329         place_layout: TyLayout<'tcx>,
330         source_info: SourceInfo,
331     ) -> Option<Const<'tcx>> {
332         let span = source_info.span;
333         match *rvalue {
334             Rvalue::Use(ref op) => {
335                 self.eval_operand(op, source_info)
336             },
337             Rvalue::Repeat(..) |
338             Rvalue::Ref(..) |
339             Rvalue::Aggregate(..) |
340             Rvalue::NullaryOp(NullOp::Box, _) |
341             Rvalue::Discriminant(..) => None,
342
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))
349                 })
350             }
351
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((
356                     OpTy {
357                         op: interpret::Operand::Immediate(Immediate::Scalar(
358                             Scalar::Bits {
359                                 bits: n as u128,
360                                 size: self.tcx.data_layout.pointer_size.bytes() as u8,
361                             }.into()
362                         )),
363                         layout: self.tcx.layout_of(self.param_env.and(self.tcx.types.usize)).ok()?,
364                     },
365                     span,
366                 )))
367             }
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)
371                 } else {
372                     self.source.def_id
373                 };
374                 let generics = self.tcx.generics_of(def_id);
375                 if generics.requires_monomorphization(self.tcx) {
376                     // FIXME: can't handle code with generics
377                     return None;
378                 }
379
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()?;
383                     match op {
384                         UnOp::Neg => {
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);
390                             }
391                         }
392                         UnOp::Not => {
393                             // Cannot overflow
394                         }
395                     }
396                     // Now run the actual operation.
397                     this.ecx.unary_op(op, prim, arg.layout)
398                 })?;
399                 let res = OpTy {
400                     op: interpret::Operand::Immediate(Immediate::Scalar(val.into())),
401                     layout: place_layout,
402                 };
403                 Some((res, span))
404             }
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)
411                 } else {
412                     self.source.def_id
413                 };
414                 let generics = self.tcx.generics_of(def_id);
415                 if generics.requires_monomorphization(self.tcx) {
416                     // FIXME: can't handle code with generics
417                     return None;
418                 }
419
420                 let r = self.use_ecx(source_info, |this| {
421                     this.ecx.read_immediate(right.0)
422                 })?;
423                 if op == BinOp::Shr || op == BinOp::Shl {
424                     let left_ty = left.ty(self.mir, self.tcx);
425                     let left_bits = self
426                         .tcx
427                         .layout_of(self.param_env.and(left_ty))
428                         .unwrap()
429                         .size
430                         .bits();
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,
437                         };
438                         let dir = if op == BinOp::Shr {
439                             "right"
440                         } else {
441                             "left"
442                         };
443                         let node_id = source_scope_local_data[source_info.scope].lint_root;
444                         self.tcx.lint_node(
445                             ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
446                             node_id,
447                             span,
448                             &format!("attempt to shift {} with overflow", dir));
449                         return None;
450                     }
451                 }
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)
455                 })?;
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)
459                 })?;
460                 let val = if let Rvalue::CheckedBinaryOp(..) = *rvalue {
461                     Immediate::ScalarPair(
462                         val.into(),
463                         Scalar::from_bool(overflow).into(),
464                     )
465                 } else {
466                     if overflow {
467                         let err = EvalErrorKind::Overflow(op).into();
468                         let _: Option<()> = self.use_ecx(source_info, |_| Err(err));
469                         return None;
470                     }
471                     Immediate::Scalar(val.into())
472                 };
473                 let res = OpTy {
474                     op: interpret::Operand::Immediate(val),
475                     layout: place_layout,
476                 };
477                 Some((res, span))
478             },
479         }
480     }
481 }
482
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())
487 }
488
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>,
493 }
494
495 impl CanConstProp {
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),
501         };
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
505             //        lint for x != y
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;
509         }
510         cpv.visit_mir(mir);
511         cpv.can_const_prop
512     }
513 }
514
515 impl<'tcx> Visitor<'tcx> for CanConstProp {
516     fn visit_local(
517         &mut self,
518         &local: &Local,
519         context: PlaceContext<'tcx>,
520         _: Location,
521     ) {
522         use rustc::mir::visit::PlaceContext::*;
523         match context {
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;
529             } else {
530                 self.found_assignment[local] = true
531             },
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) |
538             NonUse(_) => {},
539             _ => self.can_const_prop[local] = false,
540         }
541     }
542 }
543
544 impl<'b, 'a, 'tcx> Visitor<'tcx> for ConstPropagator<'b, 'a, 'tcx> {
545     fn visit_constant(
546         &mut self,
547         constant: &Constant<'tcx>,
548         location: Location,
549     ) {
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);
554     }
555
556     fn visit_statement(
557         &mut self,
558         block: BasicBlock,
559         statement: &Statement<'tcx>,
560         location: Location,
561     ) {
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)
566                 .to_ty(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);
575                         }
576                     }
577                 }
578             }
579         }
580         self.super_statement(block, statement, location);
581     }
582
583     fn visit_terminator_kind(
584         &mut self,
585         block: BasicBlock,
586         kind: &TerminatorKind<'tcx>,
587         location: Location,
588     ) {
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
598                     match cond {
599                         Operand::Move(ref place) | Operand::Copy(ref place) => {
600                             let mut place = place;
601                             while let Place::Projection(ref proj) = *place {
602                                 place = &proj.base;
603                             }
604                             if let Place::Local(local) = *place {
605                                 self.places[local] = None;
606                             }
607                         },
608                         Operand::Constant(_) => {}
609                     }
610                     let span = self.mir[block]
611                         .terminator
612                         .as_ref()
613                         .unwrap()
614                         .source_info
615                         .span;
616                     let node_id = self
617                         .tcx
618                         .hir
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 {
623                         Overflow(_) |
624                         OverflowNeg |
625                         DivisionByZero |
626                         RemainderByZero => msg.description().to_owned(),
627                         BoundsCheck { ref len, ref index } => {
628                             let len = self
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 {
633                                     bits, ..
634                                 })) => bits,
635                                 other => bug!("const len not primitive: {:?}", other),
636                             };
637                             let index = self
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 {
642                                     bits, ..
643                                 })) => bits,
644                                 other => bug!("const index not primitive: {:?}", other),
645                             };
646                             format!(
647                                 "index out of bounds: \
648                                 the len is {} but the index is {}",
649                                 len,
650                                 index,
651                             )
652                         },
653                         // Need proper const propagator for these
654                         _ => return,
655                     };
656                     self.tcx.lint_node(
657                         ::rustc::lint::builtin::CONST_ERR,
658                         node_id,
659                         span,
660                         &msg,
661                     );
662                 }
663             }
664         }
665     }
666 }