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