]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/const_prop_lint.rs
Add 'src/tools/rust-analyzer/' from commit '977e12a0bdc3e329af179ef3a9d466af9eb613bb'
[rust.git] / compiler / rustc_mir_transform / src / const_prop_lint.rs
1 //! Propagates constants for early reporting of statically known
2 //! assertion failures
3
4 use std::cell::Cell;
5
6 use rustc_ast::Mutability;
7 use rustc_data_structures::fx::FxHashSet;
8 use rustc_hir::def::DefKind;
9 use rustc_hir::HirId;
10 use rustc_index::bit_set::BitSet;
11 use rustc_index::vec::IndexVec;
12 use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor};
13 use rustc_middle::mir::{
14     AssertKind, BasicBlock, BinOp, Body, Constant, ConstantKind, Local, LocalDecl, LocalKind,
15     Location, Operand, Place, Rvalue, SourceInfo, SourceScope, SourceScopeData, Statement,
16     StatementKind, Terminator, TerminatorKind, UnOp, RETURN_PLACE,
17 };
18 use rustc_middle::ty::layout::{LayoutError, LayoutOf, LayoutOfHelpers, TyAndLayout};
19 use rustc_middle::ty::subst::{InternalSubsts, Subst};
20 use rustc_middle::ty::{
21     self, ConstInt, ConstKind, EarlyBinder, Instance, ParamEnv, ScalarInt, Ty, TyCtxt,
22     TypeVisitable,
23 };
24 use rustc_session::lint;
25 use rustc_span::{def_id::DefId, Span};
26 use rustc_target::abi::{HasDataLayout, Size, TargetDataLayout};
27 use rustc_target::spec::abi::Abi as CallAbi;
28 use rustc_trait_selection::traits;
29
30 use crate::MirLint;
31 use rustc_const_eval::const_eval::ConstEvalErr;
32 use rustc_const_eval::interpret::{
33     self, compile_time_machine, AllocId, ConstAllocation, Frame, ImmTy, InterpCx, InterpResult,
34     LocalState, LocalValue, MemoryKind, OpTy, PlaceTy, Pointer, Scalar, ScalarMaybeUninit,
35     StackPopCleanup, StackPopUnwind,
36 };
37
38 /// The maximum number of bytes that we'll allocate space for a local or the return value.
39 /// Needed for #66397, because otherwise we eval into large places and that can cause OOM or just
40 /// Severely regress performance.
41 const MAX_ALLOC_LIMIT: u64 = 1024;
42
43 /// Macro for machine-specific `InterpError` without allocation.
44 /// (These will never be shown to the user, but they help diagnose ICEs.)
45 macro_rules! throw_machine_stop_str {
46     ($($tt:tt)*) => {{
47         // We make a new local type for it. The type itself does not carry any information,
48         // but its vtable (for the `MachineStopType` trait) does.
49         struct Zst;
50         // Printing this type shows the desired string.
51         impl std::fmt::Display for Zst {
52             fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53                 write!(f, $($tt)*)
54             }
55         }
56         impl rustc_middle::mir::interpret::MachineStopType for Zst {}
57         throw_machine_stop!(Zst)
58     }};
59 }
60
61 pub struct ConstProp;
62
63 impl<'tcx> MirLint<'tcx> for ConstProp {
64     fn run_lint(&self, tcx: TyCtxt<'tcx>, body: &Body<'tcx>) {
65         // will be evaluated by miri and produce its errors there
66         if body.source.promoted.is_some() {
67             return;
68         }
69
70         let def_id = body.source.def_id().expect_local();
71         let is_fn_like = tcx.def_kind(def_id).is_fn_like();
72         let is_assoc_const = tcx.def_kind(def_id) == DefKind::AssocConst;
73
74         // Only run const prop on functions, methods, closures and associated constants
75         if !is_fn_like && !is_assoc_const {
76             // skip anon_const/statics/consts because they'll be evaluated by miri anyway
77             trace!("ConstProp skipped for {:?}", def_id);
78             return;
79         }
80
81         let is_generator = tcx.type_of(def_id.to_def_id()).is_generator();
82         // FIXME(welseywiser) const prop doesn't work on generators because of query cycles
83         // computing their layout.
84         if is_generator {
85             trace!("ConstProp skipped for generator {:?}", def_id);
86             return;
87         }
88
89         // Check if it's even possible to satisfy the 'where' clauses
90         // for this item.
91         // This branch will never be taken for any normal function.
92         // However, it's possible to `#!feature(trivial_bounds)]` to write
93         // a function with impossible to satisfy clauses, e.g.:
94         // `fn foo() where String: Copy {}`
95         //
96         // We don't usually need to worry about this kind of case,
97         // since we would get a compilation error if the user tried
98         // to call it. However, since we can do const propagation
99         // even without any calls to the function, we need to make
100         // sure that it even makes sense to try to evaluate the body.
101         // If there are unsatisfiable where clauses, then all bets are
102         // off, and we just give up.
103         //
104         // We manually filter the predicates, skipping anything that's not
105         // "global". We are in a potentially generic context
106         // (e.g. we are evaluating a function without substituting generic
107         // parameters, so this filtering serves two purposes:
108         //
109         // 1. We skip evaluating any predicates that we would
110         // never be able prove are unsatisfiable (e.g. `<T as Foo>`
111         // 2. We avoid trying to normalize predicates involving generic
112         // parameters (e.g. `<T as Foo>::MyItem`). This can confuse
113         // the normalization code (leading to cycle errors), since
114         // it's usually never invoked in this way.
115         let predicates = tcx
116             .predicates_of(def_id.to_def_id())
117             .predicates
118             .iter()
119             .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None });
120         if traits::impossible_predicates(
121             tcx,
122             traits::elaborate_predicates(tcx, predicates).map(|o| o.predicate).collect(),
123         ) {
124             trace!("ConstProp skipped for {:?}: found unsatisfiable predicates", def_id);
125             return;
126         }
127
128         trace!("ConstProp starting for {:?}", def_id);
129
130         let dummy_body = &Body::new(
131             body.source,
132             body.basic_blocks().clone(),
133             body.source_scopes.clone(),
134             body.local_decls.clone(),
135             Default::default(),
136             body.arg_count,
137             Default::default(),
138             body.span,
139             body.generator_kind(),
140             body.tainted_by_errors,
141         );
142
143         // FIXME(oli-obk, eddyb) Optimize locals (or even local paths) to hold
144         // constants, instead of just checking for const-folding succeeding.
145         // That would require a uniform one-def no-mutation analysis
146         // and RPO (or recursing when needing the value of a local).
147         let mut optimization_finder = ConstPropagator::new(body, dummy_body, tcx);
148         optimization_finder.visit_body(body);
149
150         trace!("ConstProp done for {:?}", def_id);
151     }
152 }
153
154 struct ConstPropMachine<'mir, 'tcx> {
155     /// The virtual call stack.
156     stack: Vec<Frame<'mir, 'tcx>>,
157     /// `OnlyInsideOwnBlock` locals that were written in the current block get erased at the end.
158     written_only_inside_own_block_locals: FxHashSet<Local>,
159     /// Locals that need to be cleared after every block terminates.
160     only_propagate_inside_block_locals: BitSet<Local>,
161     can_const_prop: IndexVec<Local, ConstPropMode>,
162 }
163
164 impl ConstPropMachine<'_, '_> {
165     fn new(
166         only_propagate_inside_block_locals: BitSet<Local>,
167         can_const_prop: IndexVec<Local, ConstPropMode>,
168     ) -> Self {
169         Self {
170             stack: Vec::new(),
171             written_only_inside_own_block_locals: Default::default(),
172             only_propagate_inside_block_locals,
173             can_const_prop,
174         }
175     }
176 }
177
178 impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine<'mir, 'tcx> {
179     compile_time_machine!(<'mir, 'tcx>);
180     const PANIC_ON_ALLOC_FAIL: bool = true; // all allocations are small (see `MAX_ALLOC_LIMIT`)
181
182     type MemoryKind = !;
183
184     fn load_mir(
185         _ecx: &InterpCx<'mir, 'tcx, Self>,
186         _instance: ty::InstanceDef<'tcx>,
187     ) -> InterpResult<'tcx, &'tcx Body<'tcx>> {
188         throw_machine_stop_str!("calling functions isn't supported in ConstProp")
189     }
190
191     fn find_mir_or_eval_fn(
192         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
193         _instance: ty::Instance<'tcx>,
194         _abi: CallAbi,
195         _args: &[OpTy<'tcx>],
196         _destination: &PlaceTy<'tcx>,
197         _target: Option<BasicBlock>,
198         _unwind: StackPopUnwind,
199     ) -> InterpResult<'tcx, Option<(&'mir Body<'tcx>, ty::Instance<'tcx>)>> {
200         Ok(None)
201     }
202
203     fn call_intrinsic(
204         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
205         _instance: ty::Instance<'tcx>,
206         _args: &[OpTy<'tcx>],
207         _destination: &PlaceTy<'tcx>,
208         _target: Option<BasicBlock>,
209         _unwind: StackPopUnwind,
210     ) -> InterpResult<'tcx> {
211         throw_machine_stop_str!("calling intrinsics isn't supported in ConstProp")
212     }
213
214     fn assert_panic(
215         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
216         _msg: &rustc_middle::mir::AssertMessage<'tcx>,
217         _unwind: Option<rustc_middle::mir::BasicBlock>,
218     ) -> InterpResult<'tcx> {
219         bug!("panics terminators are not evaluated in ConstProp")
220     }
221
222     fn binary_ptr_op(
223         _ecx: &InterpCx<'mir, 'tcx, Self>,
224         _bin_op: BinOp,
225         _left: &ImmTy<'tcx>,
226         _right: &ImmTy<'tcx>,
227     ) -> InterpResult<'tcx, (Scalar, bool, Ty<'tcx>)> {
228         // We can't do this because aliasing of memory can differ between const eval and llvm
229         throw_machine_stop_str!("pointer arithmetic or comparisons aren't supported in ConstProp")
230     }
231
232     fn access_local<'a>(
233         frame: &'a Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>,
234         local: Local,
235     ) -> InterpResult<'tcx, &'a interpret::Operand<Self::Provenance>> {
236         let l = &frame.locals[local];
237
238         if matches!(
239             l.value,
240             LocalValue::Live(interpret::Operand::Immediate(interpret::Immediate::Uninit))
241         ) {
242             // For us "uninit" means "we don't know its value, might be initiailized or not".
243             // So stop here.
244             throw_machine_stop_str!("tried to access a local with unknown value")
245         }
246
247         l.access()
248     }
249
250     fn access_local_mut<'a>(
251         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
252         frame: usize,
253         local: Local,
254     ) -> InterpResult<'tcx, &'a mut interpret::Operand<Self::Provenance>> {
255         if ecx.machine.can_const_prop[local] == ConstPropMode::NoPropagation {
256             throw_machine_stop_str!("tried to write to a local that is marked as not propagatable")
257         }
258         if frame == 0 && ecx.machine.only_propagate_inside_block_locals.contains(local) {
259             trace!(
260                 "mutating local {:?} which is restricted to its block. \
261                 Will remove it from const-prop after block is finished.",
262                 local
263             );
264             ecx.machine.written_only_inside_own_block_locals.insert(local);
265         }
266         ecx.machine.stack[frame].locals[local].access_mut()
267     }
268
269     fn before_access_global(
270         _tcx: TyCtxt<'tcx>,
271         _machine: &Self,
272         _alloc_id: AllocId,
273         alloc: ConstAllocation<'tcx, Self::Provenance, Self::AllocExtra>,
274         _static_def_id: Option<DefId>,
275         is_write: bool,
276     ) -> InterpResult<'tcx> {
277         if is_write {
278             throw_machine_stop_str!("can't write to global");
279         }
280         // If the static allocation is mutable, then we can't const prop it as its content
281         // might be different at runtime.
282         if alloc.inner().mutability == Mutability::Mut {
283             throw_machine_stop_str!("can't access mutable globals in ConstProp");
284         }
285
286         Ok(())
287     }
288
289     #[inline(always)]
290     fn expose_ptr(
291         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
292         _ptr: Pointer<AllocId>,
293     ) -> InterpResult<'tcx> {
294         throw_machine_stop_str!("exposing pointers isn't supported in ConstProp")
295     }
296
297     #[inline(always)]
298     fn init_frame_extra(
299         _ecx: &mut InterpCx<'mir, 'tcx, Self>,
300         frame: Frame<'mir, 'tcx>,
301     ) -> InterpResult<'tcx, Frame<'mir, 'tcx>> {
302         Ok(frame)
303     }
304
305     #[inline(always)]
306     fn stack<'a>(
307         ecx: &'a InterpCx<'mir, 'tcx, Self>,
308     ) -> &'a [Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>] {
309         &ecx.machine.stack
310     }
311
312     #[inline(always)]
313     fn stack_mut<'a>(
314         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
315     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>> {
316         &mut ecx.machine.stack
317     }
318 }
319
320 /// Finds optimization opportunities on the MIR.
321 struct ConstPropagator<'mir, 'tcx> {
322     ecx: InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>,
323     tcx: TyCtxt<'tcx>,
324     param_env: ParamEnv<'tcx>,
325     source_scopes: &'mir IndexVec<SourceScope, SourceScopeData<'tcx>>,
326     local_decls: &'mir IndexVec<Local, LocalDecl<'tcx>>,
327     // Because we have `MutVisitor` we can't obtain the `SourceInfo` from a `Location`. So we store
328     // the last known `SourceInfo` here and just keep revisiting it.
329     source_info: Option<SourceInfo>,
330 }
331
332 impl<'tcx> LayoutOfHelpers<'tcx> for ConstPropagator<'_, 'tcx> {
333     type LayoutOfResult = Result<TyAndLayout<'tcx>, LayoutError<'tcx>>;
334
335     #[inline]
336     fn handle_layout_err(&self, err: LayoutError<'tcx>, _: Span, _: Ty<'tcx>) -> LayoutError<'tcx> {
337         err
338     }
339 }
340
341 impl HasDataLayout for ConstPropagator<'_, '_> {
342     #[inline]
343     fn data_layout(&self) -> &TargetDataLayout {
344         &self.tcx.data_layout
345     }
346 }
347
348 impl<'tcx> ty::layout::HasTyCtxt<'tcx> for ConstPropagator<'_, 'tcx> {
349     #[inline]
350     fn tcx(&self) -> TyCtxt<'tcx> {
351         self.tcx
352     }
353 }
354
355 impl<'tcx> ty::layout::HasParamEnv<'tcx> for ConstPropagator<'_, 'tcx> {
356     #[inline]
357     fn param_env(&self) -> ty::ParamEnv<'tcx> {
358         self.param_env
359     }
360 }
361
362 impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
363     fn new(
364         body: &Body<'tcx>,
365         dummy_body: &'mir Body<'tcx>,
366         tcx: TyCtxt<'tcx>,
367     ) -> ConstPropagator<'mir, 'tcx> {
368         let def_id = body.source.def_id();
369         let substs = &InternalSubsts::identity_for_item(tcx, def_id);
370         let param_env = tcx.param_env_reveal_all_normalized(def_id);
371
372         let can_const_prop = CanConstProp::check(tcx, param_env, body);
373         let mut only_propagate_inside_block_locals = BitSet::new_empty(can_const_prop.len());
374         for (l, mode) in can_const_prop.iter_enumerated() {
375             if *mode == ConstPropMode::OnlyInsideOwnBlock {
376                 only_propagate_inside_block_locals.insert(l);
377             }
378         }
379         let mut ecx = InterpCx::new(
380             tcx,
381             tcx.def_span(def_id),
382             param_env,
383             ConstPropMachine::new(only_propagate_inside_block_locals, can_const_prop),
384         );
385
386         let ret_layout = ecx
387             .layout_of(EarlyBinder(body.return_ty()).subst(tcx, substs))
388             .ok()
389             // Don't bother allocating memory for large values.
390             // I don't know how return types can seem to be unsized but this happens in the
391             // `type/type-unsatisfiable.rs` test.
392             .filter(|ret_layout| {
393                 !ret_layout.is_unsized() && ret_layout.size < Size::from_bytes(MAX_ALLOC_LIMIT)
394             })
395             .unwrap_or_else(|| ecx.layout_of(tcx.types.unit).unwrap());
396
397         let ret = ecx
398             .allocate(ret_layout, MemoryKind::Stack)
399             .expect("couldn't perform small allocation")
400             .into();
401
402         ecx.push_stack_frame(
403             Instance::new(def_id, substs),
404             dummy_body,
405             &ret,
406             StackPopCleanup::Root { cleanup: false },
407         )
408         .expect("failed to push initial stack frame");
409
410         ConstPropagator {
411             ecx,
412             tcx,
413             param_env,
414             source_scopes: &dummy_body.source_scopes,
415             local_decls: &dummy_body.local_decls,
416             source_info: None,
417         }
418     }
419
420     fn get_const(&self, place: Place<'tcx>) -> Option<OpTy<'tcx>> {
421         let op = match self.ecx.eval_place_to_op(place, None) {
422             Ok(op) => op,
423             Err(e) => {
424                 trace!("get_const failed: {}", e);
425                 return None;
426             }
427         };
428
429         // Try to read the local as an immediate so that if it is representable as a scalar, we can
430         // handle it as such, but otherwise, just return the value as is.
431         Some(match self.ecx.read_immediate_raw(&op, /*force*/ false) {
432             Ok(Ok(imm)) => imm.into(),
433             _ => op,
434         })
435     }
436
437     /// Remove `local` from the pool of `Locals`. Allows writing to them,
438     /// but not reading from them anymore.
439     fn remove_const(ecx: &mut InterpCx<'mir, 'tcx, ConstPropMachine<'mir, 'tcx>>, local: Local) {
440         ecx.frame_mut().locals[local] = LocalState {
441             value: LocalValue::Live(interpret::Operand::Immediate(interpret::Immediate::Uninit)),
442             layout: Cell::new(None),
443         };
444     }
445
446     fn lint_root(&self, source_info: SourceInfo) -> Option<HirId> {
447         source_info.scope.lint_root(self.source_scopes)
448     }
449
450     fn use_ecx<F, T>(&mut self, source_info: SourceInfo, f: F) -> Option<T>
451     where
452         F: FnOnce(&mut Self) -> InterpResult<'tcx, T>,
453     {
454         // Overwrite the PC -- whatever the interpreter does to it does not make any sense anyway.
455         self.ecx.frame_mut().loc = Err(source_info.span);
456         match f(self) {
457             Ok(val) => Some(val),
458             Err(error) => {
459                 trace!("InterpCx operation failed: {:?}", error);
460                 // Some errors shouldn't come up because creating them causes
461                 // an allocation, which we should avoid. When that happens,
462                 // dedicated error variants should be introduced instead.
463                 assert!(
464                     !error.kind().formatted_string(),
465                     "const-prop encountered formatting error: {}",
466                     error
467                 );
468                 None
469             }
470         }
471     }
472
473     /// Returns the value, if any, of evaluating `c`.
474     fn eval_constant(&mut self, c: &Constant<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
475         // FIXME we need to revisit this for #67176
476         if c.needs_subst() {
477             return None;
478         }
479
480         match self.ecx.mir_const_to_op(&c.literal, None) {
481             Ok(op) => Some(op),
482             Err(error) => {
483                 let tcx = self.ecx.tcx.at(c.span);
484                 let err = ConstEvalErr::new(&self.ecx, error, Some(c.span));
485                 if let Some(lint_root) = self.lint_root(source_info) {
486                     let lint_only = match c.literal {
487                         ConstantKind::Ty(ct) => match ct.kind() {
488                             // Promoteds must lint and not error as the user didn't ask for them
489                             ConstKind::Unevaluated(ty::Unevaluated {
490                                 def: _,
491                                 substs: _,
492                                 promoted: Some(_),
493                             }) => true,
494                             // Out of backwards compatibility we cannot report hard errors in unused
495                             // generic functions using associated constants of the generic parameters.
496                             _ => c.literal.needs_subst(),
497                         },
498                         ConstantKind::Val(_, ty) => ty.needs_subst(),
499                     };
500                     if lint_only {
501                         // Out of backwards compatibility we cannot report hard errors in unused
502                         // generic functions using associated constants of the generic parameters.
503                         err.report_as_lint(tcx, "erroneous constant used", lint_root, Some(c.span));
504                     } else {
505                         err.report_as_error(tcx, "erroneous constant used");
506                     }
507                 } else {
508                     err.report_as_error(tcx, "erroneous constant used");
509                 }
510                 None
511             }
512         }
513     }
514
515     /// Returns the value, if any, of evaluating `place`.
516     fn eval_place(&mut self, place: Place<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
517         trace!("eval_place(place={:?})", place);
518         self.use_ecx(source_info, |this| this.ecx.eval_place_to_op(place, None))
519     }
520
521     /// Returns the value, if any, of evaluating `op`. Calls upon `eval_constant`
522     /// or `eval_place`, depending on the variant of `Operand` used.
523     fn eval_operand(&mut self, op: &Operand<'tcx>, source_info: SourceInfo) -> Option<OpTy<'tcx>> {
524         match *op {
525             Operand::Constant(ref c) => self.eval_constant(c, source_info),
526             Operand::Move(place) | Operand::Copy(place) => self.eval_place(place, source_info),
527         }
528     }
529
530     fn report_assert_as_lint(
531         &self,
532         lint: &'static lint::Lint,
533         source_info: SourceInfo,
534         message: &'static str,
535         panic: AssertKind<impl std::fmt::Debug>,
536     ) {
537         if let Some(lint_root) = self.lint_root(source_info) {
538             self.tcx.struct_span_lint_hir(lint, lint_root, source_info.span, |lint| {
539                 let mut err = lint.build(message);
540                 err.span_label(source_info.span, format!("{:?}", panic));
541                 err.emit();
542             });
543         }
544     }
545
546     fn check_unary_op(
547         &mut self,
548         op: UnOp,
549         arg: &Operand<'tcx>,
550         source_info: SourceInfo,
551     ) -> Option<()> {
552         if let (val, true) = self.use_ecx(source_info, |this| {
553             let val = this.ecx.read_immediate(&this.ecx.eval_operand(arg, None)?)?;
554             let (_res, overflow, _ty) = this.ecx.overflowing_unary_op(op, &val)?;
555             Ok((val, overflow))
556         })? {
557             // `AssertKind` only has an `OverflowNeg` variant, so make sure that is
558             // appropriate to use.
559             assert_eq!(op, UnOp::Neg, "Neg is the only UnOp that can overflow");
560             self.report_assert_as_lint(
561                 lint::builtin::ARITHMETIC_OVERFLOW,
562                 source_info,
563                 "this arithmetic operation will overflow",
564                 AssertKind::OverflowNeg(val.to_const_int()),
565             );
566             return None;
567         }
568
569         Some(())
570     }
571
572     fn check_binary_op(
573         &mut self,
574         op: BinOp,
575         left: &Operand<'tcx>,
576         right: &Operand<'tcx>,
577         source_info: SourceInfo,
578     ) -> Option<()> {
579         let r = self.use_ecx(source_info, |this| {
580             this.ecx.read_immediate(&this.ecx.eval_operand(right, None)?)
581         });
582         let l = self.use_ecx(source_info, |this| {
583             this.ecx.read_immediate(&this.ecx.eval_operand(left, None)?)
584         });
585         // Check for exceeding shifts *even if* we cannot evaluate the LHS.
586         if op == BinOp::Shr || op == BinOp::Shl {
587             let r = r.clone()?;
588             // We need the type of the LHS. We cannot use `place_layout` as that is the type
589             // of the result, which for checked binops is not the same!
590             let left_ty = left.ty(self.local_decls, self.tcx);
591             let left_size = self.ecx.layout_of(left_ty).ok()?.size;
592             let right_size = r.layout.size;
593             let r_bits = r.to_scalar().ok();
594             let r_bits = r_bits.and_then(|r| r.to_bits(right_size).ok());
595             if r_bits.map_or(false, |b| b >= left_size.bits() as u128) {
596                 debug!("check_binary_op: reporting assert for {:?}", source_info);
597                 self.report_assert_as_lint(
598                     lint::builtin::ARITHMETIC_OVERFLOW,
599                     source_info,
600                     "this arithmetic operation will overflow",
601                     AssertKind::Overflow(
602                         op,
603                         match l {
604                             Some(l) => l.to_const_int(),
605                             // Invent a dummy value, the diagnostic ignores it anyway
606                             None => ConstInt::new(
607                                 ScalarInt::try_from_uint(1_u8, left_size).unwrap(),
608                                 left_ty.is_signed(),
609                                 left_ty.is_ptr_sized_integral(),
610                             ),
611                         },
612                         r.to_const_int(),
613                     ),
614                 );
615                 return None;
616             }
617         }
618
619         if let (Some(l), Some(r)) = (l, r) {
620             // The remaining operators are handled through `overflowing_binary_op`.
621             if self.use_ecx(source_info, |this| {
622                 let (_res, overflow, _ty) = this.ecx.overflowing_binary_op(op, &l, &r)?;
623                 Ok(overflow)
624             })? {
625                 self.report_assert_as_lint(
626                     lint::builtin::ARITHMETIC_OVERFLOW,
627                     source_info,
628                     "this arithmetic operation will overflow",
629                     AssertKind::Overflow(op, l.to_const_int(), r.to_const_int()),
630                 );
631                 return None;
632             }
633         }
634         Some(())
635     }
636
637     fn const_prop(
638         &mut self,
639         rvalue: &Rvalue<'tcx>,
640         source_info: SourceInfo,
641         place: Place<'tcx>,
642     ) -> Option<()> {
643         // Perform any special handling for specific Rvalue types.
644         // Generally, checks here fall into one of two categories:
645         //   1. Additional checking to provide useful lints to the user
646         //        - In this case, we will do some validation and then fall through to the
647         //          end of the function which evals the assignment.
648         //   2. Working around bugs in other parts of the compiler
649         //        - In this case, we'll return `None` from this function to stop evaluation.
650         match rvalue {
651             // Additional checking: give lints to the user if an overflow would occur.
652             // We do this here and not in the `Assert` terminator as that terminator is
653             // only sometimes emitted (overflow checks can be disabled), but we want to always
654             // lint.
655             Rvalue::UnaryOp(op, arg) => {
656                 trace!("checking UnaryOp(op = {:?}, arg = {:?})", op, arg);
657                 self.check_unary_op(*op, arg, source_info)?;
658             }
659             Rvalue::BinaryOp(op, box (left, right)) => {
660                 trace!("checking BinaryOp(op = {:?}, left = {:?}, right = {:?})", op, left, right);
661                 self.check_binary_op(*op, left, right, source_info)?;
662             }
663             Rvalue::CheckedBinaryOp(op, box (left, right)) => {
664                 trace!(
665                     "checking CheckedBinaryOp(op = {:?}, left = {:?}, right = {:?})",
666                     op,
667                     left,
668                     right
669                 );
670                 self.check_binary_op(*op, left, right, source_info)?;
671             }
672
673             // Do not try creating references (#67862)
674             Rvalue::AddressOf(_, place) | Rvalue::Ref(_, _, place) => {
675                 trace!("skipping AddressOf | Ref for {:?}", place);
676
677                 // This may be creating mutable references or immutable references to cells.
678                 // If that happens, the pointed to value could be mutated via that reference.
679                 // Since we aren't tracking references, the const propagator loses track of what
680                 // value the local has right now.
681                 // Thus, all locals that have their reference taken
682                 // must not take part in propagation.
683                 Self::remove_const(&mut self.ecx, place.local);
684
685                 return None;
686             }
687             Rvalue::ThreadLocalRef(def_id) => {
688                 trace!("skipping ThreadLocalRef({:?})", def_id);
689
690                 return None;
691             }
692
693             // There's no other checking to do at this time.
694             Rvalue::Aggregate(..)
695             | Rvalue::Use(..)
696             | Rvalue::CopyForDeref(..)
697             | Rvalue::Repeat(..)
698             | Rvalue::Len(..)
699             | Rvalue::Cast(..)
700             | Rvalue::ShallowInitBox(..)
701             | Rvalue::Discriminant(..)
702             | Rvalue::NullaryOp(..) => {}
703         }
704
705         // FIXME we need to revisit this for #67176
706         if rvalue.needs_subst() {
707             return None;
708         }
709
710         self.use_ecx(source_info, |this| this.ecx.eval_rvalue_into_place(rvalue, place))
711     }
712 }
713
714 /// The mode that `ConstProp` is allowed to run in for a given `Local`.
715 #[derive(Clone, Copy, Debug, PartialEq)]
716 enum ConstPropMode {
717     /// The `Local` can be propagated into and reads of this `Local` can also be propagated.
718     FullConstProp,
719     /// The `Local` can only be propagated into and from its own block.
720     OnlyInsideOwnBlock,
721     /// The `Local` can be propagated into but reads cannot be propagated.
722     OnlyPropagateInto,
723     /// The `Local` cannot be part of propagation at all. Any statement
724     /// referencing it either for reading or writing will not get propagated.
725     NoPropagation,
726 }
727
728 struct CanConstProp {
729     can_const_prop: IndexVec<Local, ConstPropMode>,
730     // False at the beginning. Once set, no more assignments are allowed to that local.
731     found_assignment: BitSet<Local>,
732     // Cache of locals' information
733     local_kinds: IndexVec<Local, LocalKind>,
734 }
735
736 impl CanConstProp {
737     /// Returns true if `local` can be propagated
738     fn check<'tcx>(
739         tcx: TyCtxt<'tcx>,
740         param_env: ParamEnv<'tcx>,
741         body: &Body<'tcx>,
742     ) -> IndexVec<Local, ConstPropMode> {
743         let mut cpv = CanConstProp {
744             can_const_prop: IndexVec::from_elem(ConstPropMode::FullConstProp, &body.local_decls),
745             found_assignment: BitSet::new_empty(body.local_decls.len()),
746             local_kinds: IndexVec::from_fn_n(
747                 |local| body.local_kind(local),
748                 body.local_decls.len(),
749             ),
750         };
751         for (local, val) in cpv.can_const_prop.iter_enumerated_mut() {
752             let ty = body.local_decls[local].ty;
753             match tcx.layout_of(param_env.and(ty)) {
754                 Ok(layout) if layout.size < Size::from_bytes(MAX_ALLOC_LIMIT) => {}
755                 // Either the layout fails to compute, then we can't use this local anyway
756                 // or the local is too large, then we don't want to.
757                 _ => {
758                     *val = ConstPropMode::NoPropagation;
759                     continue;
760                 }
761             }
762             // Cannot use args at all
763             // Cannot use locals because if x < y { y - x } else { x - y } would
764             //        lint for x != y
765             // FIXME(oli-obk): lint variables until they are used in a condition
766             // FIXME(oli-obk): lint if return value is constant
767             if cpv.local_kinds[local] == LocalKind::Arg {
768                 *val = ConstPropMode::OnlyPropagateInto;
769                 trace!(
770                     "local {:?} can't be const propagated because it's a function argument",
771                     local
772                 );
773             } else if cpv.local_kinds[local] == LocalKind::Var {
774                 *val = ConstPropMode::OnlyInsideOwnBlock;
775                 trace!(
776                     "local {:?} will only be propagated inside its block, because it's a user variable",
777                     local
778                 );
779             }
780         }
781         cpv.visit_body(&body);
782         cpv.can_const_prop
783     }
784 }
785
786 impl Visitor<'_> for CanConstProp {
787     fn visit_local(&mut self, local: Local, context: PlaceContext, _: Location) {
788         use rustc_middle::mir::visit::PlaceContext::*;
789         match context {
790             // Projections are fine, because `&mut foo.x` will be caught by
791             // `MutatingUseContext::Borrow` elsewhere.
792             MutatingUse(MutatingUseContext::Projection)
793             // These are just stores, where the storing is not propagatable, but there may be later
794             // mutations of the same local via `Store`
795             | MutatingUse(MutatingUseContext::Call)
796             | MutatingUse(MutatingUseContext::AsmOutput)
797             | MutatingUse(MutatingUseContext::Deinit)
798             // Actual store that can possibly even propagate a value
799             | MutatingUse(MutatingUseContext::SetDiscriminant)
800             | MutatingUse(MutatingUseContext::Store) => {
801                 if !self.found_assignment.insert(local) {
802                     match &mut self.can_const_prop[local] {
803                         // If the local can only get propagated in its own block, then we don't have
804                         // to worry about multiple assignments, as we'll nuke the const state at the
805                         // end of the block anyway, and inside the block we overwrite previous
806                         // states as applicable.
807                         ConstPropMode::OnlyInsideOwnBlock => {}
808                         ConstPropMode::NoPropagation => {}
809                         ConstPropMode::OnlyPropagateInto => {}
810                         other @ ConstPropMode::FullConstProp => {
811                             trace!(
812                                 "local {:?} can't be propagated because of multiple assignments. Previous state: {:?}",
813                                 local, other,
814                             );
815                             *other = ConstPropMode::OnlyInsideOwnBlock;
816                         }
817                     }
818                 }
819             }
820             // Reading constants is allowed an arbitrary number of times
821             NonMutatingUse(NonMutatingUseContext::Copy)
822             | NonMutatingUse(NonMutatingUseContext::Move)
823             | NonMutatingUse(NonMutatingUseContext::Inspect)
824             | NonMutatingUse(NonMutatingUseContext::Projection)
825             | NonUse(_) => {}
826
827             // These could be propagated with a smarter analysis or just some careful thinking about
828             // whether they'd be fine right now.
829             MutatingUse(MutatingUseContext::Yield)
830             | MutatingUse(MutatingUseContext::Drop)
831             | MutatingUse(MutatingUseContext::Retag)
832             // These can't ever be propagated under any scheme, as we can't reason about indirect
833             // mutation.
834             | NonMutatingUse(NonMutatingUseContext::SharedBorrow)
835             | NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
836             | NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
837             | NonMutatingUse(NonMutatingUseContext::AddressOf)
838             | MutatingUse(MutatingUseContext::Borrow)
839             | MutatingUse(MutatingUseContext::AddressOf) => {
840                 trace!("local {:?} can't be propagaged because it's used: {:?}", local, context);
841                 self.can_const_prop[local] = ConstPropMode::NoPropagation;
842             }
843         }
844     }
845 }
846
847 impl<'tcx> Visitor<'tcx> for ConstPropagator<'_, 'tcx> {
848     fn visit_body(&mut self, body: &Body<'tcx>) {
849         for (bb, data) in body.basic_blocks().iter_enumerated() {
850             self.visit_basic_block_data(bb, data);
851         }
852     }
853
854     fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
855         self.super_operand(operand, location);
856     }
857
858     fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
859         trace!("visit_constant: {:?}", constant);
860         self.super_constant(constant, location);
861         self.eval_constant(constant, self.source_info.unwrap());
862     }
863
864     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
865         trace!("visit_statement: {:?}", statement);
866         let source_info = statement.source_info;
867         self.source_info = Some(source_info);
868         if let StatementKind::Assign(box (place, ref rval)) = statement.kind {
869             let can_const_prop = self.ecx.machine.can_const_prop[place.local];
870             if let Some(()) = self.const_prop(rval, source_info, place) {
871                 match can_const_prop {
872                     ConstPropMode::OnlyInsideOwnBlock => {
873                         trace!(
874                             "found local restricted to its block. \
875                                 Will remove it from const-prop after block is finished. Local: {:?}",
876                             place.local
877                         );
878                     }
879                     ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
880                         trace!("can't propagate into {:?}", place);
881                         if place.local != RETURN_PLACE {
882                             Self::remove_const(&mut self.ecx, place.local);
883                         }
884                     }
885                     ConstPropMode::FullConstProp => {}
886                 }
887             } else {
888                 // Const prop failed, so erase the destination, ensuring that whatever happens
889                 // from here on, does not know about the previous value.
890                 // This is important in case we have
891                 // ```rust
892                 // let mut x = 42;
893                 // x = SOME_MUTABLE_STATIC;
894                 // // x must now be uninit
895                 // ```
896                 // FIXME: we overzealously erase the entire local, because that's easier to
897                 // implement.
898                 trace!(
899                     "propagation into {:?} failed.
900                         Nuking the entire site from orbit, it's the only way to be sure",
901                     place,
902                 );
903                 Self::remove_const(&mut self.ecx, place.local);
904             }
905         } else {
906             match statement.kind {
907                 StatementKind::SetDiscriminant { ref place, .. } => {
908                     match self.ecx.machine.can_const_prop[place.local] {
909                         ConstPropMode::FullConstProp | ConstPropMode::OnlyInsideOwnBlock => {
910                             if self
911                                 .use_ecx(source_info, |this| this.ecx.statement(statement))
912                                 .is_some()
913                             {
914                                 trace!("propped discriminant into {:?}", place);
915                             } else {
916                                 Self::remove_const(&mut self.ecx, place.local);
917                             }
918                         }
919                         ConstPropMode::OnlyPropagateInto | ConstPropMode::NoPropagation => {
920                             Self::remove_const(&mut self.ecx, place.local);
921                         }
922                     }
923                 }
924                 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
925                     let frame = self.ecx.frame_mut();
926                     frame.locals[local].value =
927                         if let StatementKind::StorageLive(_) = statement.kind {
928                             LocalValue::Live(interpret::Operand::Immediate(
929                                 interpret::Immediate::Uninit,
930                             ))
931                         } else {
932                             LocalValue::Dead
933                         };
934                 }
935                 _ => {}
936             }
937         }
938
939         self.super_statement(statement, location);
940     }
941
942     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
943         let source_info = terminator.source_info;
944         self.source_info = Some(source_info);
945         self.super_terminator(terminator, location);
946         match &terminator.kind {
947             TerminatorKind::Assert { expected, ref msg, ref cond, .. } => {
948                 if let Some(ref value) = self.eval_operand(&cond, source_info) {
949                     trace!("assertion on {:?} should be {:?}", value, expected);
950                     let expected = ScalarMaybeUninit::from(Scalar::from_bool(*expected));
951                     let value_const = self.ecx.read_scalar(&value).unwrap();
952                     if expected != value_const {
953                         enum DbgVal<T> {
954                             Val(T),
955                             Underscore,
956                         }
957                         impl<T: std::fmt::Debug> std::fmt::Debug for DbgVal<T> {
958                             fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
959                                 match self {
960                                     Self::Val(val) => val.fmt(fmt),
961                                     Self::Underscore => fmt.write_str("_"),
962                                 }
963                             }
964                         }
965                         let mut eval_to_int = |op| {
966                             // This can be `None` if the lhs wasn't const propagated and we just
967                             // triggered the assert on the value of the rhs.
968                             self.eval_operand(op, source_info).map_or(DbgVal::Underscore, |op| {
969                                 DbgVal::Val(self.ecx.read_immediate(&op).unwrap().to_const_int())
970                             })
971                         };
972                         let msg = match msg {
973                             AssertKind::DivisionByZero(op) => {
974                                 Some(AssertKind::DivisionByZero(eval_to_int(op)))
975                             }
976                             AssertKind::RemainderByZero(op) => {
977                                 Some(AssertKind::RemainderByZero(eval_to_int(op)))
978                             }
979                             AssertKind::Overflow(bin_op @ (BinOp::Div | BinOp::Rem), op1, op2) => {
980                                 // Division overflow is *UB* in the MIR, and different than the
981                                 // other overflow checks.
982                                 Some(AssertKind::Overflow(
983                                     *bin_op,
984                                     eval_to_int(op1),
985                                     eval_to_int(op2),
986                                 ))
987                             }
988                             AssertKind::BoundsCheck { ref len, ref index } => {
989                                 let len = eval_to_int(len);
990                                 let index = eval_to_int(index);
991                                 Some(AssertKind::BoundsCheck { len, index })
992                             }
993                             // Remaining overflow errors are already covered by checks on the binary operators.
994                             AssertKind::Overflow(..) | AssertKind::OverflowNeg(_) => None,
995                             // Need proper const propagator for these.
996                             _ => None,
997                         };
998                         // Poison all places this operand references so that further code
999                         // doesn't use the invalid value
1000                         match cond {
1001                             Operand::Move(ref place) | Operand::Copy(ref place) => {
1002                                 Self::remove_const(&mut self.ecx, place.local);
1003                             }
1004                             Operand::Constant(_) => {}
1005                         }
1006                         if let Some(msg) = msg {
1007                             self.report_assert_as_lint(
1008                                 lint::builtin::UNCONDITIONAL_PANIC,
1009                                 source_info,
1010                                 "this operation will panic at runtime",
1011                                 msg,
1012                             );
1013                         }
1014                     }
1015                 }
1016             }
1017             // None of these have Operands to const-propagate.
1018             TerminatorKind::Goto { .. }
1019             | TerminatorKind::Resume
1020             | TerminatorKind::Abort
1021             | TerminatorKind::Return
1022             | TerminatorKind::Unreachable
1023             | TerminatorKind::Drop { .. }
1024             | TerminatorKind::DropAndReplace { .. }
1025             | TerminatorKind::Yield { .. }
1026             | TerminatorKind::GeneratorDrop
1027             | TerminatorKind::FalseEdge { .. }
1028             | TerminatorKind::FalseUnwind { .. }
1029             | TerminatorKind::SwitchInt { .. }
1030             | TerminatorKind::Call { .. }
1031             | TerminatorKind::InlineAsm { .. } => {}
1032         }
1033
1034         // We remove all Locals which are restricted in propagation to their containing blocks and
1035         // which were modified in the current block.
1036         // Take it out of the ecx so we can get a mutable reference to the ecx for `remove_const`.
1037         let mut locals = std::mem::take(&mut self.ecx.machine.written_only_inside_own_block_locals);
1038         for &local in locals.iter() {
1039             Self::remove_const(&mut self.ecx, local);
1040         }
1041         locals.clear();
1042         // Put it back so we reuse the heap of the storage
1043         self.ecx.machine.written_only_inside_own_block_locals = locals;
1044         if cfg!(debug_assertions) {
1045             // Ensure we are correctly erasing locals with the non-debug-assert logic.
1046             for local in self.ecx.machine.only_propagate_inside_block_locals.iter() {
1047                 assert!(
1048                     self.get_const(local.into()).is_none()
1049                         || self
1050                             .layout_of(self.local_decls[local].ty)
1051                             .map_or(true, |layout| layout.is_zst())
1052                 )
1053             }
1054         }
1055     }
1056 }