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::mir::interpret::{InterpResult, Scalar};
16use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor};
17use rustc_middle::mir::*;
18use rustc_middle::ty::{self, Ty, TyCtxt};
19use rustc_mir_dataflow::fmt::DebugWithContext;
20use rustc_mir_dataflow::lattice::{FlatSet, HasBottom};
21use rustc_mir_dataflow::value_analysis::{
22 Map, PlaceCollectionMode, PlaceIndex, State, TrackElem, ValueOrPlace, debug_with_context,
23};
24use rustc_mir_dataflow::{Analysis, ResultsVisitor, visit_results};
25use rustc_span::{DUMMY_SP, bug};
26use tracing::{debug, debug_span, instrument};
27
28use crate::PassPolicy;
29
30const BLOCK_LIMIT: usize = 100;
33const PLACE_LIMIT: usize = 100;
34
35pub(super) struct DataflowConstProp;
36
37impl<'tcx> crate::MirPass<'tcx> for DataflowConstProp {
38 fn policy(&self, ctx: &crate::PassCtx<'_>) -> PassPolicy {
39 PassPolicy::optional(ctx.mir_opt_level() >= 3)
40 }
41
42 #[instrument(skip_all level = "debug")]
43 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
44 if body.coroutine.is_some() {
46 return;
47 }
48
49 debug!(def_id = ?body.source.def_id());
50 if tcx.sess.mir_opt_level() < 4 && body.basic_blocks.len() > BLOCK_LIMIT {
51 debug!("aborted dataflow const prop due too many basic blocks");
52 return;
53 }
54
55 let value_limit = if tcx.sess.mir_opt_level() < 4 { Some(PLACE_LIMIT) } else { None };
64
65 let map = Map::new(tcx, body, PlaceCollectionMode::Full { value_limit });
67
68 let const_ = debug_span!("analyze")
70 .in_scope(|| ConstAnalysis::new(tcx, body, map).iterate_to_fixpoint(tcx, body, None));
71
72 let mut visitor = Collector::new(tcx, body, &const_.analysis.map);
74 debug_span!("collect").in_scope(|| {
75 visit_results(body, traversal::reachable(body).map(|(bb, _)| bb), &const_, &mut visitor)
76 });
77 let mut patch = visitor.patch;
78 debug_span!("patch").in_scope(|| patch.visit_body_preserves_cfg(body));
79 }
80}
81
82struct ConstAnalysis<'a, 'tcx> {
87 map: Map<'tcx>,
88 tcx: TyCtxt<'tcx>,
89 local_decls: &'a LocalDecls<'tcx>,
90 ecx: InterpCx<'tcx, DummyMachine>,
91 typing_env: ty::TypingEnv<'tcx>,
92}
93
94impl<'tcx> Analysis<'tcx> for ConstAnalysis<'_, 'tcx> {
95 type Domain = State<FlatSet<Scalar>>;
96
97 const NAME: &'static str = "ConstAnalysis";
98
99 fn bottom_value(&self, _body: &Body<'tcx>) -> Self::Domain {
103 State::Unreachable
104 }
105
106 fn initialize_start_block(&self, body: &Body<'tcx>, state: &mut Self::Domain) {
107 assert_matches!(state, State::Unreachable);
109 *state = State::new_reachable();
110 for arg in body.args_iter() {
111 state.flood(PlaceRef { local: arg, projection: &[] }, &self.map);
112 }
113 }
114
115 fn apply_primary_statement_effect(
116 &self,
117 state: &mut Self::Domain,
118 statement: &Statement<'tcx>,
119 _location: Location,
120 ) {
121 if state.is_reachable() {
122 self.handle_statement(statement, state);
123 }
124 }
125
126 fn get_terminator_edges<'mir>(
127 &self,
128 state: &Self::Domain,
129 terminator: &'mir Terminator<'tcx>,
130 _location: Location,
131 ) -> TerminatorEdges<'mir, 'tcx> {
132 if state.is_reachable() {
133 if let TerminatorKind::SwitchInt { discr, targets } = &terminator.kind {
134 self.get_switch_int_edges(discr, targets, state)
135 } else {
136 terminator.edges()
137 }
138 } else {
139 TerminatorEdges::None
140 }
141 }
142
143 fn apply_primary_terminator_effect(
144 &self,
145 state: &mut Self::Domain,
146 terminator: &Terminator<'tcx>,
147 _location: Location,
148 ) {
149 if state.is_reachable() {
150 self.handle_terminator(terminator, state)
151 }
152 }
153
154 fn apply_call_return_effect(
155 &self,
156 state: &mut Self::Domain,
157 _block: BasicBlock,
158 return_places: CallReturnPlaces<'_, 'tcx>,
159 ) {
160 if state.is_reachable() {
161 self.handle_call_return(return_places, state)
162 }
163 }
164}
165
166impl<'a, 'tcx> ConstAnalysis<'a, 'tcx> {
167 fn new(tcx: TyCtxt<'tcx>, body: &'a Body<'tcx>, map: Map<'tcx>) -> Self {
168 let typing_env = body.typing_env(tcx);
169 Self {
170 map,
171 tcx,
172 local_decls: &body.local_decls,
173 ecx: InterpCx::new(tcx, DUMMY_SP, typing_env, DummyMachine),
174 typing_env,
175 }
176 }
177
178 fn handle_statement(&self, statement: &Statement<'tcx>, state: &mut State<FlatSet<Scalar>>) {
179 match &statement.kind {
180 StatementKind::Assign((place, rvalue)) => {
181 self.handle_assign(*place, rvalue, state);
182 }
183 StatementKind::SetDiscriminant { place, variant_index } => {
184 self.handle_set_discriminant(**place, *variant_index, state);
185 }
186 StatementKind::Intrinsic(intrinsic) => {
187 self.handle_intrinsic(intrinsic);
188 }
189 StatementKind::StorageLive(local) | StatementKind::StorageDead(local) => {
190 state.flood_with(
193 Place::from(*local).as_ref(),
194 &self.map,
195 FlatSet::<Scalar>::BOTTOM,
196 );
197 }
198 StatementKind::ConstEvalCounter
199 | StatementKind::Nop
200 | StatementKind::FakeRead(..)
201 | StatementKind::PlaceMention(..)
202 | StatementKind::Coverage(..)
203 | StatementKind::BackwardIncompatibleDropHint { .. }
204 | StatementKind::AscribeUserType(..) => {}
205 }
206 }
207
208 fn handle_intrinsic(&self, intrinsic: &NonDivergingIntrinsic<'tcx>) {
209 match intrinsic {
210 NonDivergingIntrinsic::Assume(..) => {
211 }
213 NonDivergingIntrinsic::CopyNonOverlapping(CopyNonOverlapping {
214 dst: _,
215 src: _,
216 count: _,
217 }) => {
218 }
220 }
221 }
222
223 fn handle_operand(&self, operand: &Operand<'tcx>) -> ValueOrPlace<FlatSet<Scalar>> {
224 match operand {
225 Operand::RuntimeChecks(_) => ValueOrPlace::TOP,
226 Operand::Constant(constant) => ValueOrPlace::Value(self.handle_constant(constant)),
227 Operand::Copy(place) | Operand::Move(place) => {
228 self.map.find(place.as_ref()).map(ValueOrPlace::Place).unwrap_or(ValueOrPlace::TOP)
231 }
232 }
233 }
234
235 fn handle_terminator<'mir>(
238 &self,
239 terminator: &'mir Terminator<'tcx>,
240 state: &mut State<FlatSet<Scalar>>,
241 ) {
242 match &terminator.kind {
243 TerminatorKind::Call { .. } | TerminatorKind::InlineAsm { .. } => {
244 }
246 TerminatorKind::Drop { place, .. } => {
247 state.flood_with(place.as_ref(), &self.map, FlatSet::<Scalar>::BOTTOM);
248 }
249 TerminatorKind::Yield { .. } => {
250 bug!("encountered disallowed terminator");
252 }
253 TerminatorKind::TailCall { .. } => {
254 }
257 TerminatorKind::SwitchInt { .. }
258 | TerminatorKind::Goto { .. }
259 | TerminatorKind::UnwindResume
260 | TerminatorKind::UnwindTerminate(_)
261 | TerminatorKind::Return
262 | TerminatorKind::Unreachable
263 | TerminatorKind::Assert { .. }
264 | TerminatorKind::CoroutineDrop
265 | TerminatorKind::FalseEdge { .. }
266 | TerminatorKind::FalseUnwind { .. } => {
267 }
269 }
270 }
271
272 fn handle_call_return(
273 &self,
274 return_places: CallReturnPlaces<'_, 'tcx>,
275 state: &mut State<FlatSet<Scalar>>,
276 ) {
277 return_places.for_each(|place| {
278 state.flood(place.as_ref(), &self.map);
279 })
280 }
281
282 fn handle_set_discriminant(
283 &self,
284 place: Place<'tcx>,
285 variant_index: VariantIdx,
286 state: &mut State<FlatSet<Scalar>>,
287 ) {
288 state.flood_discr(place.as_ref(), &self.map);
289 if self.map.find_discr(place.as_ref()).is_some() {
290 let enum_ty = place.ty(self.local_decls, self.tcx).ty;
291 if let Some(discr) = self.eval_discriminant(enum_ty, variant_index) {
292 state.assign_discr(
293 place.as_ref(),
294 ValueOrPlace::Value(FlatSet::Elem(discr)),
295 &self.map,
296 );
297 }
298 }
299 }
300
301 fn handle_assign(
302 &self,
303 target: Place<'tcx>,
304 rvalue: &Rvalue<'tcx>,
305 state: &mut State<FlatSet<Scalar>>,
306 ) {
307 match rvalue {
308 Rvalue::Use(operand, _) => {
309 state.flood(target.as_ref(), &self.map);
310 if let Some(target) = self.map.find(target.as_ref()) {
311 self.assign_operand(state, target, operand);
312 }
313 }
314 Rvalue::CopyForDeref(_) => bug!("`CopyForDeref` in runtime MIR"),
315 Rvalue::Aggregate(kind, operands) => {
316 state.flood(target.as_ref(), &self.map);
319
320 let Some(target_idx) = self.map.find(target.as_ref()) else { return };
321
322 let (variant_target, variant_index) = match **kind {
323 AggregateKind::Tuple | AggregateKind::Closure(..) => (Some(target_idx), None),
324 AggregateKind::Adt(def_id, variant_index, ..) => {
325 match self.tcx.def_kind(def_id) {
326 DefKind::Struct => (Some(target_idx), None),
327 DefKind::Enum => (
328 self.map.apply(target_idx, TrackElem::Variant(variant_index)),
329 Some(variant_index),
330 ),
331 _ => return,
332 }
333 }
334 _ => return,
335 };
336 if let Some(variant_target_idx) = variant_target {
337 for (field_index, operand) in operands.iter_enumerated() {
338 if let Some(field) =
339 self.map.apply(variant_target_idx, TrackElem::Field(field_index))
340 {
341 self.assign_operand(state, field, operand);
342 }
343 }
344 }
345 if let Some(variant_index) = variant_index
346 && let Some(discr_idx) = self.map.apply(target_idx, TrackElem::Discriminant)
347 {
348 let enum_ty = target.ty(self.local_decls, self.tcx).ty;
354 if let Some(discr_val) = self.eval_discriminant(enum_ty, variant_index) {
355 state.insert_value_idx(discr_idx, FlatSet::Elem(discr_val), &self.map);
356 }
357 }
358 }
359 Rvalue::BinaryOp(op, (left, right)) if op.is_overflowing() => {
360 state.flood(target.as_ref(), &self.map);
362
363 let Some(target) = self.map.find(target.as_ref()) else { return };
364
365 let value_target = self.map.apply(target, TrackElem::Field(0_u32.into()));
366 let overflow_target = self.map.apply(target, TrackElem::Field(1_u32.into()));
367
368 if value_target.is_some() || overflow_target.is_some() {
369 let (val, overflow) = self.binary_op(state, *op, left, right);
370
371 if let Some(value_target) = value_target {
372 state.insert_value_idx(value_target, val, &self.map);
374 }
375 if let Some(overflow_target) = overflow_target {
376 state.insert_value_idx(overflow_target, overflow, &self.map);
378 }
379 }
380 }
381 Rvalue::Cast(
382 CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _),
383 operand,
384 _,
385 ) => {
386 let pointer = self.handle_operand(operand);
387 state.assign(target.as_ref(), pointer, &self.map);
388
389 if let Some(target_len) = self.map.find_len(target.as_ref())
390 && let operand_ty = operand.ty(self.local_decls, self.tcx)
391 && let Some(operand_ty) = operand_ty.builtin_deref(true)
392 && let ty::Array(_, len) = operand_ty.kind()
393 && let Some(len) = Const::Ty(self.tcx.types.usize, *len)
394 .try_eval_scalar_int(self.tcx, self.typing_env)
395 {
396 state.insert_value_idx(target_len, FlatSet::Elem(len.into()), &self.map);
397 }
398 }
399 _ => {
400 let result = self.handle_rvalue(rvalue, state);
401 state.assign(target.as_ref(), result, &self.map);
402 }
403 }
404 }
405
406 fn handle_rvalue(
407 &self,
408 rvalue: &Rvalue<'tcx>,
409 state: &mut State<FlatSet<Scalar>>,
410 ) -> ValueOrPlace<FlatSet<Scalar>> {
411 let val = match rvalue {
412 Rvalue::Cast(CastKind::IntToInt | CastKind::IntToFloat, operand, ty) => {
413 let Ok(layout) = self.tcx.layout_of(self.typing_env.as_query_input(*ty)) else {
414 return ValueOrPlace::Value(FlatSet::Top);
415 };
416 match self.eval_operand(operand, state) {
417 FlatSet::Elem(op) => self
418 .ecx
419 .int_to_int_or_float(&op, layout)
420 .discard_err()
421 .map_or(FlatSet::Top, |result| self.wrap_immediate(*result)),
422 FlatSet::Bottom => FlatSet::Bottom,
423 FlatSet::Top => FlatSet::Top,
424 }
425 }
426 Rvalue::Cast(CastKind::FloatToInt | CastKind::FloatToFloat, operand, ty) => {
427 let Ok(layout) = self.tcx.layout_of(self.typing_env.as_query_input(*ty)) else {
428 return ValueOrPlace::Value(FlatSet::Top);
429 };
430 match self.eval_operand(operand, state) {
431 FlatSet::Elem(op) => self
432 .ecx
433 .float_to_float_or_int(&op, layout)
434 .discard_err()
435 .map_or(FlatSet::Top, |result| self.wrap_immediate(*result)),
436 FlatSet::Bottom => FlatSet::Bottom,
437 FlatSet::Top => FlatSet::Top,
438 }
439 }
440 Rvalue::Cast(CastKind::Transmute | CastKind::Subtype, operand, _) => {
441 match self.eval_operand(operand, state) {
442 FlatSet::Elem(op) => self.wrap_immediate(*op),
443 FlatSet::Bottom => FlatSet::Bottom,
444 FlatSet::Top => FlatSet::Top,
445 }
446 }
447 Rvalue::BinaryOp(op, (left, right)) if !op.is_overflowing() => {
448 let (val, _overflow) = self.binary_op(state, *op, left, right);
451 val
452 }
453 Rvalue::UnaryOp(op, operand) => {
454 if let UnOp::PtrMetadata = op
455 && let Some(place) = operand.place()
456 && let Some(len) = self.map.find_len(place.as_ref())
457 {
458 return ValueOrPlace::Place(len);
459 }
460 match self.eval_operand(operand, state) {
461 FlatSet::Elem(value) => self
462 .ecx
463 .unary_op(*op, &value)
464 .discard_err()
465 .map_or(FlatSet::Top, |val| self.wrap_immediate(*val)),
466 FlatSet::Bottom => FlatSet::Bottom,
467 FlatSet::Top => FlatSet::Top,
468 }
469 }
470 Rvalue::Discriminant(place) => state.get_discr(place.as_ref(), &self.map),
471 Rvalue::Use(operand, _) => return self.handle_operand(operand),
472 Rvalue::CopyForDeref(_) => bug!("`CopyForDeref` in runtime MIR"),
473 Rvalue::Ref(..) | Rvalue::Reborrow(..) | Rvalue::RawPtr(..) => {
474 return ValueOrPlace::TOP;
476 }
477 Rvalue::Repeat(..)
478 | Rvalue::ThreadLocalRef(..)
479 | Rvalue::Cast(..)
480 | Rvalue::BinaryOp(..)
481 | Rvalue::Aggregate(..)
482 | Rvalue::WrapUnsafeBinder(..) => {
483 return ValueOrPlace::TOP;
485 }
486 };
487 ValueOrPlace::Value(val)
488 }
489
490 fn handle_constant(&self, constant: &ConstOperand<'tcx>) -> FlatSet<Scalar> {
491 constant
492 .const_
493 .try_eval_scalar(self.tcx, self.typing_env)
494 .map_or(FlatSet::Top, FlatSet::Elem)
495 }
496
497 fn get_switch_int_edges<'mir>(
498 &self,
499 discr: &'mir Operand<'tcx>,
500 targets: &'mir SwitchTargets,
501 state: &State<FlatSet<Scalar>>,
502 ) -> TerminatorEdges<'mir, 'tcx> {
503 let value = match self.handle_operand(discr) {
504 ValueOrPlace::Value(value) => value,
505 ValueOrPlace::Place(place) => state.get_idx(place, &self.map),
506 };
507 match value {
508 FlatSet::Bottom => TerminatorEdges::None,
511 FlatSet::Elem(scalar) => {
512 if let Ok(scalar_int) = scalar.try_to_scalar_int() {
513 TerminatorEdges::Single(
514 targets.target_for_value(scalar_int.to_bits_unchecked()),
515 )
516 } else {
517 TerminatorEdges::SwitchInt { discr, targets }
518 }
519 }
520 FlatSet::Top => TerminatorEdges::SwitchInt { discr, targets },
521 }
522 }
523
524 fn assign_operand(
526 &self,
527 state: &mut State<FlatSet<Scalar>>,
528 place: PlaceIndex,
529 operand: &Operand<'tcx>,
530 ) {
531 match operand {
532 Operand::RuntimeChecks(_) => {}
533 Operand::Copy(rhs) | Operand::Move(rhs) => {
534 if let Some(rhs) = self.map.find(rhs.as_ref()) {
535 state.insert_place_idx(place, rhs, &self.map);
536 } else if rhs.projection.first() == Some(&PlaceElem::Deref)
537 && let FlatSet::Elem(pointer) = state.get(rhs.local.into(), &self.map)
538 && let rhs_ty = self.local_decls[rhs.local].ty
539 && let Ok(rhs_layout) =
540 self.tcx.layout_of(self.typing_env.as_query_input(rhs_ty))
541 {
542 let op = ImmTy::from_scalar(pointer, rhs_layout).into();
543 self.assign_constant(state, place, op, rhs.projection);
544 }
545 }
546 Operand::Constant(constant) => {
547 if let Some(constant) =
548 self.ecx.eval_mir_constant(&constant.const_, constant.span, None).discard_err()
549 {
550 self.assign_constant(state, place, constant, &[]);
551 }
552 }
553 }
554 }
555
556 #[instrument(level = "trace", skip(self, state))]
560 fn assign_constant(
561 &self,
562 state: &mut State<FlatSet<Scalar>>,
563 place: PlaceIndex,
564 mut operand: OpTy<'tcx>,
565 projection: &[PlaceElem<'tcx>],
566 ) {
567 for &(mut proj_elem) in projection {
568 if let PlaceElem::Index(index) = proj_elem {
569 if let FlatSet::Elem(index) = state.get(index.into(), &self.map)
570 && let Some(offset) = index.to_target_usize(&self.tcx).discard_err()
571 && let Some(min_length) = offset.checked_add(1)
572 {
573 proj_elem = PlaceElem::ConstantIndex { offset, min_length, from_end: false };
574 } else {
575 return;
576 }
577 }
578 operand = if let Some(operand) = self.ecx.project(&operand, proj_elem).discard_err() {
579 operand
580 } else {
581 return;
582 }
583 }
584
585 self.map.for_each_projection_value(
586 place,
587 operand,
588 &mut |elem, op| match elem {
589 TrackElem::Field(idx) => self.ecx.project_field(op, idx).discard_err(),
590 TrackElem::Variant(idx) => self.ecx.project_downcast(op, idx).discard_err(),
591 TrackElem::Discriminant => {
592 let variant = self.ecx.read_discriminant(op).discard_err()?;
593 let discr_value =
594 self.ecx.discriminant_for_variant(op.layout.ty, variant).discard_err()?;
595 Some(discr_value.into())
596 }
597 TrackElem::DerefLen => {
598 let op: OpTy<'_> = self.ecx.deref_pointer(op).discard_err()?.into();
599 let len_usize = op.len(&self.ecx).discard_err()?;
600 let layout = self
601 .tcx
602 .layout_of(self.typing_env.as_query_input(self.tcx.types.usize))
603 .unwrap();
604 Some(ImmTy::from_uint(len_usize, layout).into())
605 }
606 },
607 &mut |place, op| {
608 if let Some(imm) = self.ecx.read_immediate_raw(op).discard_err()
609 && let Some(imm) = imm.right()
610 {
611 let elem = self.wrap_immediate(*imm);
612 state.insert_value_idx(place, elem, &self.map);
613 }
614 },
615 );
616 }
617
618 fn binary_op(
619 &self,
620 state: &mut State<FlatSet<Scalar>>,
621 op: BinOp,
622 left: &Operand<'tcx>,
623 right: &Operand<'tcx>,
624 ) -> (FlatSet<Scalar>, FlatSet<Scalar>) {
625 let left = self.eval_operand(left, state);
626 let right = self.eval_operand(right, state);
627
628 match (left, right) {
629 (FlatSet::Bottom, _) | (_, FlatSet::Bottom) => (FlatSet::Bottom, FlatSet::Bottom),
630 (FlatSet::Elem(left), FlatSet::Elem(right)) => {
632 match self.ecx.binary_op(op, &left, &right).discard_err() {
633 Some(val) => {
637 if matches!(val.layout.backend_repr, BackendRepr::ScalarPair { .. }) {
638 let (val, overflow) = val.to_scalar_pair();
639 (FlatSet::Elem(val), FlatSet::Elem(overflow))
640 } else {
641 (FlatSet::Elem(val.to_scalar()), FlatSet::Bottom)
642 }
643 }
644 _ => (FlatSet::Top, FlatSet::Top),
645 }
646 }
647 (FlatSet::Elem(const_arg), _) | (_, FlatSet::Elem(const_arg)) => {
649 let layout = const_arg.layout;
650 if !matches!(layout.backend_repr, rustc_abi::BackendRepr::Scalar(..)) {
651 return (FlatSet::Top, FlatSet::Top);
652 }
653
654 let arg_scalar = const_arg.to_scalar();
655 let Some(arg_value) = arg_scalar.to_bits(layout.size).discard_err() else {
656 return (FlatSet::Top, FlatSet::Top);
657 };
658
659 match op {
660 BinOp::BitAnd if arg_value == 0 => (FlatSet::Elem(arg_scalar), FlatSet::Bottom),
661 BinOp::BitOr
662 if arg_value == layout.size.truncate(u128::MAX)
663 || (layout.ty.is_bool() && arg_value == 1) =>
664 {
665 (FlatSet::Elem(arg_scalar), FlatSet::Bottom)
666 }
667 BinOp::Mul if layout.ty.is_integral() && arg_value == 0 => {
668 (FlatSet::Elem(arg_scalar), FlatSet::Elem(Scalar::from_bool(false)))
669 }
670 _ => (FlatSet::Top, FlatSet::Top),
671 }
672 }
673 (FlatSet::Top, FlatSet::Top) => (FlatSet::Top, FlatSet::Top),
674 }
675 }
676
677 fn eval_operand(
678 &self,
679 op: &Operand<'tcx>,
680 state: &mut State<FlatSet<Scalar>>,
681 ) -> FlatSet<ImmTy<'tcx>> {
682 let value = match self.handle_operand(op) {
683 ValueOrPlace::Value(value) => value,
684 ValueOrPlace::Place(place) => state.get_idx(place, &self.map),
685 };
686 match value {
687 FlatSet::Top => FlatSet::Top,
688 FlatSet::Elem(scalar) => {
689 let ty = op.ty(self.local_decls, self.tcx);
690 self.tcx
691 .layout_of(self.typing_env.as_query_input(ty))
692 .map_or(FlatSet::Top, |layout| {
693 FlatSet::Elem(ImmTy::from_scalar(scalar, layout))
694 })
695 }
696 FlatSet::Bottom => FlatSet::Bottom,
697 }
698 }
699
700 fn eval_discriminant(&self, enum_ty: Ty<'tcx>, variant_index: VariantIdx) -> Option<Scalar> {
701 if !enum_ty.is_enum() {
702 return None;
703 }
704 let enum_ty_layout = self.tcx.layout_of(self.typing_env.as_query_input(enum_ty)).ok()?;
705 let discr_value =
706 self.ecx.discriminant_for_variant(enum_ty_layout.ty, variant_index).discard_err()?;
707 Some(discr_value.to_scalar())
708 }
709
710 fn wrap_immediate(&self, imm: Immediate) -> FlatSet<Scalar> {
711 match imm {
712 Immediate::Scalar(scalar) => FlatSet::Elem(scalar),
713 Immediate::Uninit => FlatSet::Bottom,
714 _ => FlatSet::Top,
715 }
716 }
717}
718
719impl<'tcx> DebugWithContext<ConstAnalysis<'_, 'tcx>> for State<FlatSet<Scalar>> {
721 fn fmt_with(&self, ctxt: &ConstAnalysis<'_, 'tcx>, f: &mut Formatter<'_>) -> std::fmt::Result {
722 match self {
723 State::Reachable(values) => debug_with_context(values, None, &ctxt.map, f),
724 State::Unreachable => write!(f, "unreachable"),
725 }
726 }
727
728 fn fmt_diff_with(
729 &self,
730 old: &Self,
731 ctxt: &ConstAnalysis<'_, 'tcx>,
732 f: &mut Formatter<'_>,
733 ) -> std::fmt::Result {
734 match (self, old) {
735 (State::Reachable(this), State::Reachable(old)) => {
736 debug_with_context(this, Some(old), &ctxt.map, f)
737 }
738 _ => Ok(()), }
740 }
741}
742
743struct Patch<'tcx> {
744 tcx: TyCtxt<'tcx>,
745
746 before_effect: FxHashMap<(Location, Place<'tcx>), Const<'tcx>>,
750
751 assignments: FxHashMap<Location, Const<'tcx>>,
753}
754
755impl<'tcx> Patch<'tcx> {
756 pub(crate) fn new(tcx: TyCtxt<'tcx>) -> Self {
757 Self { tcx, before_effect: FxHashMap::default(), assignments: FxHashMap::default() }
758 }
759
760 fn make_operand(&self, const_: Const<'tcx>) -> Operand<'tcx> {
761 Operand::Constant(Box::new(ConstOperand { span: DUMMY_SP, user_ty: None, const_ }))
762 }
763}
764
765struct Collector<'a, 'tcx> {
766 patch: Patch<'tcx>,
767 local_decls: &'a LocalDecls<'tcx>,
768 ecx: InterpCx<'tcx, DummyMachine>,
769 map: &'a Map<'tcx>,
770}
771
772impl<'a, 'tcx> Collector<'a, 'tcx> {
773 pub(crate) fn new(tcx: TyCtxt<'tcx>, body: &'a Body<'tcx>, map: &'a Map<'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 map,
779 }
780 }
781
782 #[instrument(level = "trace", skip(self), ret)]
783 fn try_make_constant(
784 &mut self,
785 place: Place<'tcx>,
786 state: &State<FlatSet<Scalar>>,
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 = self.map.find(place.as_ref())?;
800 if layout.backend_repr.is_scalar()
801 && let Some(value) = propagatable_scalar(place, state, self.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, self.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, statement))]
944 fn visit_after_early_statement_effect(
945 &mut self,
946 state: &State<FlatSet<Scalar>>,
947 statement: &Statement<'tcx>,
948 location: Location,
949 ) {
950 match &statement.kind {
951 StatementKind::Assign((_, rvalue)) => {
952 OperandCollector { state, visitor: self }.visit_rvalue(rvalue, location);
953 }
954 _ => (),
955 }
956 }
957
958 #[instrument(level = "trace", skip(self, statement))]
959 fn visit_after_primary_statement_effect(
960 &mut self,
961 state: &State<FlatSet<Scalar>>,
962 statement: &Statement<'tcx>,
963 location: Location,
964 ) {
965 match statement.kind {
966 StatementKind::Assign((_, Rvalue::Use(Operand::Constant(_), _))) => {
967 }
969 StatementKind::Assign((place, _)) => {
970 if let Some(value) = self.try_make_constant(place, state) {
971 self.patch.assignments.insert(location, value);
972 }
973 }
974 _ => (),
975 }
976 }
977
978 fn visit_after_early_terminator_effect(
979 &mut self,
980 state: &State<FlatSet<Scalar>>,
981 terminator: &Terminator<'tcx>,
982 location: Location,
983 ) {
984 OperandCollector { state, visitor: self }.visit_terminator(terminator, location);
985 }
986}
987
988impl<'tcx> MutVisitor<'tcx> for Patch<'tcx> {
989 fn tcx(&self) -> TyCtxt<'tcx> {
990 self.tcx
991 }
992
993 fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
994 if let Some(value) = self.assignments.get(&location) {
995 match &mut statement.kind {
996 StatementKind::Assign((_, rvalue)) => {
997 let old_retag = match rvalue {
998 Rvalue::Use(_, retag) => *retag,
999 _ => WithRetag::Yes,
1000 };
1001 *rvalue = Rvalue::Use(self.make_operand(*value), old_retag);
1002 }
1003 _ => bug!("found assignment info for non-assign statement"),
1004 }
1005 } else {
1006 self.super_statement(statement, location);
1007 }
1008 }
1009
1010 fn visit_operand(&mut self, operand: &mut Operand<'tcx>, location: Location) {
1011 match operand {
1012 Operand::Copy(place) | Operand::Move(place) => {
1013 if let Some(value) = self.before_effect.get(&(location, *place)) {
1014 *operand = self.make_operand(*value);
1015 } else if !place.projection.is_empty() {
1016 self.super_operand(operand, location)
1017 }
1018 }
1019 Operand::Constant(_) | Operand::RuntimeChecks(_) => {}
1020 }
1021 }
1022
1023 fn process_projection_elem(
1024 &mut self,
1025 elem: PlaceElem<'tcx>,
1026 location: Location,
1027 ) -> Option<PlaceElem<'tcx>> {
1028 if let PlaceElem::Index(local) = elem {
1029 let offset = self.before_effect.get(&(location, local.into()))?;
1030 let offset = offset.try_to_scalar()?;
1031 let offset = offset.to_target_usize(&self.tcx).discard_err()?;
1032 let min_length = offset.checked_add(1)?;
1033 Some(PlaceElem::ConstantIndex { offset, min_length, from_end: false })
1034 } else {
1035 None
1036 }
1037 }
1038}
1039
1040struct OperandCollector<'a, 'b, 'tcx> {
1041 state: &'a State<FlatSet<Scalar>>,
1042 visitor: &'a mut Collector<'b, 'tcx>,
1043}
1044
1045impl<'tcx> Visitor<'tcx> for OperandCollector<'_, '_, 'tcx> {
1046 fn visit_projection_elem(
1047 &mut self,
1048 _: PlaceRef<'tcx>,
1049 elem: PlaceElem<'tcx>,
1050 _: PlaceContext,
1051 location: Location,
1052 ) {
1053 if let PlaceElem::Index(local) = elem
1054 && let Some(value) = self.visitor.try_make_constant(local.into(), self.state)
1055 {
1056 self.visitor.patch.before_effect.insert((location, local.into()), value);
1057 }
1058 }
1059
1060 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
1061 if let Some(place) = operand.place() {
1062 if let Some(value) = self.visitor.try_make_constant(place, self.state) {
1063 self.visitor.patch.before_effect.insert((location, place), value);
1064 } else if !place.projection.is_empty() {
1065 self.super_operand(operand, location)
1067 }
1068 }
1069 }
1070}