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