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