]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/const_prop.rs
Get rid of the fake stack frame
[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, 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::Substs;
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 interpret::{self, EvalContext, ScalarMaybeUndef, Immediate, OpTy, MemoryKind};
22 use const_eval::{
23     CompileTimeInterpreter, error_to_const_error, eval_promoted, mk_eval_cx,
24     lazy_const_to_op,
25 };
26 use transform::{MirPass, MirSource};
27
28 pub struct ConstProp;
29
30 impl MirPass for ConstProp {
31     fn run_pass<'a, 'tcx>(&self,
32                           tcx: TyCtxt<'a, 'tcx, 'tcx>,
33                           source: MirSource,
34                           mir: &mut Mir<'tcx>) {
35         // will be evaluated by miri and produce its errors there
36         if source.promoted.is_some() {
37             return;
38         }
39
40         use rustc::hir::map::blocks::FnLikeNode;
41         let node_id = tcx.hir().as_local_node_id(source.def_id)
42                              .expect("Non-local call to local provider is_const_fn");
43
44         let is_fn_like = FnLikeNode::from_node(tcx.hir().get(node_id)).is_some();
45         let is_assoc_const = match tcx.describe_def(source.def_id) {
46             Some(Def::AssociatedConst(_)) => true,
47             _ => false,
48         };
49
50         // Only run const prop on functions, methods, closures and associated constants
51         if !is_fn_like && !is_assoc_const  {
52             // skip anon_const/statics/consts because they'll be evaluated by miri anyway
53             trace!("ConstProp skipped for {:?}", source.def_id);
54             return
55         }
56
57         trace!("ConstProp starting for {:?}", source.def_id);
58
59         // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
60         // constants, instead of just checking for const-folding succeeding.
61         // That would require an uniform one-def no-mutation analysis
62         // and RPO (or recursing when needing the value of a local).
63         let mut optimization_finder = ConstPropagator::new(mir, tcx, source);
64         optimization_finder.visit_mir(mir);
65
66         trace!("ConstProp done for {:?}", source.def_id);
67     }
68 }
69
70 type Const<'tcx> = (OpTy<'tcx>, Span);
71
72 /// Finds optimization opportunities on the MIR.
73 struct ConstPropagator<'a, 'mir, 'tcx:'a+'mir> {
74     ecx: EvalContext<'a, 'mir, 'tcx, CompileTimeInterpreter<'a, 'mir, 'tcx>>,
75     mir: &'mir Mir<'tcx>,
76     tcx: TyCtxt<'a, 'tcx, 'tcx>,
77     source: MirSource,
78     places: IndexVec<Local, Option<Const<'tcx>>>,
79     can_const_prop: IndexVec<Local, bool>,
80     param_env: ParamEnv<'tcx>,
81 }
82
83 impl<'a, 'b, 'tcx> LayoutOf for ConstPropagator<'a, 'b, 'tcx> {
84     type Ty = ty::Ty<'tcx>;
85     type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
86
87     fn layout_of(&self, ty: ty::Ty<'tcx>) -> Self::TyLayout {
88         self.tcx.layout_of(self.param_env.and(ty))
89     }
90 }
91
92 impl<'a, 'b, 'tcx> HasDataLayout for ConstPropagator<'a, 'b, 'tcx> {
93     #[inline]
94     fn data_layout(&self) -> &TargetDataLayout {
95         &self.tcx.data_layout
96     }
97 }
98
99 impl<'a, 'b, 'tcx> HasTyCtxt<'tcx> for ConstPropagator<'a, 'b, 'tcx> {
100     #[inline]
101     fn tcx<'c>(&'c self) -> TyCtxt<'c, 'tcx, 'tcx> {
102         self.tcx
103     }
104 }
105
106 impl<'a, 'mir, 'tcx> ConstPropagator<'a, 'mir, 'tcx> {
107     fn new(
108         mir: &'mir Mir<'tcx>,
109         tcx: TyCtxt<'a, 'tcx, 'tcx>,
110         source: MirSource,
111     ) -> ConstPropagator<'a, 'mir, 'tcx> {
112         let param_env = tcx.param_env(source.def_id);
113         let ecx = mk_eval_cx(tcx, param_env);
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                 //FIXME(#51314): remove this check
137                 if source_info.scope.index() >= ivs.len() {
138                     return None;
139                 }
140                 ivs[source_info.scope].lint_root
141             },
142             ClearCrossCrate::Clear => return None,
143         };
144         let r = match f(self) {
145             Ok(val) => Some(val),
146             Err(error) => {
147                 let diagnostic = error_to_const_error(&self.ecx, error);
148                 use rustc::mir::interpret::EvalErrorKind::*;
149                 match diagnostic.error {
150                     // don't report these, they make no sense in a const prop context
151                     | MachineError(_)
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                         );
242                     }
243                 }
244                 None
245             },
246         };
247         self.ecx.tcx.span = DUMMY_SP;
248         r
249     }
250
251     fn eval_constant(
252         &mut self,
253         c: &Constant<'tcx>,
254         source_info: SourceInfo,
255     ) -> Option<Const<'tcx>> {
256         self.ecx.tcx.span = source_info.span;
257         match lazy_const_to_op(&self.ecx, *c.literal, c.ty) {
258             Ok(op) => {
259                 Some((op, c.span))
260             },
261             Err(error) => {
262                 let err = error_to_const_error(&self.ecx, error);
263                 err.report_as_error(self.ecx.tcx, "erroneous constant used");
264                 None
265             },
266         }
267     }
268
269     fn eval_place(&mut self, place: &Place<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
270         match *place {
271             Place::Local(loc) => self.places[loc].clone(),
272             Place::Projection(ref proj) => match proj.elem {
273                 ProjectionElem::Field(field, _) => {
274                     trace!("field proj on {:?}", proj.base);
275                     let (base, span) = self.eval_place(&proj.base, source_info)?;
276                     let res = self.use_ecx(source_info, |this| {
277                         this.ecx.operand_field(base, field.index() as u64)
278                     })?;
279                     Some((res, span))
280                 },
281                 // We could get more projections by using e.g., `operand_projection`,
282                 // but we do not even have the stack frame set up properly so
283                 // an `Index` projection would throw us off-track.
284                 _ => None,
285             },
286             Place::Promoted(ref promoted) => {
287                 let generics = self.tcx.generics_of(self.source.def_id);
288                 if generics.requires_monomorphization(self.tcx) {
289                     // FIXME: can't handle code with generics
290                     return None;
291                 }
292                 let substs = Substs::identity_for_item(self.tcx, self.source.def_id);
293                 let instance = Instance::new(self.source.def_id, substs);
294                 let cid = GlobalId {
295                     instance,
296                     promoted: Some(promoted.0),
297                 };
298                 // cannot use `const_eval` here, because that would require having the MIR
299                 // for the current function available, but we're producing said MIR right now
300                 let res = self.use_ecx(source_info, |this| {
301                     eval_promoted(this.tcx, cid, this.mir, this.param_env)
302                 })?;
303                 trace!("evaluated promoted {:?} to {:?}", promoted, res);
304                 Some((res.into(), source_info.span))
305             },
306             _ => None,
307         }
308     }
309
310     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<Const<'tcx>> {
311         match *op {
312             Operand::Constant(ref c) => self.eval_constant(c, source_info),
313             | Operand::Move(ref place)
314             | Operand::Copy(ref place) => self.eval_place(place, source_info),
315         }
316     }
317
318     fn const_prop(
319         &mut self,
320         rvalue: &Rvalue<'tcx>,
321         place_layout: TyLayout<'tcx>,
322         source_info: SourceInfo,
323     ) -> Option<Const<'tcx>> {
324         let span = source_info.span;
325         match *rvalue {
326             Rvalue::Use(ref op) => {
327                 self.eval_operand(op, source_info)
328             },
329             Rvalue::Repeat(..) |
330             Rvalue::Ref(..) |
331             Rvalue::Aggregate(..) |
332             Rvalue::NullaryOp(NullOp::Box, _) |
333             Rvalue::Discriminant(..) => None,
334
335             Rvalue::Cast(kind, ref operand, _) => {
336                 let (op, span) = self.eval_operand(operand, source_info)?;
337                 self.use_ecx(source_info, |this| {
338                     let dest = this.ecx.allocate(place_layout, MemoryKind::Stack);
339                     this.ecx.cast(op, kind, dest.into())?;
340                     Ok((dest.into(), span))
341                 })
342             }
343
344             // FIXME(oli-obk): evaluate static/constant slice lengths
345             Rvalue::Len(_) => None,
346             Rvalue::NullaryOp(NullOp::SizeOf, ty) => {
347                 type_size_of(self.tcx, self.param_env, ty).and_then(|n| Some((
348                     OpTy {
349                         op: interpret::Operand::Immediate(Immediate::Scalar(
350                             Scalar::Bits {
351                                 bits: n as u128,
352                                 size: self.tcx.data_layout.pointer_size.bytes() as u8,
353                             }.into()
354                         )),
355                         layout: self.tcx.layout_of(self.param_env.and(self.tcx.types.usize)).ok()?,
356                     },
357                     span,
358                 )))
359             }
360             Rvalue::UnaryOp(op, ref arg) => {
361                 let def_id = if self.tcx.is_closure(self.source.def_id) {
362                     self.tcx.closure_base_def_id(self.source.def_id)
363                 } else {
364                     self.source.def_id
365                 };
366                 let generics = self.tcx.generics_of(def_id);
367                 if generics.requires_monomorphization(self.tcx) {
368                     // FIXME: can't handle code with generics
369                     return None;
370                 }
371
372                 let (arg, _) = self.eval_operand(arg, source_info)?;
373                 let val = self.use_ecx(source_info, |this| {
374                     let prim = this.ecx.read_scalar(arg)?.not_undef()?;
375                     match op {
376                         UnOp::Neg => {
377                             // Need to do overflow check here: For actual CTFE, MIR
378                             // generation emits code that does this before calling the op.
379                             let size = arg.layout.size;
380                             if prim.to_bits(size)? == (1 << (size.bits() - 1)) {
381                                 return err!(OverflowNeg);
382                             }
383                         }
384                         UnOp::Not => {
385                             // Cannot overflow
386                         }
387                     }
388                     // Now run the actual operation.
389                     this.ecx.unary_op(op, prim, arg.layout)
390                 })?;
391                 let res = OpTy {
392                     op: interpret::Operand::Immediate(Immediate::Scalar(val.into())),
393                     layout: place_layout,
394                 };
395                 Some((res, span))
396             }
397             Rvalue::CheckedBinaryOp(op, ref left, ref right) |
398             Rvalue::BinaryOp(op, ref left, ref right) => {
399                 trace!("rvalue binop {:?} for {:?} and {:?}", op, left, right);
400                 let right = self.eval_operand(right, source_info)?;
401                 let def_id = if self.tcx.is_closure(self.source.def_id) {
402                     self.tcx.closure_base_def_id(self.source.def_id)
403                 } else {
404                     self.source.def_id
405                 };
406                 let generics = self.tcx.generics_of(def_id);
407                 if generics.requires_monomorphization(self.tcx) {
408                     // FIXME: can't handle code with generics
409                     return None;
410                 }
411
412                 let r = self.use_ecx(source_info, |this| {
413                     this.ecx.read_immediate(right.0)
414                 })?;
415                 if op == BinOp::Shr || op == BinOp::Shl {
416                     let left_ty = left.ty(self.mir, self.tcx);
417                     let left_bits = self
418                         .tcx
419                         .layout_of(self.param_env.and(left_ty))
420                         .unwrap()
421                         .size
422                         .bits();
423                     let right_size = right.0.layout.size;
424                     let r_bits = r.to_scalar().and_then(|r| r.to_bits(right_size));
425                     if r_bits.ok().map_or(false, |b| b >= left_bits as u128) {
426                         let source_scope_local_data = match self.mir.source_scope_local_data {
427                             ClearCrossCrate::Set(ref data) => data,
428                             ClearCrossCrate::Clear => return None,
429                         };
430                         let dir = if op == BinOp::Shr {
431                             "right"
432                         } else {
433                             "left"
434                         };
435                         let node_id = source_scope_local_data[source_info.scope].lint_root;
436                         self.tcx.lint_node(
437                             ::rustc::lint::builtin::EXCEEDING_BITSHIFTS,
438                             node_id,
439                             span,
440                             &format!("attempt to shift {} with overflow", dir));
441                         return None;
442                     }
443                 }
444                 let left = self.eval_operand(left, source_info)?;
445                 let l = self.use_ecx(source_info, |this| {
446                     this.ecx.read_immediate(left.0)
447                 })?;
448                 trace!("const evaluating {:?} for {:?} and {:?}", op, left, right);
449                 let (val, overflow) = self.use_ecx(source_info, |this| {
450                     this.ecx.binary_op_imm(op, l, r)
451                 })?;
452                 let val = if let Rvalue::CheckedBinaryOp(..) = *rvalue {
453                     Immediate::ScalarPair(
454                         val.into(),
455                         Scalar::from_bool(overflow).into(),
456                     )
457                 } else {
458                     if overflow {
459                         let err = EvalErrorKind::Overflow(op).into();
460                         let _: Option<()> = self.use_ecx(source_info, |_| Err(err));
461                         return None;
462                     }
463                     Immediate::Scalar(val.into())
464                 };
465                 let res = OpTy {
466                     op: interpret::Operand::Immediate(val),
467                     layout: place_layout,
468                 };
469                 Some((res, span))
470             },
471         }
472     }
473 }
474
475 fn type_size_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
476                           param_env: ty::ParamEnv<'tcx>,
477                           ty: ty::Ty<'tcx>) -> Option<u64> {
478     tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
479 }
480
481 struct CanConstProp {
482     can_const_prop: IndexVec<Local, bool>,
483     // false at the beginning, once set, there are not allowed to be any more assignments
484     found_assignment: IndexVec<Local, bool>,
485 }
486
487 impl CanConstProp {
488     /// returns true if `local` can be propagated
489     fn check(mir: &Mir) -> IndexVec<Local, bool> {
490         let mut cpv = CanConstProp {
491             can_const_prop: IndexVec::from_elem(true, &mir.local_decls),
492             found_assignment: IndexVec::from_elem(false, &mir.local_decls),
493         };
494         for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
495             // cannot use args at all
496             // cannot use locals because if x < y { y - x } else { x - y } would
497             //        lint for x != y
498             // FIXME(oli-obk): lint variables until they are used in a condition
499             // FIXME(oli-obk): lint if return value is constant
500             *val = mir.local_kind(local) == LocalKind::Temp;
501         }
502         cpv.visit_mir(mir);
503         cpv.can_const_prop
504     }
505 }
506
507 impl<'tcx> Visitor<'tcx> for CanConstProp {
508     fn visit_local(
509         &mut self,
510         &local: &Local,
511         context: PlaceContext<'tcx>,
512         _: Location,
513     ) {
514         use rustc::mir::visit::PlaceContext::*;
515         match context {
516             // Constants must have at most one write
517             // FIXME(oli-obk): we could be more powerful here, if the multiple writes
518             // only occur in independent execution paths
519             MutatingUse(MutatingUseContext::Store) => if self.found_assignment[local] {
520                 self.can_const_prop[local] = false;
521             } else {
522                 self.found_assignment[local] = true
523             },
524             // Reading constants is allowed an arbitrary number of times
525             NonMutatingUse(NonMutatingUseContext::Copy) |
526             NonMutatingUse(NonMutatingUseContext::Move) |
527             NonMutatingUse(NonMutatingUseContext::Inspect) |
528             NonMutatingUse(NonMutatingUseContext::Projection) |
529             MutatingUse(MutatingUseContext::Projection) |
530             NonUse(_) => {},
531             _ => self.can_const_prop[local] = false,
532         }
533     }
534 }
535
536 impl<'b, 'a, 'tcx> Visitor<'tcx> for ConstPropagator<'b, 'a, 'tcx> {
537     fn visit_constant(
538         &mut self,
539         constant: &Constant<'tcx>,
540         location: Location,
541     ) {
542         trace!("visit_constant: {:?}", constant);
543         self.super_constant(constant, location);
544         let source_info = *self.mir.source_info(location);
545         self.eval_constant(constant, source_info);
546     }
547
548     fn visit_statement(
549         &mut self,
550         block: BasicBlock,
551         statement: &Statement<'tcx>,
552         location: Location,
553     ) {
554         trace!("visit_statement: {:?}", statement);
555         if let StatementKind::Assign(ref place, ref rval) = statement.kind {
556             let place_ty: ty::Ty<'tcx> = place
557                 .ty(&self.mir.local_decls, self.tcx)
558                 .to_ty(self.tcx);
559             if let Ok(place_layout) = self.tcx.layout_of(self.param_env.and(place_ty)) {
560                 if let Some(value) = self.const_prop(rval, place_layout, statement.source_info) {
561                     if let Place::Local(local) = *place {
562                         trace!("checking whether {:?} can be stored to {:?}", value, local);
563                         if self.can_const_prop[local] {
564                             trace!("storing {:?} to {:?}", value, local);
565                             assert!(self.places[local].is_none());
566                             self.places[local] = Some(value);
567                         }
568                     }
569                 }
570             }
571         }
572         self.super_statement(block, statement, location);
573     }
574
575     fn visit_terminator_kind(
576         &mut self,
577         block: BasicBlock,
578         kind: &TerminatorKind<'tcx>,
579         location: Location,
580     ) {
581         self.super_terminator_kind(block, 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::Local(local) = *place {
597                                 self.places[local] = None;
598                             }
599                         },
600                         Operand::Constant(_) => {}
601                     }
602                     let span = self.mir[block]
603                         .terminator
604                         .as_ref()
605                         .unwrap()
606                         .source_info
607                         .span;
608                     let node_id = self
609                         .tcx
610                         .hir()
611                         .as_local_node_id(self.source.def_id)
612                         .expect("some part of a failing const eval must be local");
613                     use rustc::mir::interpret::EvalErrorKind::*;
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_node(
649                         ::rustc::lint::builtin::CONST_ERR,
650                         node_id,
651                         span,
652                         &msg,
653                     );
654                 }
655             }
656         }
657     }
658 }