1use 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
31const 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 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 let value_limit = if tcx.sess.mir_opt_level() < 4 { Some(PLACE_LIMIT) } else { None };
65
66 let map = Map::new(tcx, body, PlaceCollectionMode::Full { value_limit });
68
69 let const_ = debug_span!("analyze")
71 .in_scope(|| ConstAnalysis::new(tcx, body, map).iterate_to_fixpoint(tcx, body, None));
72
73 let mut visitor = Collector::new(tcx, body);
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
83struct 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 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 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 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 }
214 NonDivergingIntrinsic::CopyNonOverlapping(CopyNonOverlapping {
215 dst: _,
216 src: _,
217 count: _,
218 }) => {
219 }
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 self.map.find(place.as_ref()).map(ValueOrPlace::Place).unwrap_or(ValueOrPlace::TOP)
232 }
233 }
234 }
235
236 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 }
247 TerminatorKind::Drop { place, .. } => {
248 state.flood_with(place.as_ref(), &self.map, FlatSet::<Scalar>::BOTTOM);
249 }
250 TerminatorKind::Yield { .. } => {
251 bug!("encountered disallowed terminator");
253 }
254 TerminatorKind::TailCall { .. } => {
255 }
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 }
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 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 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 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 state.insert_value_idx(value_target, val, &self.map);
375 }
376 if let Some(overflow_target) = overflow_target {
377 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 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 return ValueOrPlace::TOP;
477 }
478 Rvalue::Repeat(..)
479 | Rvalue::ThreadLocalRef(..)
480 | Rvalue::Cast(..)
481 | Rvalue::BinaryOp(..)
482 | Rvalue::Aggregate(..)
483 | Rvalue::WrapUnsafeBinder(..) => {
484 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 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 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 #[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 (FlatSet::Elem(left), FlatSet::Elem(right)) => {
633 match self.ecx.binary_op(op, &left, &right).discard_err() {
634 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 (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
720impl<'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(()), }
741 }
742}
743
744struct Patch<'tcx> {
745 tcx: TyCtxt<'tcx>,
746
747 before_effect: FxHashMap<(Location, Place<'tcx>), Const<'tcx>>,
751
752 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}
771
772impl<'a, 'tcx> Collector<'a, 'tcx> {
773 pub(crate) fn new(tcx: TyCtxt<'tcx>, body: &'a Body<'tcx>) -> Self {
774 Self {
775 patch: Patch::new(tcx),
776 local_decls: &body.local_decls,
777 ecx: InterpCx::new(tcx, DUMMY_SP, body.typing_env(tcx), DummyMachine),
778 }
779 }
780
781 #[instrument(level = "trace", skip(self, map), ret)]
782 fn try_make_constant(
783 &mut self,
784 place: Place<'tcx>,
785 state: &State<FlatSet<Scalar>>,
786 map: &Map<'tcx>,
787 ) -> Option<Const<'tcx>> {
788 let ty = place.ty(self.local_decls, self.patch.tcx).ty;
789 let layout = self.ecx.layout_of(ty).ok()?;
790
791 if layout.is_zst() {
792 return Some(Const::zero_sized(ty));
793 }
794
795 if layout.is_unsized() {
796 return None;
797 }
798
799 let place = map.find(place.as_ref())?;
800 if layout.backend_repr.is_scalar()
801 && let Some(value) = propagatable_scalar(place, state, map)
802 {
803 return Some(Const::Val(ConstValue::Scalar(value), ty));
804 }
805
806 if matches!(layout.backend_repr, BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. }) {
807 let alloc_id = self
808 .ecx
809 .intern_with_temp_alloc(layout, |ecx, dest| {
810 try_write_constant(ecx, dest, place, ty, state, map)
811 })
812 .discard_err()?;
813 return Some(Const::Val(ConstValue::Indirect { alloc_id, offset: Size::ZERO }, ty));
814 }
815
816 None
817 }
818}
819
820#[instrument(level = "trace", skip(map), ret)]
821fn propagatable_scalar(
822 place: PlaceIndex,
823 state: &State<FlatSet<Scalar>>,
824 map: &Map<'_>,
825) -> Option<Scalar> {
826 if let FlatSet::Elem(value) = state.get_idx(place, map)
827 && value.try_to_scalar_int().is_ok()
828 {
829 Some(value)
831 } else {
832 None
833 }
834}
835
836#[instrument(level = "trace", skip(ecx, state, map), ret)]
837fn try_write_constant<'tcx>(
838 ecx: &mut InterpCx<'tcx, DummyMachine>,
839 dest: &PlaceTy<'tcx>,
840 place: PlaceIndex,
841 ty: Ty<'tcx>,
842 state: &State<FlatSet<Scalar>>,
843 map: &Map<'tcx>,
844) -> InterpResult<'tcx> {
845 let layout = ecx.layout_of(ty)?;
846
847 if layout.is_zst() {
849 return interp_ok(());
850 }
851
852 if layout.backend_repr.is_scalar()
854 && let Some(value) = propagatable_scalar(place, state, map)
855 {
856 return ecx.write_immediate(Immediate::Scalar(value), dest);
857 }
858
859 match ty.kind() {
860 ty::FnDef(..) => {}
862
863 ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Char => {
865 throw_machine_stop_str!("primitive type with provenance")
866 }
867
868 ty::Tuple(elem_tys) => {
869 for (i, elem) in elem_tys.iter().enumerate() {
870 let i = FieldIdx::from_usize(i);
871 let Some(field) = map.apply(place, TrackElem::Field(i)) else {
872 throw_machine_stop_str!("missing field in tuple")
873 };
874 let field_dest = ecx.project_field(dest, i)?;
875 try_write_constant(ecx, &field_dest, field, elem, state, map)?;
876 }
877 }
878
879 ty::Adt(def, args) => {
880 if def.is_union() {
881 throw_machine_stop_str!("cannot propagate unions")
882 }
883
884 let (variant_idx, variant_def, variant_place, variant_dest) = if def.is_enum() {
885 let Some(discr) = map.apply(place, TrackElem::Discriminant) else {
886 throw_machine_stop_str!("missing discriminant for enum")
887 };
888 let FlatSet::Elem(Scalar::Int(discr)) = state.get_idx(discr, map) else {
889 throw_machine_stop_str!("discriminant with provenance")
890 };
891 let discr_bits = discr.to_bits(discr.size());
892 let Some((variant, _)) =
893 def.discriminants(*ecx.tcx).find(|(_, var)| discr_bits == var.val)
894 else {
895 throw_machine_stop_str!("illegal discriminant for enum")
896 };
897 let Some(variant_place) = map.apply(place, TrackElem::Variant(variant)) else {
898 throw_machine_stop_str!("missing variant for enum")
899 };
900 let variant_dest = ecx.project_downcast(dest, variant)?;
901 (variant, def.variant(variant), variant_place, variant_dest)
902 } else {
903 (FIRST_VARIANT, def.non_enum_variant(), place, dest.clone())
904 };
905
906 for (i, field) in variant_def.fields.iter_enumerated() {
907 let ty = field.ty(*ecx.tcx, args).skip_norm_wip();
908 let Some(field) = map.apply(variant_place, TrackElem::Field(i)) else {
909 throw_machine_stop_str!("missing field in ADT")
910 };
911 let field_dest = ecx.project_field(&variant_dest, i)?;
912 try_write_constant(ecx, &field_dest, field, ty, state, map)?;
913 }
914 ecx.write_discriminant(variant_idx, dest)?;
915 }
916
917 ty::Array(_, _)
919 | ty::Pat(_, _)
920
921 | ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) | ty::Str | ty::Slice(_)
923
924 | ty::Never
925 | ty::Foreign(..)
926 | ty::Alias(..)
927 | ty::Param(_)
928 | ty::Bound(..)
929 | ty::Placeholder(..)
930 | ty::Closure(..)
931 | ty::CoroutineClosure(..)
932 | ty::Coroutine(..)
933 | ty::Dynamic(..)
934 | ty::UnsafeBinder(_) => throw_machine_stop_str!("unsupported type"),
935
936 ty::Error(_) | ty::Infer(..) | ty::CoroutineWitness(..) => bug!(),
937 }
938
939 interp_ok(())
940}
941
942impl<'tcx> ResultsVisitor<'tcx, ConstAnalysis<'_, 'tcx>> for Collector<'_, 'tcx> {
943 #[instrument(level = "trace", skip(self, analysis, statement))]
944 fn visit_after_early_statement_effect(
945 &mut self,
946 analysis: &ConstAnalysis<'_, 'tcx>,
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, map: &analysis.map }
954 .visit_rvalue(rvalue, location);
955 }
956 _ => (),
957 }
958 }
959
960 #[instrument(level = "trace", skip(self, analysis, statement))]
961 fn visit_after_primary_statement_effect(
962 &mut self,
963 analysis: &ConstAnalysis<'_, 'tcx>,
964 state: &State<FlatSet<Scalar>>,
965 statement: &Statement<'tcx>,
966 location: Location,
967 ) {
968 match statement.kind {
969 StatementKind::Assign((_, Rvalue::Use(Operand::Constant(_), _))) => {
970 }
972 StatementKind::Assign((place, _)) => {
973 if let Some(value) = self.try_make_constant(place, state, &analysis.map) {
974 self.patch.assignments.insert(location, value);
975 }
976 }
977 _ => (),
978 }
979 }
980
981 fn visit_after_early_terminator_effect(
982 &mut self,
983 analysis: &ConstAnalysis<'_, 'tcx>,
984 state: &State<FlatSet<Scalar>>,
985 terminator: &Terminator<'tcx>,
986 location: Location,
987 ) {
988 OperandCollector { state, visitor: self, map: &analysis.map }
989 .visit_terminator(terminator, location);
990 }
991}
992
993impl<'tcx> MutVisitor<'tcx> for Patch<'tcx> {
994 fn tcx(&self) -> TyCtxt<'tcx> {
995 self.tcx
996 }
997
998 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
999 if let Some(value) = self.assignments.get(&location) {
1000 match &mut statement.kind {
1001 StatementKind::Assign((_, rvalue)) => {
1002 let old_retag = match rvalue {
1003 Rvalue::Use(_, retag) => *retag,
1004 _ => WithRetag::Yes,
1005 };
1006 *rvalue = Rvalue::Use(self.make_operand(*value), old_retag);
1007 }
1008 _ => bug!("found assignment info for non-assign statement"),
1009 }
1010 } else {
1011 self.super_statement(statement, location);
1012 }
1013 }
1014
1015 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1016 match operand {
1017 Operand::Copy(place) | Operand::Move(place) => {
1018 if let Some(value) = self.before_effect.get(&(location, *place)) {
1019 *operand = self.make_operand(*value);
1020 } else if !place.projection.is_empty() {
1021 self.super_operand(operand, location)
1022 }
1023 }
1024 Operand::Constant(_) | Operand::RuntimeChecks(_) => {}
1025 }
1026 }
1027
1028 fn process_projection_elem(
1029 &mut self,
1030 elem: PlaceElem<'tcx>,
1031 location: Location,
1032 ) -> Option<PlaceElem<'tcx>> {
1033 if let PlaceElem::Index(local) = elem {
1034 let offset = self.before_effect.get(&(location, local.into()))?;
1035 let offset = offset.try_to_scalar()?;
1036 let offset = offset.to_target_usize(&self.tcx).discard_err()?;
1037 let min_length = offset.checked_add(1)?;
1038 Some(PlaceElem::ConstantIndex { offset, min_length, from_end: false })
1039 } else {
1040 None
1041 }
1042 }
1043}
1044
1045struct OperandCollector<'a, 'b, 'tcx> {
1046 state: &'a State<FlatSet<Scalar>>,
1047 visitor: &'a mut Collector<'b, 'tcx>,
1048 map: &'a Map<'tcx>,
1049}
1050
1051impl<'tcx> Visitor<'tcx> for OperandCollector<'_, '_, 'tcx> {
1052 fn visit_projection_elem(
1053 &mut self,
1054 _: PlaceRef<'tcx>,
1055 elem: PlaceElem<'tcx>,
1056 _: PlaceContext,
1057 location: Location,
1058 ) {
1059 if let PlaceElem::Index(local) = elem
1060 && let Some(value) = self.visitor.try_make_constant(local.into(), self.state, self.map)
1061 {
1062 self.visitor.patch.before_effect.insert((location, local.into()), value);
1063 }
1064 }
1065
1066 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
1067 if let Some(place) = operand.place() {
1068 if let Some(value) = self.visitor.try_make_constant(place, self.state, self.map) {
1069 self.visitor.patch.before_effect.insert((location, place), value);
1070 } else if !place.projection.is_empty() {
1071 self.super_operand(operand, location)
1073 }
1074 }
1075 }
1076}