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