Skip to main content

rapx/analysis/dataflow/
call_summary.rs

1//! Call-effect summaries shared by VM execution and dataflow analysis.
2mod dependency_semantics;
3pub(crate) mod effects;
4pub(crate) mod function_var;
5pub(crate) mod pointer_semantics;
6
7use rustc_middle::{
8    mir::Operand,
9    ty::{FloatTy, Ty, TyCtxt, TyKind, TypingEnv},
10};
11use rustc_span::DUMMY_SP;
12
13pub(crate) use dependency_semantics::VerifierCallSemantics;
14
15/// Evaluate a valid constant input to `float_to_int_unchecked` exactly.
16pub(crate) fn constant_float_to_int<'tcx>(tcx: TyCtxt<'tcx>, input: &Operand<'tcx>, dest_ty: Ty<'tcx>) -> Option<u128> {
17    let Operand::Constant(constant) = input else { return None };
18    let scalar = constant.const_.eval(tcx, TypingEnv::fully_monomorphized(), DUMMY_SP)
19        .ok()?
20        .try_to_scalar_int()?;
21    let value = match constant.const_.ty().kind() {
22        TyKind::Float(FloatTy::F32) => f32::from_bits(scalar.to_bits(scalar.size()) as u32) as f64,
23        TyKind::Float(FloatTy::F64) => f64::from_bits(scalar.to_bits(scalar.size()) as u64),
24        _ => return None,
25    };
26    let width = (tcx.layout_of(TypingEnv::fully_monomorphized().as_query_input(dest_ty))
27        .ok()?.size.bytes() * 8) as i32;
28    if !value.is_finite() || !(1..=128).contains(&width) { return None }
29    match dest_ty.kind() {
30        TyKind::Int(_) if value >= -2f64.powi(width - 1) && value < 2f64.powi(width - 1) => {
31            Some((value.trunc() as i128) as u128)
32        }
33        TyKind::Uint(_) if value >= 0.0 && value < 2f64.powi(width) => {
34            Some(value.trunc() as u128)
35        }
36        _ => None,
37    }
38}
39
40/// Effect summary consumed by the forward visitor.
41pub(crate) type CallEffectSummary = Vec<CallEffect>;
42
43/// Path-local effect produced by a retained call.
44#[derive(Clone, Debug)]
45pub(crate) enum CallEffect {
46    /// The return value aliases or is a direct value flow from an argument.
47    ReturnAliasArg { arg: usize },
48    /// The return value is a transparent copy of an argument's *value*
49    /// (`MaybeUninit::assume_init`, `ManuallyDrop::into_inner`): same term and
50    /// facts, retyped to the destination — no pointer `non_null` forcing.
51    ReturnArgValue { arg: usize },
52    ReturnOpaque,
53    /// Fold a constant unchecked float-to-int conversion; other inputs remain opaque.
54    ReturnFloatToIntUnchecked,
55    ReturnSizeOfVal { arg: usize },
56    ReturnRawEq { left_arg: usize, right_arg: usize },
57    ReturnExactDiv { lhs_arg: usize, rhs_arg: usize },
58    /// `select_unpredictable(cond, x, y)` returns either `x` or `y`: the result
59    /// is one of the two candidate values (`args[1]`/`args[2]`), non-deterministic
60    /// since the boolean selector (`args[0]`) is unpredictable.
61    SelectUnpredictable,
62    /// The return value is a pointer extracted from an aggregate/reference arg.
63    ReturnWrappingPointerOffset { base_arg: usize, offset_arg: usize },
64    ReturnPtrOffsetFrom { ptr_arg: usize, base_arg: usize },
65    /// The return value is a concrete layout/numeric constant.
66    ReturnConst { value: u64 },
67    ReallocateVec { arg: usize },
68    CopyMemory { source_arg: usize, destination_arg: usize, count_arg: usize },
69    SwapMemory { left_arg: usize, right_arg: usize },
70    FillBytes { pointer_arg: usize, byte_arg: usize, count_arg: usize },
71    ReturnNullableAllocation { size_arg: usize, align_arg: usize, zeroed: bool },
72    /// The return value is `min(lhs_arg, rhs_arg)`, satisfying
73    /// `return <= lhs_arg` and `return <= rhs_arg`.
74    ReturnMin { lhs_arg: usize, rhs_arg: usize },
75    /// The return value is `max(lhs_arg, rhs_arg)`.
76    ReturnMax { lhs_arg: usize, rhs_arg: usize },
77    /// The return value is `lhs_arg + rhs_arg`.
78    ReturnAdd { lhs_arg: usize, rhs_arg: usize },
79    /// The return value is `lhs_arg * rhs_arg`.
80    ReturnMul { lhs_arg: usize, rhs_arg: usize },
81    ReturnBoundedArithmetic {
82        lhs_arg: usize,
83        rhs_arg: usize,
84        op: BoundedArithmeticOp,
85    },
86    ReturnWithOverflow {
87        lhs_arg: usize,
88        rhs_arg: usize,
89        op: OverflowOp,
90    },
91    /// The return value is non-zero *iff* `arg` is non-zero (models bit-manipulating
92    /// intrinsics like `bswap`/`bitreverse`/`ctpop`/`rotate_*`, which map `0` to
93    /// `0` and non-zero to non-zero).
94    ReturnNonZeroIff { arg: usize },
95    ReturnLeadingZeros { arg: usize },
96    ReturnTrailingZeros { arg: usize },
97    ReturnAlignOfVal { arg: usize },
98    ReturnCompareBytes { left_arg: usize, right_arg: usize, count_arg: usize },
99    ReturnMaskedPointer { pointer_arg: usize, mask_arg: usize },
100    LoadMemory { pointer_arg: usize },
101    StoreMemory { pointer_arg: usize, value_arg: usize },
102    AtomicRmw { pointer_arg: usize },
103    SimdCompare { lhs_arg: usize, rhs_arg: usize, op: SimdCmpOp },
104    SimdArithmetic { lhs_arg: usize, rhs_arg: usize, op: SimdArithOp },
105    SimdOpaque,
106    SimdSplat { arg: usize },
107    SimdExtract { vector_arg: usize, index_arg: usize },
108    SimdInsert { vector_arg: usize, index_arg: usize, value_arg: usize },
109    SimdHavocMemory { pointer_arg: usize, mask_arg: usize },
110    SimdMaskedFallback { mask_arg: usize, fallback_arg: usize },
111    SimdBitmask { arg: usize },
112    /// The slice-to-Vec conversion creates a new allocation with the source length.
113    ReturnVecFromSlice,
114    /// `ptr.align_offset(align)` returns an offset such that
115    /// `(ptr + offset) % align == 0` and `0 <= offset < align` (or `usize::MAX`
116    /// when no such offset exists). Models `*const T::align_offset` /
117    /// `*mut T::align_offset` by recording the alignment path-condition so
118    /// downstream `ptr.add(offset)` dereferences can discharge `Align`.
119    ReturnAlignOffset { ptr_arg: usize, align_arg: usize },
120    /// `<ManuallyDrop<T> as Deref>::deref` / `MaybeDangling::as_ref` return a
121    /// reference to the inner value at the *same* address (transparent
122    /// wrappers).  The return aliases `arg` (a `&T` pointing at `arg`'s
123    /// pointee) and its pointee field values are the argument's field values
124    /// with the leading `peel` transparent field-0 hops stripped.
125    ReturnTransparentDeref { arg: usize, peel: usize },
126    /// `size_of::<T>()` / `align_of::<T>()` for a *generic* `T` (no concrete
127    /// layout): the result is the shared symbolic `sizeof_T` / `align_T`, bound
128    /// at apply time from `func`'s type argument.
129    ReturnLayoutSymbolic { is_size: bool },
130}
131
132impl CallEffect {
133    pub(super) fn written_args(&self) -> Vec<usize> {
134        match self {
135            Self::ReallocateVec { arg } => vec![*arg],
136            Self::StoreMemory { pointer_arg, .. }
137            | Self::AtomicRmw { pointer_arg }
138            | Self::SimdHavocMemory { pointer_arg, .. }
139            | Self::FillBytes { pointer_arg, .. } => vec![*pointer_arg],
140            Self::CopyMemory { destination_arg, .. } => vec![*destination_arg],
141            Self::SwapMemory { left_arg, right_arg } => vec![*left_arg, *right_arg],
142            _ => Vec::new(),
143        }
144    }
145
146    pub(super) fn write_inputs(&self) -> Vec<usize> {
147        match self {
148            Self::FillBytes { pointer_arg, byte_arg, count_arg } => {
149                vec![*pointer_arg, *byte_arg, *count_arg]
150            }
151            Self::StoreMemory { pointer_arg, value_arg } => vec![*pointer_arg, *value_arg],
152            Self::SimdHavocMemory { pointer_arg, mask_arg } => vec![*pointer_arg, *mask_arg],
153            Self::AtomicRmw { pointer_arg } => vec![*pointer_arg, 1, 2],
154            Self::CopyMemory { source_arg, destination_arg, count_arg } => {
155                vec![*source_arg, *destination_arg, *count_arg]
156            }
157            _ => self.written_args(),
158        }
159    }
160}
161
162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
163pub(crate) enum OverflowOp {
164    Add,
165    Sub,
166    Mul,
167}
168
169#[derive(Clone, Copy, Debug)]
170pub(crate) enum SimdCmpOp {
171    Eq,
172    Ne,
173    Lt,
174    Le,
175    Gt,
176    Ge,
177}
178
179#[derive(Clone, Copy, Debug)]
180pub(crate) enum SimdArithOp {
181    Add,
182    Sub,
183    Mul,
184    SaturatingAdd,
185    SaturatingSub,
186}
187
188#[derive(Clone, Copy, Debug)]
189pub(crate) enum BoundedArithmeticOp {
190    SaturatingAdd,
191    SaturatingSub,
192    WrappingAdd,
193    WrappingSub,
194}