rustc_mir_transform/
dataflow_const_prop.rs

1//! A constant propagation optimization pass based on dataflow analysis.
2//!
3//! Currently, this pass only propagates scalar values.
4
5use std::assert_matches::assert_matches;
6use std::cell::RefCell;
7use std::fmt::Formatter;
8
9use rustc_abi::{BackendRepr, FIRST_VARIANT, FieldIdx, Size, VariantIdx};
10use rustc_const_eval::const_eval::{DummyMachine, throw_machine_stop_str};
11use rustc_const_eval::interpret::{
12    ImmTy, Immediate, InterpCx, OpTy, PlaceTy, Projectable, interp_ok,
13};
14use rustc_data_structures::fx::FxHashMap;
15use rustc_hir::def::DefKind;
16use rustc_middle::bug;
17use rustc_middle::mir::interpret::{InterpResult, Scalar};
18use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor};
19use rustc_middle::mir::*;
20use rustc_middle::ty::{self, Ty, TyCtxt};
21use rustc_mir_dataflow::fmt::DebugWithContext;
22use rustc_mir_dataflow::lattice::{FlatSet, HasBottom};
23use rustc_mir_dataflow::value_analysis::{
24    Map, PlaceIndex, State, TrackElem, ValueOrPlace, debug_with_context,
25};
26use rustc_mir_dataflow::{Analysis, ResultsVisitor, visit_reachable_results};
27use rustc_span::DUMMY_SP;
28use tracing::{debug, debug_span, instrument};
29
30// These constants are somewhat random guesses and have not been optimized.
31// If `tcx.sess.mir_opt_level() >= 4`, we ignore the limits (this can become very expensive).
32const BLOCK_LIMIT: usize = 100;
33const PLACE_LIMIT: usize = 100;
34
35pub(super) struct DataflowConstProp;
36
37impl<'tcx> crate::MirPass<'tcx> for DataflowConstProp {
38    fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
39        sess.mir_opt_level() >= 3
40    }
41
42    #[instrument(skip_all level = "debug")]
43    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
44        debug!(def_id = ?body.source.def_id());
45        if tcx.sess.mir_opt_level() < 4 && body.basic_blocks.len() > BLOCK_LIMIT {
46            debug!("aborted dataflow const prop due too many basic blocks");
47            return;
48        }
49
50        // We want to have a somewhat linear runtime w.r.t. the number of statements/terminators.
51        // Let's call this number `n`. Dataflow analysis has `O(h*n)` transfer function
52        // applications, where `h` is the height of the lattice. Because the height of our lattice
53        // is linear w.r.t. the number of tracked places, this is `O(tracked_places * n)`. However,
54        // because every transfer function application could traverse the whole map, this becomes
55        // `O(num_nodes * tracked_places * n)` in terms of time complexity. Since the number of
56        // map nodes is strongly correlated to the number of tracked places, this becomes more or
57        // less `O(n)` if we place a constant limit on the number of tracked places.
58        let place_limit = if tcx.sess.mir_opt_level() < 4 { Some(PLACE_LIMIT) } else { None };
59
60        // Decide which places to track during the analysis.
61        let map = Map::new(tcx, body, place_limit);
62
63        // Perform the actual dataflow analysis.
64        let const_ = debug_span!("analyze")
65            .in_scope(|| ConstAnalysis::new(tcx, body, map).iterate_to_fixpoint(tcx, body, None));
66
67        // Collect results and patch the body afterwards.
68        let mut visitor = Collector::new(tcx, &body.local_decls);
69        debug_span!("collect").in_scope(|| visit_reachable_results(body, &const_, &mut visitor));
70        let mut patch = visitor.patch;
71        debug_span!("patch").in_scope(|| patch.visit_body_preserves_cfg(body));
72    }
73
74    fn is_required(&self) -> bool {
75        false
76    }
77}
78
79// Note: Currently, places that have their reference taken cannot be tracked. Although this would
80// be possible, it has to rely on some aliasing model, which we are not ready to commit to yet.
81// Because of that, we can assume that the only way to change the value behind a tracked place is
82// by direct assignment.
83struct ConstAnalysis<'a, 'tcx> {
84    map: Map<'tcx>,
85    tcx: TyCtxt<'tcx>,
86    local_decls: &'a LocalDecls<'tcx>,
87    ecx: RefCell<InterpCx<'tcx, DummyMachine>>,
88    typing_env: ty::TypingEnv<'tcx>,
89}
90
91impl<'tcx> Analysis<'tcx> for ConstAnalysis<'_, 'tcx> {
92    type Domain = State<FlatSet<Scalar>>;
93
94    const NAME: &'static str = "ConstAnalysis";
95
96    // The bottom state denotes uninitialized memory. Because we are only doing a sound
97    // approximation of the actual execution, we can also use this state for places where access
98    // would be UB.
99    fn bottom_value(&self, _body: &Body<'tcx>) -> Self::Domain {
100        State::Unreachable
101    }
102
103    fn initialize_start_block(&self, body: &Body<'tcx>, state: &mut Self::Domain) {
104        // The initial state maps all tracked places of argument projections to ⊤ and the rest to ⊥.
105        assert_matches!(state, State::Unreachable);
106        *state = State::new_reachable();
107        for arg in body.args_iter() {
108            state.flood(PlaceRef { local: arg, projection: &[] }, &self.map);
109        }
110    }
111
112    fn apply_primary_statement_effect(
113        &self,
114        state: &mut Self::Domain,
115        statement: &Statement<'tcx>,
116        _location: Location,
117    ) {
118        if state.is_reachable() {
119            self.handle_statement(statement, state);
120        }
121    }
122
123    fn apply_primary_terminator_effect<'mir>(
124        &self,
125        state: &mut Self::Domain,
126        terminator: &'mir Terminator<'tcx>,
127        _location: Location,
128    ) -> TerminatorEdges<'mir, 'tcx> {
129        if state.is_reachable() {
130            self.handle_terminator(terminator, state)
131        } else {
132            TerminatorEdges::None
133        }
134    }
135
136    fn apply_call_return_effect(
137        &self,
138        state: &mut Self::Domain,
139        _block: BasicBlock,
140        return_places: CallReturnPlaces<'_, 'tcx>,
141    ) {
142        if state.is_reachable() {
143            self.handle_call_return(return_places, state)
144        }
145    }
146}
147
148impl<'a, 'tcx> ConstAnalysis<'a, 'tcx> {
149    fn new(tcx: TyCtxt<'tcx>, body: &'a Body<'tcx>, map: Map<'tcx>) -> Self {
150        let typing_env = body.typing_env(tcx);
151        Self {
152            map,
153            tcx,
154            local_decls: &body.local_decls,
155            ecx: RefCell::new(InterpCx::new(tcx, DUMMY_SP, typing_env, DummyMachine)),
156            typing_env,
157        }
158    }
159
160    fn handle_statement(&self, statement: &Statement<'tcx>, state: &mut State<FlatSet<Scalar>>) {
161        match &statement.kind {
162            StatementKind::Assign(box (place, rvalue)) => {
163                self.handle_assign(*place, rvalue, state);
164            }
165            StatementKind::SetDiscriminant { box place, variant_index } => {
166                self.handle_set_discriminant(*place, *variant_index, state);
167            }
168            StatementKind::Intrinsic(box intrinsic) => {
169                self.handle_intrinsic(intrinsic);
170            }
171            StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
172                // StorageLive leaves the local in an uninitialized state.
173                // StorageDead makes it UB to access the local afterwards.
174                state.flood_with(
175                    Place::from(*local).as_ref(),
176                    &self.map,
177                    FlatSet::<Scalar>::BOTTOM,
178                );
179            }
180            StatementKind::Retag(..) => {
181                // We don't track references.
182            }
183            StatementKind::ConstEvalCounter
184            | StatementKind::Nop
185            | StatementKind::FakeRead(..)
186            | StatementKind::PlaceMention(..)
187            | StatementKind::Coverage(..)
188            | StatementKind::BackwardIncompatibleDropHint { .. }
189            | StatementKind::AscribeUserType(..) => {}
190        }
191    }
192
193    fn handle_intrinsic(&self, intrinsic: &NonDivergingIntrinsic<'tcx>) {
194        match intrinsic {
195            NonDivergingIntrinsic::Assume(..) => {
196                // Could use this, but ignoring it is sound.
197            }
198            NonDivergingIntrinsic::CopyNonOverlapping(CopyNonOverlapping {
199                dst: _,
200                src: _,
201                count: _,
202            }) => {
203                // This statement represents `*dst = *src`, `count` times.
204            }
205        }
206    }
207
208    fn handle_operand(
209        &self,
210        operand: &Operand<'tcx>,
211        state: &mut State<FlatSet<Scalar>>,
212    ) -> ValueOrPlace<FlatSet<Scalar>> {
213        match operand {
214            Operand::Constant(box constant) => {
215                ValueOrPlace::Value(self.handle_constant(constant, state))
216            }
217            Operand::Copy(place) | Operand::Move(place) => {
218                // On move, we would ideally flood the place with bottom. But with the current
219                // framework this is not possible (similar to `InterpCx::eval_operand`).
220                self.map.find(place.as_ref()).map(ValueOrPlace::Place).unwrap_or(ValueOrPlace::TOP)
221            }
222        }
223    }
224
225    /// The effect of a successful function call return should not be
226    /// applied here, see [`Analysis::apply_primary_terminator_effect`].
227    fn handle_terminator<'mir>(
228        &self,
229        terminator: &'mir Terminator<'tcx>,
230        state: &mut State<FlatSet<Scalar>>,
231    ) -> TerminatorEdges<'mir, 'tcx> {
232        match &terminator.kind {
233            TerminatorKind::Call { .. } | TerminatorKind::InlineAsm { .. } => {
234                // Effect is applied by `handle_call_return`.
235            }
236            TerminatorKind::Drop { place, .. } => {
237                state.flood_with(place.as_ref(), &self.map, FlatSet::<Scalar>::BOTTOM);
238            }
239            TerminatorKind::Yield { .. } => {
240                // They would have an effect, but are not allowed in this phase.
241                bug!("encountered disallowed terminator");
242            }
243            TerminatorKind::SwitchInt { discr, targets } => {
244                return self.handle_switch_int(discr, targets, state);
245            }
246            TerminatorKind::TailCall { .. } => {
247                // FIXME(explicit_tail_calls): determine if we need to do something here (probably
248                // not)
249            }
250            TerminatorKind::Goto { .. }
251            | TerminatorKind::UnwindResume
252            | TerminatorKind::UnwindTerminate(_)
253            | TerminatorKind::Return
254            | TerminatorKind::Unreachable
255            | TerminatorKind::Assert { .. }
256            | TerminatorKind::CoroutineDrop
257            | TerminatorKind::FalseEdge { .. }
258            | TerminatorKind::FalseUnwind { .. } => {
259                // These terminators have no effect on the analysis.
260            }
261        }
262        terminator.edges()
263    }
264
265    fn handle_call_return(
266        &self,
267        return_places: CallReturnPlaces<'_, 'tcx>,
268        state: &mut State<FlatSet<Scalar>>,
269    ) {
270        return_places.for_each(|place| {
271            state.flood(place.as_ref(), &self.map);
272        })
273    }
274
275    fn handle_set_discriminant(
276        &self,
277        place: Place<'tcx>,
278        variant_index: VariantIdx,
279        state: &mut State<FlatSet<Scalar>>,
280    ) {
281        state.flood_discr(place.as_ref(), &self.map);
282        if self.map.find_discr(place.as_ref()).is_some() {
283            let enum_ty = place.ty(self.local_decls, self.tcx).ty;
284            if let Some(discr) = self.eval_discriminant(enum_ty, variant_index) {
285                state.assign_discr(
286                    place.as_ref(),
287                    ValueOrPlace::Value(FlatSet::Elem(discr)),
288                    &self.map,
289                );
290            }
291        }
292    }
293
294    fn handle_assign(
295        &self,
296        target: Place<'tcx>,
297        rvalue: &Rvalue<'tcx>,
298        state: &mut State<FlatSet<Scalar>>,
299    ) {
300        match rvalue {
301            Rvalue::Use(operand) => {
302                state.flood(target.as_ref(), &self.map);
303                if let Some(target) = self.map.find(target.as_ref()) {
304                    self.assign_operand(state, target, operand);
305                }
306            }
307            Rvalue::CopyForDeref(_) => bug!("`CopyForDeref` in runtime MIR"),
308            Rvalue::Aggregate(kind, operands) => {
309                // If we assign `target = Enum::Variant#0(operand)`,
310                // we must make sure that all `target as Variant#i` are `Top`.
311                state.flood(target.as_ref(), &self.map);
312
313                let Some(target_idx) = self.map.find(target.as_ref()) else { return };
314
315                let (variant_target, variant_index) = match **kind {
316                    AggregateKind::Tuple | AggregateKind::Closure(..) => (Some(target_idx), None),
317                    AggregateKind::Adt(def_id, variant_index, ..) => {
318                        match self.tcx.def_kind(def_id) {
319                            DefKind::Struct => (Some(target_idx), None),
320                            DefKind::Enum => (
321                                self.map.apply(target_idx, TrackElem::Variant(variant_index)),
322                                Some(variant_index),
323                            ),
324                            _ => return,
325                        }
326                    }
327                    _ => return,
328                };
329                if let Some(variant_target_idx) = variant_target {
330                    for (field_index, operand) in operands.iter_enumerated() {
331                        if let Some(field) =
332                            self.map.apply(variant_target_idx, TrackElem::Field(field_index))
333                        {
334                            self.assign_operand(state, field, operand);
335                        }
336                    }
337                }
338                if let Some(variant_index) = variant_index
339                    && let Some(discr_idx) = self.map.apply(target_idx, TrackElem::Discriminant)
340                {
341                    // We are assigning the discriminant as part of an aggregate.
342                    // This discriminant can only alias a variant field's value if the operand
343                    // had an invalid value for that type.
344                    // Using invalid values is UB, so we are allowed to perform the assignment
345                    // without extra flooding.
346                    let enum_ty = target.ty(self.local_decls, self.tcx).ty;
347                    if let Some(discr_val) = self.eval_discriminant(enum_ty, variant_index) {
348                        state.insert_value_idx(discr_idx, FlatSet::Elem(discr_val), &self.map);
349                    }
350                }
351            }
352            Rvalue::BinaryOp(op, box (left, right)) if op.is_overflowing() => {
353                // Flood everything now, so we can use `insert_value_idx` directly later.
354                state.flood(target.as_ref(), &self.map);
355
356                let Some(target) = self.map.find(target.as_ref()) else { return };
357
358                let value_target = self.map.apply(target, TrackElem::Field(0_u32.into()));
359                let overflow_target = self.map.apply(target, TrackElem::Field(1_u32.into()));
360
361                if value_target.is_some() || overflow_target.is_some() {
362                    let (val, overflow) = self.binary_op(state, *op, left, right);
363
364                    if let Some(value_target) = value_target {
365                        // We have flooded `target` earlier.
366                        state.insert_value_idx(value_target, val, &self.map);
367                    }
368                    if let Some(overflow_target) = overflow_target {
369                        // We have flooded `target` earlier.
370                        state.insert_value_idx(overflow_target, overflow, &self.map);
371                    }
372                }
373            }
374            Rvalue::Cast(
375                CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
376                operand,
377                _,
378            ) => {
379                let pointer = self.handle_operand(operand, state);
380                state.assign(target.as_ref(), pointer, &self.map);
381
382                if let Some(target_len) = self.map.find_len(target.as_ref())
383                    && let operand_ty = operand.ty(self.local_decls, self.tcx)
384                    && let Some(operand_ty) = operand_ty.builtin_deref(true)
385                    && let ty::Array(_, len) = operand_ty.kind()
386                    && let Some(len) = Const::Ty(self.tcx.types.usize, *len)
387                        .try_eval_scalar_int(self.tcx, self.typing_env)
388                {
389                    state.insert_value_idx(target_len, FlatSet::Elem(len.into()), &self.map);
390                }
391            }
392            _ => {
393                let result = self.handle_rvalue(rvalue, state);
394                state.assign(target.as_ref(), result, &self.map);
395            }
396        }
397    }
398
399    fn handle_rvalue(
400        &self,
401        rvalue: &Rvalue<'tcx>,
402        state: &mut State<FlatSet<Scalar>>,
403    ) -> ValueOrPlace<FlatSet<Scalar>> {
404        let val = match rvalue {
405            Rvalue::Cast(CastKind::IntToInt | CastKind::IntToFloat, operand, ty) => {
406                let Ok(layout) = self.tcx.layout_of(self.typing_env.as_query_input(*ty)) else {
407                    return ValueOrPlace::Value(FlatSet::Top);
408                };
409                match self.eval_operand(operand, state) {
410                    FlatSet::Elem(op) => self
411                        .ecx
412                        .borrow()
413                        .int_to_int_or_float(&op, layout)
414                        .discard_err()
415                        .map_or(FlatSet::Top, |result| self.wrap_immediate(*result)),
416                    FlatSet::Bottom => FlatSet::Bottom,
417                    FlatSet::Top => FlatSet::Top,
418                }
419            }
420            Rvalue::Cast(CastKind::FloatToInt | CastKind::FloatToFloat, operand, ty) => {
421                let Ok(layout) = self.tcx.layout_of(self.typing_env.as_query_input(*ty)) else {
422                    return ValueOrPlace::Value(FlatSet::Top);
423                };
424                match self.eval_operand(operand, state) {
425                    FlatSet::Elem(op) => self
426                        .ecx
427                        .borrow()
428                        .float_to_float_or_int(&op, layout)
429                        .discard_err()
430                        .map_or(FlatSet::Top, |result| self.wrap_immediate(*result)),
431                    FlatSet::Bottom => FlatSet::Bottom,
432                    FlatSet::Top => FlatSet::Top,
433                }
434            }
435            Rvalue::Cast(CastKind::Transmute | CastKind::Subtype, operand, _) => {
436                match self.eval_operand(operand, state) {
437                    FlatSet::Elem(op) => self.wrap_immediate(*op),
438                    FlatSet::Bottom => FlatSet::Bottom,
439                    FlatSet::Top => FlatSet::Top,
440                }
441            }
442            Rvalue::BinaryOp(op, box (left, right)) if !op.is_overflowing() => {
443                // Overflows must be ignored here.
444                // The overflowing operators are handled in `handle_assign`.
445                let (val, _overflow) = self.binary_op(state, *op, left, right);
446                val
447            }
448            Rvalue::UnaryOp(op, operand) => {
449                if let UnOp::PtrMetadata = op
450                    && let Some(place) = operand.place()
451                    && let Some(len) = self.map.find_len(place.as_ref())
452                {
453                    return ValueOrPlace::Place(len);
454                }
455                match self.eval_operand(operand, state) {
456                    FlatSet::Elem(value) => self
457                        .ecx
458                        .borrow()
459                        .unary_op(*op, &value)
460                        .discard_err()
461                        .map_or(FlatSet::Top, |val| self.wrap_immediate(*val)),
462                    FlatSet::Bottom => FlatSet::Bottom,
463                    FlatSet::Top => FlatSet::Top,
464                }
465            }
466            Rvalue::NullaryOp(null_op, ty) => {
467                let Ok(layout) = self.tcx.layout_of(self.typing_env.as_query_input(*ty)) else {
468                    return ValueOrPlace::Value(FlatSet::Top);
469                };
470                let val = match null_op {
471                    NullOp::OffsetOf(fields) => self
472                        .ecx
473                        .borrow()
474                        .tcx
475                        .offset_of_subfield(self.typing_env, layout, fields.iter())
476                        .bytes(),
477                    _ => return ValueOrPlace::Value(FlatSet::Top),
478                };
479                FlatSet::Elem(Scalar::from_target_usize(val, &self.tcx))
480            }
481            Rvalue::Discriminant(place) => state.get_discr(place.as_ref(), &self.map),
482            Rvalue::Use(operand) => return self.handle_operand(operand, state),
483            Rvalue::CopyForDeref(_) => bug!("`CopyForDeref` in runtime MIR"),
484            Rvalue::ShallowInitBox(..) => bug!("`ShallowInitBox` in runtime MIR"),
485            Rvalue::Ref(..) | Rvalue::RawPtr(..) => {
486                // We don't track such places.
487                return ValueOrPlace::TOP;
488            }
489            Rvalue::Repeat(..)
490            | Rvalue::ThreadLocalRef(..)
491            | Rvalue::Cast(..)
492            | Rvalue::BinaryOp(..)
493            | Rvalue::Aggregate(..)
494            | Rvalue::WrapUnsafeBinder(..) => {
495                // No modification is possible through these r-values.
496                return ValueOrPlace::TOP;
497            }
498        };
499        ValueOrPlace::Value(val)
500    }
501
502    fn handle_constant(
503        &self,
504        constant: &ConstOperand<'tcx>,
505        _state: &mut State<FlatSet<Scalar>>,
506    ) -> FlatSet<Scalar> {
507        constant
508            .const_
509            .try_eval_scalar(self.tcx, self.typing_env)
510            .map_or(FlatSet::Top, FlatSet::Elem)
511    }
512
513    fn handle_switch_int<'mir>(
514        &self,
515        discr: &'mir Operand<'tcx>,
516        targets: &'mir SwitchTargets,
517        state: &mut State<FlatSet<Scalar>>,
518    ) -> TerminatorEdges<'mir, 'tcx> {
519        let value = match self.handle_operand(discr, state) {
520            ValueOrPlace::Value(value) => value,
521            ValueOrPlace::Place(place) => state.get_idx(place, &self.map),
522        };
523        match value {
524            // We are branching on uninitialized data, this is UB, treat it as unreachable.
525            // This allows the set of visited edges to grow monotonically with the lattice.
526            FlatSet::Bottom => TerminatorEdges::None,
527            FlatSet::Elem(scalar) => {
528                if let Ok(scalar_int) = scalar.try_to_scalar_int() {
529                    TerminatorEdges::Single(
530                        targets.target_for_value(scalar_int.to_bits_unchecked()),
531                    )
532                } else {
533                    TerminatorEdges::SwitchInt { discr, targets }
534                }
535            }
536            FlatSet::Top => TerminatorEdges::SwitchInt { discr, targets },
537        }
538    }
539
540    /// The caller must have flooded `place`.
541    fn assign_operand(
542        &self,
543        state: &mut State<FlatSet<Scalar>>,
544        place: PlaceIndex,
545        operand: &Operand<'tcx>,
546    ) {
547        match operand {
548            Operand::Copy(rhs) | Operand::Move(rhs) => {
549                if let Some(rhs) = self.map.find(rhs.as_ref()) {
550                    state.insert_place_idx(place, rhs, &self.map);
551                } else if rhs.projection.first() == Some(&PlaceElem::Deref)
552                    && let FlatSet::Elem(pointer) = state.get(rhs.local.into(), &self.map)
553                    && let rhs_ty = self.local_decls[rhs.local].ty
554                    && let Ok(rhs_layout) =
555                        self.tcx.layout_of(self.typing_env.as_query_input(rhs_ty))
556                {
557                    let op = ImmTy::from_scalar(pointer, rhs_layout).into();
558                    self.assign_constant(state, place, op, rhs.projection);
559                }
560            }
561            Operand::Constant(box constant) => {
562                if let Some(constant) = self
563                    .ecx
564                    .borrow()
565                    .eval_mir_constant(&constant.const_, constant.span, None)
566                    .discard_err()
567                {
568                    self.assign_constant(state, place, constant, &[]);
569                }
570            }
571        }
572    }
573
574    /// The caller must have flooded `place`.
575    ///
576    /// Perform: `place = operand.projection`.
577    #[instrument(level = "trace", skip(self, state))]
578    fn assign_constant(
579        &self,
580        state: &mut State<FlatSet<Scalar>>,
581        place: PlaceIndex,
582        mut operand: OpTy<'tcx>,
583        projection: &[PlaceElem<'tcx>],
584    ) {
585        for &(mut proj_elem) in projection {
586            if let PlaceElem::Index(index) = proj_elem {
587                if let FlatSet::Elem(index) = state.get(index.into(), &self.map)
588                    && let Some(offset) = index.to_target_usize(&self.tcx).discard_err()
589                    && let Some(min_length) = offset.checked_add(1)
590                {
591                    proj_elem = PlaceElem::ConstantIndex { offset, min_length, from_end: false };
592                } else {
593                    return;
594                }
595            }
596            operand = if let Some(operand) =
597                self.ecx.borrow().project(&operand, proj_elem).discard_err()
598            {
599                operand
600            } else {
601                return;
602            }
603        }
604
605        self.map.for_each_projection_value(
606            place,
607            operand,
608            &mut |elem, op| match elem {
609                TrackElem::Field(idx) => self.ecx.borrow().project_field(op, idx).discard_err(),
610                TrackElem::Variant(idx) => {
611                    self.ecx.borrow().project_downcast(op, idx).discard_err()
612                }
613                TrackElem::Discriminant => {
614                    let variant = self.ecx.borrow().read_discriminant(op).discard_err()?;
615                    let discr_value = self
616                        .ecx
617                        .borrow()
618                        .discriminant_for_variant(op.layout.ty, variant)
619                        .discard_err()?;
620                    Some(discr_value.into())
621                }
622                TrackElem::DerefLen => {
623                    let op: OpTy<'_> = self.ecx.borrow().deref_pointer(op).discard_err()?.into();
624                    let len_usize = op.len(&self.ecx.borrow()).discard_err()?;
625                    let layout = self
626                        .tcx
627                        .layout_of(self.typing_env.as_query_input(self.tcx.types.usize))
628                        .unwrap();
629                    Some(ImmTy::from_uint(len_usize, layout).into())
630                }
631            },
632            &mut |place, op| {
633                if let Some(imm) = self.ecx.borrow().read_immediate_raw(op).discard_err()
634                    && let Some(imm) = imm.right()
635                {
636                    let elem = self.wrap_immediate(*imm);
637                    state.insert_value_idx(place, elem, &self.map);
638                }
639            },
640        );
641    }
642
643    fn binary_op(
644        &self,
645        state: &mut State<FlatSet<Scalar>>,
646        op: BinOp,
647        left: &Operand<'tcx>,
648        right: &Operand<'tcx>,
649    ) -> (FlatSet<Scalar>, FlatSet<Scalar>) {
650        let left = self.eval_operand(left, state);
651        let right = self.eval_operand(right, state);
652
653        match (left, right) {
654            (FlatSet::Bottom, _) | (_, FlatSet::Bottom) => (FlatSet::Bottom, FlatSet::Bottom),
655            // Both sides are known, do the actual computation.
656            (FlatSet::Elem(left), FlatSet::Elem(right)) => {
657                match self.ecx.borrow().binary_op(op, &left, &right).discard_err() {
658                    // Ideally this would return an Immediate, since it's sometimes
659                    // a pair and sometimes not. But as a hack we always return a pair
660                    // and just make the 2nd component `Bottom` when it does not exist.
661                    Some(val) => {
662                        if matches!(val.layout.backend_repr, BackendRepr::ScalarPair(..)) {
663                            let (val, overflow) = val.to_scalar_pair();
664                            (FlatSet::Elem(val), FlatSet::Elem(overflow))
665                        } else {
666                            (FlatSet::Elem(val.to_scalar()), FlatSet::Bottom)
667                        }
668                    }
669                    _ => (FlatSet::Top, FlatSet::Top),
670                }
671            }
672            // Exactly one side is known, attempt some algebraic simplifications.
673            (FlatSet::Elem(const_arg), _) | (_, FlatSet::Elem(const_arg)) => {
674                let layout = const_arg.layout;
675                if !matches!(layout.backend_repr, rustc_abi::BackendRepr::Scalar(..)) {
676                    return (FlatSet::Top, FlatSet::Top);
677                }
678
679                let arg_scalar = const_arg.to_scalar();
680                let Some(arg_value) = arg_scalar.to_bits(layout.size).discard_err() else {
681                    return (FlatSet::Top, FlatSet::Top);
682                };
683
684                match op {
685                    BinOp::BitAnd if arg_value == 0 => (FlatSet::Elem(arg_scalar), FlatSet::Bottom),
686                    BinOp::BitOr
687                        if arg_value == layout.size.truncate(u128::MAX)
688                            || (layout.ty.is_bool() && arg_value == 1) =>
689                    {
690                        (FlatSet::Elem(arg_scalar), FlatSet::Bottom)
691                    }
692                    BinOp::Mul if layout.ty.is_integral() && arg_value == 0 => {
693                        (FlatSet::Elem(arg_scalar), FlatSet::Elem(Scalar::from_bool(false)))
694                    }
695                    _ => (FlatSet::Top, FlatSet::Top),
696                }
697            }
698            (FlatSet::Top, FlatSet::Top) => (FlatSet::Top, FlatSet::Top),
699        }
700    }
701
702    fn eval_operand(
703        &self,
704        op: &Operand<'tcx>,
705        state: &mut State<FlatSet<Scalar>>,
706    ) -> FlatSet<ImmTy<'tcx>> {
707        let value = match self.handle_operand(op, state) {
708            ValueOrPlace::Value(value) => value,
709            ValueOrPlace::Place(place) => state.get_idx(place, &self.map),
710        };
711        match value {
712            FlatSet::Top => FlatSet::Top,
713            FlatSet::Elem(scalar) => {
714                let ty = op.ty(self.local_decls, self.tcx);
715                self.tcx
716                    .layout_of(self.typing_env.as_query_input(ty))
717                    .map_or(FlatSet::Top, |layout| {
718                        FlatSet::Elem(ImmTy::from_scalar(scalar, layout))
719                    })
720            }
721            FlatSet::Bottom => FlatSet::Bottom,
722        }
723    }
724
725    fn eval_discriminant(&self, enum_ty: Ty<'tcx>, variant_index: VariantIdx) -> Option<Scalar> {
726        if !enum_ty.is_enum() {
727            return None;
728        }
729        let enum_ty_layout = self.tcx.layout_of(self.typing_env.as_query_input(enum_ty)).ok()?;
730        let discr_value = self
731            .ecx
732            .borrow()
733            .discriminant_for_variant(enum_ty_layout.ty, variant_index)
734            .discard_err()?;
735        Some(discr_value.to_scalar())
736    }
737
738    fn wrap_immediate(&self, imm: Immediate) -> FlatSet<Scalar> {
739        match imm {
740            Immediate::Scalar(scalar) => FlatSet::Elem(scalar),
741            Immediate::Uninit => FlatSet::Bottom,
742            _ => FlatSet::Top,
743        }
744    }
745}
746
747/// This is used to visualize the dataflow analysis.
748impl<'tcx> DebugWithContext<ConstAnalysis<'_, 'tcx>> for State<FlatSet<Scalar>> {
749    fn fmt_with(&self, ctxt: &ConstAnalysis<'_, 'tcx>, f: &mut Formatter<'_>) -> std::fmt::Result {
750        match self {
751            State::Reachable(values) => debug_with_context(values, None, &ctxt.map, f),
752            State::Unreachable => write!(f, "unreachable"),
753        }
754    }
755
756    fn fmt_diff_with(
757        &self,
758        old: &Self,
759        ctxt: &ConstAnalysis<'_, 'tcx>,
760        f: &mut Formatter<'_>,
761    ) -> std::fmt::Result {
762        match (self, old) {
763            (State::Reachable(this), State::Reachable(old)) => {
764                debug_with_context(this, Some(old), &ctxt.map, f)
765            }
766            _ => Ok(()), // Consider printing something here.
767        }
768    }
769}
770
771struct Patch<'tcx> {
772    tcx: TyCtxt<'tcx>,
773
774    /// For a given MIR location, this stores the values of the operands used by that location. In
775    /// particular, this is before the effect, such that the operands of `_1 = _1 + _2` are
776    /// properly captured. (This may become UB soon, but it is currently emitted even by safe code.)
777    before_effect: FxHashMap<(Location, Place<'tcx>), Const<'tcx>>,
778
779    /// Stores the assigned values for assignments where the Rvalue is constant.
780    assignments: FxHashMap<Location, Const<'tcx>>,
781}
782
783impl<'tcx> Patch<'tcx> {
784    pub(crate) fn new(tcx: TyCtxt<'tcx>) -> Self {
785        Self { tcx, before_effect: FxHashMap::default(), assignments: FxHashMap::default() }
786    }
787
788    fn make_operand(&self, const_: Const<'tcx>) -> Operand<'tcx> {
789        Operand::Constant(Box::new(ConstOperand { span: DUMMY_SP, user_ty: None, const_ }))
790    }
791}
792
793struct Collector<'a, 'tcx> {
794    patch: Patch<'tcx>,
795    local_decls: &'a LocalDecls<'tcx>,
796}
797
798impl<'a, 'tcx> Collector<'a, 'tcx> {
799    pub(crate) fn new(tcx: TyCtxt<'tcx>, local_decls: &'a LocalDecls<'tcx>) -> Self {
800        Self { patch: Patch::new(tcx), local_decls }
801    }
802
803    #[instrument(level = "trace", skip(self, ecx, map), ret)]
804    fn try_make_constant(
805        &self,
806        ecx: &mut InterpCx<'tcx, DummyMachine>,
807        place: Place<'tcx>,
808        state: &State<FlatSet<Scalar>>,
809        map: &Map<'tcx>,
810    ) -> Option<Const<'tcx>> {
811        let ty = place.ty(self.local_decls, self.patch.tcx).ty;
812        let layout = ecx.layout_of(ty).ok()?;
813
814        if layout.is_zst() {
815            return Some(Const::zero_sized(ty));
816        }
817
818        if layout.is_unsized() {
819            return None;
820        }
821
822        let place = map.find(place.as_ref())?;
823        if layout.backend_repr.is_scalar()
824            && let Some(value) = propagatable_scalar(place, state, map)
825        {
826            return Some(Const::Val(ConstValue::Scalar(value), ty));
827        }
828
829        if matches!(layout.backend_repr, BackendRepr::Scalar(..) | BackendRepr::ScalarPair(..)) {
830            let alloc_id = ecx
831                .intern_with_temp_alloc(layout, |ecx, dest| {
832                    try_write_constant(ecx, dest, place, ty, state, map)
833                })
834                .discard_err()?;
835            return Some(Const::Val(ConstValue::Indirect { alloc_id, offset: Size::ZERO }, ty));
836        }
837
838        None
839    }
840}
841
842#[instrument(level = "trace", skip(map), ret)]
843fn propagatable_scalar(
844    place: PlaceIndex,
845    state: &State<FlatSet<Scalar>>,
846    map: &Map<'_>,
847) -> Option<Scalar> {
848    if let FlatSet::Elem(value) = state.get_idx(place, map)
849        && value.try_to_scalar_int().is_ok()
850    {
851        // Do not attempt to propagate pointers, as we may fail to preserve their identity.
852        Some(value)
853    } else {
854        None
855    }
856}
857
858#[instrument(level = "trace", skip(ecx, state, map), ret)]
859fn try_write_constant<'tcx>(
860    ecx: &mut InterpCx<'tcx, DummyMachine>,
861    dest: &PlaceTy<'tcx>,
862    place: PlaceIndex,
863    ty: Ty<'tcx>,
864    state: &State<FlatSet<Scalar>>,
865    map: &Map<'tcx>,
866) -> InterpResult<'tcx> {
867    let layout = ecx.layout_of(ty)?;
868
869    // Fast path for ZSTs.
870    if layout.is_zst() {
871        return interp_ok(());
872    }
873
874    // Fast path for scalars.
875    if layout.backend_repr.is_scalar()
876        && let Some(value) = propagatable_scalar(place, state, map)
877    {
878        return ecx.write_immediate(Immediate::Scalar(value), dest);
879    }
880
881    match ty.kind() {
882        // ZSTs. Nothing to do.
883        ty::FnDef(..) => {}
884
885        // Those are scalars, must be handled above.
886        ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Char =>
887            throw_machine_stop_str!("primitive type with provenance"),
888
889        ty::Tuple(elem_tys) => {
890            for (i, elem) in elem_tys.iter().enumerate() {
891                let i = FieldIdx::from_usize(i);
892                let Some(field) = map.apply(place, TrackElem::Field(i)) else {
893                    throw_machine_stop_str!("missing field in tuple")
894                };
895                let field_dest = ecx.project_field(dest, i)?;
896                try_write_constant(ecx, &field_dest, field, elem, state, map)?;
897            }
898        }
899
900        ty::Adt(def, args) => {
901            if def.is_union() {
902                throw_machine_stop_str!("cannot propagate unions")
903            }
904
905            let (variant_idx, variant_def, variant_place, variant_dest) = if def.is_enum() {
906                let Some(discr) = map.apply(place, TrackElem::Discriminant) else {
907                    throw_machine_stop_str!("missing discriminant for enum")
908                };
909                let FlatSet::Elem(Scalar::Int(discr)) = state.get_idx(discr, map) else {
910                    throw_machine_stop_str!("discriminant with provenance")
911                };
912                let discr_bits = discr.to_bits(discr.size());
913                let Some((variant, _)) = def.discriminants(*ecx.tcx).find(|(_, var)| discr_bits == var.val) else {
914                    throw_machine_stop_str!("illegal discriminant for enum")
915                };
916                let Some(variant_place) = map.apply(place, TrackElem::Variant(variant)) else {
917                    throw_machine_stop_str!("missing variant for enum")
918                };
919                let variant_dest = ecx.project_downcast(dest, variant)?;
920                (variant, def.variant(variant), variant_place, variant_dest)
921            } else {
922                (FIRST_VARIANT, def.non_enum_variant(), place, dest.clone())
923            };
924
925            for (i, field) in variant_def.fields.iter_enumerated() {
926                let ty = field.ty(*ecx.tcx, args);
927                let Some(field) = map.apply(variant_place, TrackElem::Field(i)) else {
928                    throw_machine_stop_str!("missing field in ADT")
929                };
930                let field_dest = ecx.project_field(&variant_dest, i)?;
931                try_write_constant(ecx, &field_dest, field, ty, state, map)?;
932            }
933            ecx.write_discriminant(variant_idx, dest)?;
934        }
935
936        // Unsupported for now.
937        ty::Array(_, _)
938        | ty::Pat(_, _)
939
940        // Do not attempt to support indirection in constants.
941        | ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Str | ty::Slice(_)
942
943        | ty::Never
944        | ty::Foreign(..)
945        | ty::Alias(..)
946        | ty::Param(_)
947        | ty::Bound(..)
948        | ty::Placeholder(..)
949        | ty::Closure(..)
950        | ty::CoroutineClosure(..)
951        | ty::Coroutine(..)
952        | ty::Dynamic(..)
953        | ty::UnsafeBinder(_) => throw_machine_stop_str!("unsupported type"),
954
955        ty::Error(_) | ty::Infer(..) | ty::CoroutineWitness(..) => bug!(),
956    }
957
958    interp_ok(())
959}
960
961impl<'tcx> ResultsVisitor<'tcx, ConstAnalysis<'_, 'tcx>> for Collector<'_, 'tcx> {
962    #[instrument(level = "trace", skip(self, analysis, statement))]
963    fn visit_after_early_statement_effect(
964        &mut self,
965        analysis: &ConstAnalysis<'_, 'tcx>,
966        state: &State<FlatSet<Scalar>>,
967        statement: &Statement<'tcx>,
968        location: Location,
969    ) {
970        match &statement.kind {
971            StatementKind::Assign(box (_, rvalue)) => {
972                OperandCollector {
973                    state,
974                    visitor: self,
975                    ecx: &mut analysis.ecx.borrow_mut(),
976                    map: &analysis.map,
977                }
978                .visit_rvalue(rvalue, location);
979            }
980            _ => (),
981        }
982    }
983
984    #[instrument(level = "trace", skip(self, analysis, statement))]
985    fn visit_after_primary_statement_effect(
986        &mut self,
987        analysis: &ConstAnalysis<'_, 'tcx>,
988        state: &State<FlatSet<Scalar>>,
989        statement: &Statement<'tcx>,
990        location: Location,
991    ) {
992        match statement.kind {
993            StatementKind::Assign(box (_, Rvalue::Use(Operand::Constant(_)))) => {
994                // Don't overwrite the assignment if it already uses a constant (to keep the span).
995            }
996            StatementKind::Assign(box (place, _)) => {
997                if let Some(value) = self.try_make_constant(
998                    &mut analysis.ecx.borrow_mut(),
999                    place,
1000                    state,
1001                    &analysis.map,
1002                ) {
1003                    self.patch.assignments.insert(location, value);
1004                }
1005            }
1006            _ => (),
1007        }
1008    }
1009
1010    fn visit_after_early_terminator_effect(
1011        &mut self,
1012        analysis: &ConstAnalysis<'_, 'tcx>,
1013        state: &State<FlatSet<Scalar>>,
1014        terminator: &Terminator<'tcx>,
1015        location: Location,
1016    ) {
1017        OperandCollector {
1018            state,
1019            visitor: self,
1020            ecx: &mut analysis.ecx.borrow_mut(),
1021            map: &analysis.map,
1022        }
1023        .visit_terminator(terminator, location);
1024    }
1025}
1026
1027impl<'tcx> MutVisitor<'tcx> for Patch<'tcx> {
1028    fn tcx(&self) -> TyCtxt<'tcx> {
1029        self.tcx
1030    }
1031
1032    fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
1033        if let Some(value) = self.assignments.get(&location) {
1034            match &mut statement.kind {
1035                StatementKind::Assign(box (_, rvalue)) => {
1036                    *rvalue = Rvalue::Use(self.make_operand(*value));
1037                }
1038                _ => bug!("found assignment info for non-assign statement"),
1039            }
1040        } else {
1041            self.super_statement(statement, location);
1042        }
1043    }
1044
1045    fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1046        match operand {
1047            Operand::Copy(place) | Operand::Move(place) => {
1048                if let Some(value) = self.before_effect.get(&(location, *place)) {
1049                    *operand = self.make_operand(*value);
1050                } else if !place.projection.is_empty() {
1051                    self.super_operand(operand, location)
1052                }
1053            }
1054            Operand::Constant(_) => {}
1055        }
1056    }
1057
1058    fn process_projection_elem(
1059        &mut self,
1060        elem: PlaceElem<'tcx>,
1061        location: Location,
1062    ) -> Option<PlaceElem<'tcx>> {
1063        if let PlaceElem::Index(local) = elem {
1064            let offset = self.before_effect.get(&(location, local.into()))?;
1065            let offset = offset.try_to_scalar()?;
1066            let offset = offset.to_target_usize(&self.tcx).discard_err()?;
1067            let min_length = offset.checked_add(1)?;
1068            Some(PlaceElem::ConstantIndex { offset, min_length, from_end: false })
1069        } else {
1070            None
1071        }
1072    }
1073}
1074
1075struct OperandCollector<'a, 'b, 'tcx> {
1076    state: &'a State<FlatSet<Scalar>>,
1077    visitor: &'a mut Collector<'b, 'tcx>,
1078    ecx: &'a mut InterpCx<'tcx, DummyMachine>,
1079    map: &'a Map<'tcx>,
1080}
1081
1082impl<'tcx> Visitor<'tcx> for OperandCollector<'_, '_, 'tcx> {
1083    fn visit_projection_elem(
1084        &mut self,
1085        _: PlaceRef<'tcx>,
1086        elem: PlaceElem<'tcx>,
1087        _: PlaceContext,
1088        location: Location,
1089    ) {
1090        if let PlaceElem::Index(local) = elem
1091            && let Some(value) =
1092                self.visitor.try_make_constant(self.ecx, local.into(), self.state, self.map)
1093        {
1094            self.visitor.patch.before_effect.insert((location, local.into()), value);
1095        }
1096    }
1097
1098    fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
1099        if let Some(place) = operand.place() {
1100            if let Some(value) =
1101                self.visitor.try_make_constant(self.ecx, place, self.state, self.map)
1102            {
1103                self.visitor.patch.before_effect.insert((location, place), value);
1104            } else if !place.projection.is_empty() {
1105                // Try to propagate into `Index` projections.
1106                self.super_operand(operand, location)
1107            }
1108        }
1109    }
1110}