]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/const_prop.rs
Auto merge of #58902 - matthewjasper:generator-cleanup-blocks, r=davidtwco
[rust.git] / src / librustc_mir / transform / const_prop.rs
1 //! Propagates constants for early reporting of statically known
2 //! assertion failures
3
4
5 use rustc::hir::def::Def;
6 use rustc::mir::{Constant, Location, Place, PlaceBase, Mir, Operand, Rvalue, Local};
7 use rustc::mir::{NullOp, UnOp, StatementKind, Statement, BasicBlock, LocalKind};
8 use rustc::mir::{TerminatorKind, ClearCrossCrate, SourceInfo, BinOp, ProjectionElem};
9 use rustc::mir::visit::{Visitor, PlaceContext, MutatingUseContext, NonMutatingUseContext};
10 use rustc::mir::interpret::{EvalErrorKind, Scalar, GlobalId, EvalResult};
11 use rustc::ty::{TyCtxt, self, Instance};
12 use syntax::source_map::{Span, DUMMY_SP};
13 use rustc::ty::subst::InternalSubsts;
14 use rustc_data_structures::indexed_vec::IndexVec;
15 use rustc::ty::ParamEnv;
16 use rustc::ty::layout::{
17     LayoutOf, TyLayout, LayoutError,
18     HasTyCtxt, TargetDataLayout, HasDataLayout,
19 };
20
21 use crate::interpret::{EvalContext, ScalarMaybeUndef, Immediate, OpTy, ImmTy, MemoryKind};
22 use crate::const_eval::{
23     CompileTimeInterpreter, error_to_const_error, eval_promoted, mk_eval_cx,
24 };
25 use crate::transform::{MirPass, MirSource};
26
27 pub struct ConstProp;
28
29 impl MirPass for ConstProp {
30     fn run_pass<'a, 'tcx>(&self,
31                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
32                           source: MirSource<'tcx>,
33                           mir: &mut Mir<'tcx>) {
34         // will be evaluated by miri and produce its errors there
35         if source.promoted.is_some() {
36             return;
37         }
38
39         use rustc::hir::map::blocks::FnLikeNode;
40         let hir_id = tcx.hir().as_local_hir_id(source.def_id())
41                               .expect("Non-local call to local provider is_const_fn");
42
43         let is_fn_like = FnLikeNode::from_node(tcx.hir().get_by_hir_id(hir_id)).is_some();
44         let is_assoc_const = match tcx.describe_def(source.def_id()) {
45             Some(Def::AssociatedConst(_)) => true,
46             _ => false,
47         };
48
49         // Only run const prop on functions, methods, closures and associated constants
50         if !is_fn_like && !is_assoc_const  {
51             // skip anon_const/statics/consts because they'll be evaluated by miri anyway
52             trace!("ConstProp skipped for {:?}", source.def_id());
53             return
54         }
55
56         trace!("ConstProp starting for {:?}", source.def_id());
57
58         // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
59         // constants, instead of just checking for const-folding succeeding.
60         // That would require an uniform one-def no-mutation analysis
61         // and RPO (or recursing when needing the value of a local).
62         let mut optimization_finder = ConstPropagator::new(mir, tcx, source);
63         optimization_finder.visit_mir(mir);
64
65         trace!("ConstProp done for {:?}", source.def_id());
66     }
67 }
68
69 type Const<'tcx> = (OpTy<'tcx>, Span);
70
71 /// Finds optimization opportunities on the MIR.
72 struct ConstPropagator<'a, 'mir, 'tcx:'a+'mir> {
73     ecx: EvalContext<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>,
74     mir: &'mir Mir<'tcx>,
75     tcx: TyCtxt<'a, 'tcx, 'tcx>,
76     source: MirSource<'tcx>,
77     places: IndexVec<Local, Option<Const<'tcx>>>,
78     can_const_prop: IndexVec<Local, bool>,
79     param_env: ParamEnv<'tcx>,
80 }
81
82 impl<'a, 'b, 'tcx> LayoutOf for ConstPropagator<'a, 'b, 'tcx> {
83     type Ty = ty::Ty<'tcx>;
84     type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
85
86     fn layout_of(&self, ty: ty::Ty<'tcx>) -> Self::TyLayout {
87         self.tcx.layout_of(self.param_env.and(ty))
88     }
89 }
90
91 impl<'a, 'b, 'tcx> HasDataLayout for ConstPropagator<'a, 'b, 'tcx> {
92     #[inline]
93     fn data_layout(&self) -> &TargetDataLayout {
94         &self.tcx.data_layout
95     }
96 }
97
98 impl<'a, 'b, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'a, 'b, 'tcx> {
99     #[inline]
100     fn tcx<'c>(&'c self) -> TyCtxt<'c, 'tcx, 'tcx> {
101         self.tcx
102     }
103 }
104
105 impl<'a, 'mir, 'tcx> ConstPropagator<'a, 'mir, 'tcx> {
106     fn new(
107         mir: &'mir Mir<'tcx>,
108         tcx: TyCtxt<'a, 'tcx, 'tcx>,
109         source: MirSource<'tcx>,
110     ) -> ConstPropagator<'a, 'mir, 'tcx> {
111         let param_env = tcx.param_env(source.def_id());
112         let ecx = mk_eval_cx(tcx, tcx.def_span(source.def_id()), param_env);
113         ConstPropagator {
114             ecx,
115             mir,
116             tcx,
117             source,
118             param_env,
119             can_const_prop: CanConstProp::check(mir),
120             places: IndexVec::from_elem(None, &mir.local_decls),
121         }
122     }
123
124     fn use_ecx<F, T>(
125         &mut self,
126         source_info: SourceInfo,
127         f: F
128     ) -> Option<T>
129     where
130         F: FnOnce(&mut Self) -> EvalResult<'tcx, T>,
131     {
132         self.ecx.tcx.span = source_info.span;
133         let lint_root = match self.mir.source_scope_local_data {
134             ClearCrossCrate::Set(ref ivs) => {
135                 //FIXME(#51314): remove this check
136                 if source_info.scope.index() >= ivs.len() {
137                     return None;
138                 }
139                 ivs[source_info.scope].lint_root
140             },
141             ClearCrossCrate::Clear => return None,
142         };
143         let r = match f(self) {
144             Ok(val) => Some(val),
145             Err(error) => {
146                 let diagnostic = error_to_const_error(&self.ecx, error);
147                 use rustc::mir::interpret::EvalErrorKind::*;
148                 match diagnostic.error {
149                     // don't report these, they make no sense in a const prop context
150                     | MachineError(_)
151                     // at runtime these transformations might make sense
152                     // FIXME: figure out the rules and start linting
153                     | FunctionAbiMismatch(..)
154                     | FunctionArgMismatch(..)
155                     | FunctionRetMismatch(..)
156                     | FunctionArgCountMismatch
157                     // fine at runtime, might be a register address or sth
158                     | ReadBytesAsPointer
159                     // fine at runtime
160                     | ReadForeignStatic
161                     | Unimplemented(_)
162                     // don't report const evaluator limits
163                     | StackFrameLimitReached
164                     | NoMirFor(..)
165                     | InlineAsm
166                     => {},
167
168                     | InvalidMemoryAccess
169                     | DanglingPointerDeref
170                     | DoubleFree
171                     | InvalidFunctionPointer
172                     | InvalidBool
173                     | InvalidDiscriminant(..)
174                     | PointerOutOfBounds { .. }
175                     | InvalidNullPointerUsage
176                     | ValidationFailure(..)
177                     | InvalidPointerMath
178                     | ReadUndefBytes(_)
179                     | DeadLocal
180                     | InvalidBoolOp(_)
181                     | DerefFunctionPointer
182                     | ExecuteMemory
183                     | Intrinsic(..)
184                     | InvalidChar(..)
185                     | AbiViolation(_)
186                     | AlignmentCheckFailed{..}
187                     | CalledClosureAsFunction
188                     | VtableForArgumentlessMethod
189                     | ModifiedConstantMemory
190                     | ModifiedStatic
191                     | AssumptionNotHeld
192                     // FIXME: should probably be removed and turned into a bug! call
193                     | TypeNotPrimitive(_)
194                     | ReallocatedWrongMemoryKind(_, _)
195                     | DeallocatedWrongMemoryKind(_, _)
196                     | ReallocateNonBasePtr
197                     | DeallocateNonBasePtr
198                     | IncorrectAllocationInformation(..)
199                     | UnterminatedCString(_)
200                     | HeapAllocZeroBytes
201                     | HeapAllocNonPowerOfTwoAlignment(_)
202                     | Unreachable
203                     | ReadFromReturnPointer
204                     | GeneratorResumedAfterReturn
205                     | GeneratorResumedAfterPanic
206                     | ReferencedConstant
207                     | InfiniteLoop
208                     => {
209                         // FIXME: report UB here
210                     },
211
212                     | OutOfTls
213                     | TlsOutOfBounds
214                     | PathNotFound(_)
215                     => bug!("these should not be in rustc, but in miri's machine errors"),
216
217                     | Layout(_)
218                     | UnimplementedTraitSelection
219                     | TypeckError
220                     | TooGeneric
221                     // these are just noise
222                     => {},
223
224                     // non deterministic
225                     | ReadPointerAsBytes
226                     // FIXME: implement
227                     => {},
228
229                     | Panic { .. }
230                     | BoundsCheck{..}
231                     | Overflow(_)
232                     | OverflowNeg
233                     | DivisionByZero
234                     | RemainderByZero
235                     => {
236                         diagnostic.report_as_lint(
237                             self.ecx.tcx,
238                             "this expression will panic at runtime",
239                             lint_root,
240                         );
241                     }
242                 }
243                 None
244             },
245         };
246         self.ecx.tcx.span = DUMMY_SP;
247         r
248     }
249
250     fn eval_constant(
251         &mut self,
252         c: &Constant<'tcx>,
253         source_info: SourceInfo,
254     ) -> Option<Const<'tcx>> {
255         self.ecx.tcx.span = source_info.span;
256         match self.ecx.eval_const_to_op(*c.literal, None) {
257             Ok(op) => {
258                 Some((op, c.span))
259             },
260             Err(error) => {
261                 let err = error_to_const_error(&self.ecx, error);
262                 err.report_as_error(self.ecx.tcx, "erroneous constant used");
263                 None
264             },
265         }
266     }
267
268     fn eval_place(&mut self, place: &Place<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
269         match *place {
270             Place::Base(PlaceBase::Local(loc)) => self.places[loc].clone(),
271             Place::Projection(ref proj) => match proj.elem {
272                 ProjectionElem::Field(field, _) => {
273                     trace!("field proj on {:?}", proj.base);
274                     let (base, span) = self.eval_place(&proj.base, source_info)?;
275                     let res = self.use_ecx(source_info, |this| {
276                         this.ecx.operand_field(base, field.index() as u64)
277                     })?;
278                     Some((res, span))
279                 },
280                 // We could get more projections by using e.g., `operand_projection`,
281                 // but we do not even have the stack frame set up properly so
282                 // an `Index` projection would throw us off-track.
283                 _ => None,
284             },
285             Place::Base(PlaceBase::Promoted(ref promoted)) => {
286                 let generics = self.tcx.generics_of(self.source.def_id());
287                 if generics.requires_monomorphization(self.tcx) {
288                     // FIXME: can't handle code with generics
289                     return None;
290                 }
291                 let substs = InternalSubsts::identity_for_item(self.tcx, self.source.def_id());
292                 let instance = Instance::new(self.source.def_id(), substs);
293                 let cid = GlobalId {
294                     instance,
295                     promoted: Some(promoted.0),
296                 };
297                 // cannot use `const_eval` here, because that would require having the MIR
298                 // for the current function available, but we're producing said MIR right now
299                 let res = self.use_ecx(source_info, |this| {
300                     eval_promoted(this.tcx, cid, this.mir, this.param_env)
301                 })?;
302                 trace!("evaluated promoted {:?} to {:?}", promoted, res);
303                 Some((res.into(), source_info.span))
304             },
305             _ => None,
306         }
307     }
308
309     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
310         match *op {
311             Operand::Constant(ref c) => self.eval_constant(c, source_info),
312             | Operand::Move(ref place)
313             | Operand::Copy(ref place) => self.eval_place(place, source_info),
314         }
315     }
316
317     fn const_prop(
318         &mut self,
319         rvalue: &Rvalue<'tcx>,
320         place_layout: TyLayout<'tcx>,
321         source_info: SourceInfo,
322     ) -> Option<Const<'tcx>> {
323         let span = source_info.span;
324         match *rvalue {
325             Rvalue::Use(ref op) => {
326                 self.eval_operand(op, source_info)
327             },
328             Rvalue::Repeat(..) |
329             Rvalue::Ref(..) |
330             Rvalue::Aggregate(..) |
331             Rvalue::NullaryOp(NullOp::Box, _) |
332             Rvalue::Discriminant(..) => None,
333
334             Rvalue::Cast(kind, ref operand, _) => {
335                 let (op, span) = self.eval_operand(operand, source_info)?;
336                 self.use_ecx(source_info, |this| {
337                     let dest = this.ecx.allocate(place_layout, MemoryKind::Stack);
338                     this.ecx.cast(op, kind, dest.into())?;
339                     Ok((dest.into(), span))
340                 })
341             }
342
343             // FIXME(oli-obk): evaluate static/constant slice lengths
344             Rvalue::Len(_) => None,
345             Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
346                 type_size_of(self.tcx, self.param_env, ty).and_then(|n| Some((
347                     ImmTy {
348                         imm: Immediate::Scalar(
349                             Scalar::Bits {
350                                 bits: n as u128,
351                                 size: self.tcx.data_layout.pointer_size.bytes() as u8,
352                             }.into()
353                         ),
354                         layout: self.tcx.layout_of(self.param_env.and(self.tcx.types.usize)).ok()?,
355                     }.into(),
356                     span,
357                 )))
358             }
359             Rvalue::UnaryOp(op, ref arg) => {
360                 let def_id = if self.tcx.is_closure(self.source.def_id()) {
361                     self.tcx.closure_base_def_id(self.source.def_id())
362                 } else {
363                     self.source.def_id()
364                 };
365                 let generics = self.tcx.generics_of(def_id);
366                 if generics.requires_monomorphization(self.tcx) {
367                     // FIXME: can't handle code with generics
368                     return None;
369                 }
370
371                 let (arg, _) = self.eval_operand(arg, source_info)?;
372                 let val = self.use_ecx(source_info, |this| {
373                     let prim = this.ecx.read_immediate(arg)?;
374                     match op {
375                         UnOp::Neg => {
376                             // Need to do overflow check here: For actual CTFE, MIR
377                             // generation emits code that does this before calling the op.
378                             if prim.to_bits()? == (1 << (prim.layout.size.bits() - 1)) {
379                                 return err!(OverflowNeg);
380                             }
381                         }
382                         UnOp::Not => {
383                             // Cannot overflow
384                         }
385                     }
386                     // Now run the actual operation.
387                     this.ecx.unary_op(op, prim)
388                 })?;
389                 let res = ImmTy {
390                     imm: Immediate::Scalar(val.into()),
391                     layout: place_layout,
392                 };
393                 Some((res.into(), span))
394             }
395             Rvalue::CheckedBinaryOp(op, ref left, ref right) |
396             Rvalue::BinaryOp(op, ref left, ref right) => {
397                 trace!("rvalue binop {:?} for {:?} and {:?}", op, left, right);
398                 let right = self.eval_operand(right, source_info)?;
399                 let def_id = if self.tcx.is_closure(self.source.def_id()) {
400                     self.tcx.closure_base_def_id(self.source.def_id())
401                 } else {
402                     self.source.def_id()
403                 };
404                 let generics = self.tcx.generics_of(def_id);
405                 if generics.requires_monomorphization(self.tcx) {
406                     // FIXME: can't handle code with generics
407                     return None;
408                 }
409
410                 let r = self.use_ecx(source_info, |this| {
411                     this.ecx.read_immediate(right.0)
412                 })?;
413                 if op == BinOp::Shr || op == BinOp::Shl {
414                     let left_ty = left.ty(self.mir, self.tcx);
415                     let left_bits = self
416                         .tcx
417                         .layout_of(self.param_env.and(left_ty))
418                         .unwrap()
419                         .size
420                         .bits();
421                     let right_size = right.0.layout.size;
422                     let r_bits = r.to_scalar().and_then(|r| r.to_bits(right_size));
423                     if r_bits.ok().map_or(false, |b| b >= left_bits as u128) {
424                         let source_scope_local_data = match self.mir.source_scope_local_data {
425                             ClearCrossCrate::Set(ref data) => data,
426                             ClearCrossCrate::Clear => return None,
427                         };
428                         let dir = if op == BinOp::Shr {
429                             "right"
430                         } else {
431                             "left"
432                         };
433                         let hir_id = source_scope_local_data[source_info.scope].lint_root;
434                         self.tcx.lint_hir(
435                             ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
436                             hir_id,
437                             span,
438                             &format!("attempt to shift {} with overflow", dir));
439                         return None;
440                     }
441                 }
442                 let left = self.eval_operand(left, source_info)?;
443                 let l = self.use_ecx(source_info, |this| {
444                     this.ecx.read_immediate(left.0)
445                 })?;
446                 trace!("const evaluating {:?} for {:?} and {:?}", op, left, right);
447                 let (val, overflow) = self.use_ecx(source_info, |this| {
448                     this.ecx.binary_op(op, l, r)
449                 })?;
450                 let val = if let Rvalue::CheckedBinaryOp(..) = *rvalue {
451                     Immediate::ScalarPair(
452                         val.into(),
453                         Scalar::from_bool(overflow).into(),
454                     )
455                 } else {
456                     if overflow {
457                         let err = EvalErrorKind::Overflow(op).into();
458                         let _: Option<()> = self.use_ecx(source_info, |_| Err(err));
459                         return None;
460                     }
461                     Immediate::Scalar(val.into())
462                 };
463                 let res = ImmTy {
464                     imm: val,
465                     layout: place_layout,
466                 };
467                 Some((res.into(), span))
468             },
469         }
470     }
471 }
472
473 fn type_size_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
474                           param_env: ty::ParamEnv<'tcx>,
475                           ty: ty::Ty<'tcx>) -> Option<u64> {
476     tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
477 }
478
479 struct CanConstProp {
480     can_const_prop: IndexVec<Local, bool>,
481     // false at the beginning, once set, there are not allowed to be any more assignments
482     found_assignment: IndexVec<Local, bool>,
483 }
484
485 impl CanConstProp {
486     /// returns true if `local` can be propagated
487     fn check(mir: &Mir<'_>) -> IndexVec<Local, bool> {
488         let mut cpv = CanConstProp {
489             can_const_prop: IndexVec::from_elem(true, &mir.local_decls),
490             found_assignment: IndexVec::from_elem(false, &mir.local_decls),
491         };
492         for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
493             // cannot use args at all
494             // cannot use locals because if x < y { y - x } else { x - y } would
495             //        lint for x != y
496             // FIXME(oli-obk): lint variables until they are used in a condition
497             // FIXME(oli-obk): lint if return value is constant
498             *val = mir.local_kind(local) == LocalKind::Temp;
499         }
500         cpv.visit_mir(mir);
501         cpv.can_const_prop
502     }
503 }
504
505 impl<'tcx> Visitor<'tcx> for CanConstProp {
506     fn visit_local(
507         &mut self,
508         &local: &Local,
509         context: PlaceContext<'tcx>,
510         _: Location,
511     ) {
512         use rustc::mir::visit::PlaceContext::*;
513         match context {
514             // Constants must have at most one write
515             // FIXME(oli-obk): we could be more powerful here, if the multiple writes
516             // only occur in independent execution paths
517             MutatingUse(MutatingUseContext::Store) => if self.found_assignment[local] {
518                 self.can_const_prop[local] = false;
519             } else {
520                 self.found_assignment[local] = true
521             },
522             // Reading constants is allowed an arbitrary number of times
523             NonMutatingUse(NonMutatingUseContext::Copy) |
524             NonMutatingUse(NonMutatingUseContext::Move) |
525             NonMutatingUse(NonMutatingUseContext::Inspect) |
526             NonMutatingUse(NonMutatingUseContext::Projection) |
527             MutatingUse(MutatingUseContext::Projection) |
528             NonUse(_) => {},
529             _ => self.can_const_prop[local] = false,
530         }
531     }
532 }
533
534 impl<'b, 'a, 'tcx> Visitor<'tcx> for ConstPropagator<'b, 'a, 'tcx> {
535     fn visit_constant(
536         &mut self,
537         constant: &Constant<'tcx>,
538         location: Location,
539     ) {
540         trace!("visit_constant: {:?}", constant);
541         self.super_constant(constant, location);
542         let source_info = *self.mir.source_info(location);
543         self.eval_constant(constant, source_info);
544     }
545
546     fn visit_statement(
547         &mut self,
548         block: BasicBlock,
549         statement: &Statement<'tcx>,
550         location: Location,
551     ) {
552         trace!("visit_statement: {:?}", statement);
553         if let StatementKind::Assign(ref place, ref rval) = statement.kind {
554             let place_ty: ty::Ty<'tcx> = place
555                 .ty(&self.mir.local_decls, self.tcx)
556                 .to_ty(self.tcx);
557             if let Ok(place_layout) = self.tcx.layout_of(self.param_env.and(place_ty)) {
558                 if let Some(value) = self.const_prop(rval, place_layout, statement.source_info) {
559                     if let Place::Base(PlaceBase::Local(local)) = *place {
560                         trace!("checking whether {:?} can be stored to {:?}", value, local);
561                         if self.can_const_prop[local] {
562                             trace!("storing {:?} to {:?}", value, local);
563                             assert!(self.places[local].is_none());
564                             self.places[local] = Some(value);
565                         }
566                     }
567                 }
568             }
569         }
570         self.super_statement(block, statement, location);
571     }
572
573     fn visit_terminator_kind(
574         &mut self,
575         block: BasicBlock,
576         kind: &TerminatorKind<'tcx>,
577         location: Location,
578     ) {
579         self.super_terminator_kind(block, kind, location);
580         let source_info = *self.mir.source_info(location);
581         if let TerminatorKind::Assert { expected, msg, cond, .. } = kind {
582             if let Some(value) = self.eval_operand(cond, source_info) {
583                 trace!("assertion on {:?} should be {:?}", value, expected);
584                 let expected = ScalarMaybeUndef::from(Scalar::from_bool(*expected));
585                 if expected != self.ecx.read_scalar(value.0).unwrap() {
586                     // poison all places this operand references so that further code
587                     // doesn't use the invalid value
588                     match cond {
589                         Operand::Move(ref place) | Operand::Copy(ref place) => {
590                             let mut place = place;
591                             while let Place::Projection(ref proj) = *place {
592                                 place = &proj.base;
593                             }
594                             if let Place::Base(PlaceBase::Local(local)) = *place {
595                                 self.places[local] = None;
596                             }
597                         },
598                         Operand::Constant(_) => {}
599                     }
600                     let span = self.mir[block]
601                         .terminator
602                         .as_ref()
603                         .unwrap()
604                         .source_info
605                         .span;
606                     let hir_id = self
607                         .tcx
608                         .hir()
609                         .as_local_hir_id(self.source.def_id())
610                         .expect("some part of a failing const eval must be local");
611                     use rustc::mir::interpret::EvalErrorKind::*;
612                     let msg = match msg {
613                         Overflow(_) |
614                         OverflowNeg |
615                         DivisionByZero |
616                         RemainderByZero => msg.description().to_owned(),
617                         BoundsCheck { ref len, ref index } => {
618                             let len = self
619                                 .eval_operand(len, source_info)
620                                 .expect("len must be const");
621                             let len = match self.ecx.read_scalar(len.0) {
622                                 Ok(ScalarMaybeUndef::Scalar(Scalar::Bits {
623                                     bits, ..
624                                 })) => bits,
625                                 other => bug!("const len not primitive: {:?}", other),
626                             };
627                             let index = self
628                                 .eval_operand(index, source_info)
629                                 .expect("index must be const");
630                             let index = match self.ecx.read_scalar(index.0) {
631                                 Ok(ScalarMaybeUndef::Scalar(Scalar::Bits {
632                                     bits, ..
633                                 })) => bits,
634                                 other => bug!("const index not primitive: {:?}", other),
635                             };
636                             format!(
637                                 "index out of bounds: \
638                                 the len is {} but the index is {}",
639                                 len,
640                                 index,
641                             )
642                         },
643                         // Need proper const propagator for these
644                         _ => return,
645                     };
646                     self.tcx.lint_hir(
647                         ::rustc::lint::builtin::CONST_ERR,
648                         hir_id,
649                         span,
650                         &msg,
651                     );
652                 }
653             }
654         }
655     }
656 }