Skip to main content

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