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