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