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