tvm_tirx/sym/analyzer.rs
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20//! The analyzer. An [`Analyzer`] proves, bounds and simplifies integer expressions under the facts
21//! of a [`ConstraintContext`]; its bounds are [`ConstIntBound`]s and [`ModularSet`]s.
22
23// tvm-ffi-stubgen(file): mod(missing_docs = allow)
24// Python has no class for the `RewriteSimplifierStats` that `Analyzer.rewrite_simplify_stats()`
25// returns; it is here, with the analyzer it belongs to.
26
27// Names the hand-written wrappers use: the import section keeps them even when no generated block
28// does.
29// tvm-ffi-stubgen(import): tvm_ffi::Error
30// tvm-ffi-stubgen(import): tvm_ffi::Map
31// tvm-ffi-stubgen(import): tvm_ffi::Result
32// tvm-ffi-stubgen(import): tvm_ffi::String
33// tvm-ffi-stubgen(import): tvm_ffi::VALUE_ERROR
34// tvm-ffi-stubgen(import): crate::ExitOnDrop
35// tvm-ffi-stubgen(import): crate::ir::expr::Var
36// tvm-ffi-stubgen(import): crate::sym::int_set::IntSet
37// tvm-ffi-stubgen(import): crate::sym::constraint::ConstraintContext
38// tvm-ffi-stubgen(import): crate::ir::support
39// tvm-ffi-stubgen(import): crate::ir::expr::IntoExpr
40// tvm-ffi-stubgen(import): crate::ir::expr::PrimExpr
41// tvm-ffi-stubgen(import): std::borrow::Borrow
42// tvm-ffi-stubgen(import): tvm_ffi::IntoArg
43
44// tvm-ffi-stubgen(begin): import-section
45use crate::ExitOnDrop;
46use crate::ir::expr::IntoExpr;
47use crate::ir::expr::PrimExpr;
48use crate::ir::expr::Var;
49use crate::ir::support;
50use crate::sym::constraint::ConstraintContext;
51use crate::sym::int_set::IntSet;
52use std::borrow::Borrow;
53use tvm_ffi::Error;
54use tvm_ffi::IntoArg;
55use tvm_ffi::Map;
56use tvm_ffi::Object;
57use tvm_ffi::ObjectArc;
58use tvm_ffi::Result;
59use tvm_ffi::String;
60use tvm_ffi::VALUE_ERROR;
61// tvm-ffi-stubgen(end)
62
63// ---------------------------------------------------------------------------------------------
64// The analyzer
65
66/// An analyzer of integer expressions: it proves, bounds and simplifies them under the facts it
67/// knows, which [`sync_constraint_context`](Analyzer::sync_constraint_context) sets from a
68/// [`ConstraintContext`].
69///
70/// A clone shares the analyzer and its facts; [`deep_clone`](Analyzer::deep_clone) copies them.
71/// When the build includes the Z3 prover, default-strength proofs fall back to it unless
72/// [`set_z3_default_fallback`](Analyzer::set_z3_default_fallback) turns that off.
73///
74/// # Examples
75///
76/// ```
77/// use tvm_tirx::ir::prim::op::floordiv;
78/// use tvm_tirx::ir::{PrimType, PrimVar, Range, Var, UNKNOWN_LOC};
79/// use tvm_tirx::script::script;
80/// use tvm_tirx::sym::{Analyzer, ConstraintContext, RangeConstraint};
81///
82/// let x = PrimVar::new("x", PrimType::int(32), UNKNOWN_LOC);
83/// let context = ConstraintContext::new();
84/// let domain = Range::from_min_extent(0, 16, UNKNOWN_LOC)?;
85/// context.append(RangeConstraint::new(x.clone(), domain))?;
86/// let analyzer = Analyzer::new();
87/// analyzer.sync_constraint_context(&context)?;
88///
89/// assert_eq!(script(&analyzer.simplify(floordiv(&x, 16)?, 2)?)?, "0");
90///
91/// assert_eq!(script(&Analyzer::new().simplify(floordiv(&x, 16)?, 2)?)?, "x // 16");
92/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
93/// ```
94// tvm-ffi-stubgen(begin): object/sym.Analyzer
95#[allow(missing_docs)]
96#[repr(C)]
97#[derive(tvm_ffi::derive::ObjectRef, Clone)]
98pub struct Analyzer {
99 data_: ObjectArc<AnalyzerObj>,
100}
101
102/// The object behind [`Analyzer`].
103// Opaque: bytes [24, 120) of [24, 120) are not accounted for by reflected fields. Fields are read through the C ABI getters.
104#[allow(missing_docs)]
105#[repr(C)]
106#[derive(tvm_ffi::derive::Object)]
107#[object(type_key = "sym.Analyzer", final)]
108pub struct AnalyzerObj {
109 base_: Object,
110}
111// tvm-ffi-stubgen(end)
112
113impl Analyzer {
114 /// Create an analyzer that knows no facts (`sym.Analyzer`).
115 // Not `Default`: creating an analyzer allocates a stateful FFI object.
116 #[allow(clippy::new_without_default)]
117 pub fn new() -> Self {
118 support::infallible(
119 tvm_ffi::cached_global_func!("sym.Analyzer")
120 .call_tuple(())
121 .and_then(|any| any.try_into()),
122 )
123 }
124
125 /// Set whether default-strength queries try Z3 after native analysis fails
126 /// (`sym.AnalyzerSetZ3DefaultFallback`).
127 ///
128 /// Enabled by default and preserved by [`deep_clone`](Self::deep_clone). Stronger queries and
129 /// direct Z3 APIs are unaffected. This does not clear accepted premises or solver state.
130 pub fn set_z3_default_fallback(&self, enabled: bool) -> Result<()> {
131 tvm_ffi::cached_global_func!("sym.AnalyzerSetZ3DefaultFallback")
132 .call_tuple((self, enabled))?;
133 Ok(())
134 }
135
136 /// Return a copy of the analyzer and the facts it knows, which learns facts independently
137 /// (`sym.AnalyzerClone`).
138 pub fn deep_clone(&self) -> Result<Self> {
139 tvm_ffi::cached_global_func!("sym.AnalyzerClone").call_tuple((self,))?.try_into()
140 }
141
142 /// Synchronize the analyzer's facts with `context` at its current position
143 /// (`sym.AnalyzerSyncConstraintContext`).
144 ///
145 /// Later appends to the context take effect only at the next synchronization.
146 ///
147 /// # Errors
148 ///
149 /// Returns an error for a reentrant synchronization, or if `context` defines a variable twice.
150 pub fn sync_constraint_context(&self, context: impl IntoArg<ConstraintContext>) -> Result<()> {
151 tvm_ffi::cached_global_func!("sym.AnalyzerSyncConstraintContext").call_packed(&[
152 tvm_ffi::AnyView::from(self),
153 tvm_ffi::AnyView::from(context.into_arg().borrow()),
154 ])?;
155 Ok(())
156 }
157
158 /// Snapshot the accepted premises in an independently extensible context
159 /// (`sym.AnalyzerGetConstraintContext`).
160 ///
161 /// Fact and expression nodes remain shared. Appending to this context changes the analyzer only
162 /// after [`sync_constraint_context`](Self::sync_constraint_context) is called again.
163 pub fn get_constraint_context(&self) -> Result<ConstraintContext> {
164 tvm_ffi::cached_global_func!("sym.AnalyzerGetConstraintContext")
165 .call_tuple((self,))?
166 .try_into()
167 }
168
169 /// Return the constant bounds of `expr` under the known facts (`sym.AnalyzerConstIntBound`).
170 pub fn const_int_bound(&self, expr: impl IntoExpr<PrimExpr>) -> Result<ConstIntBound> {
171 tvm_ffi::cached_global_func!("sym.AnalyzerConstIntBound")
172 .call_tuple((self, expr.into_expr()?.borrow()))?
173 .try_into()
174 }
175
176 /// Return whether `var` has constant bounds recorded (`sym.AnalyzerConstIntBoundIsBound`).
177 pub fn const_int_bound_is_bound(&self, var: impl IntoArg<Var>) -> Result<bool> {
178 tvm_ffi::cached_global_func!("sym.AnalyzerConstIntBoundIsBound")
179 .call_tuple((self, var.into_arg().borrow()))?
180 .try_into()
181 }
182
183 /// Return the modular set `coeff * x + base` of `expr` (`sym.AnalyzerModularSet`).
184 pub fn modular_set(&self, expr: impl IntoExpr<PrimExpr>) -> Result<ModularSet> {
185 tvm_ffi::cached_global_func!("sym.AnalyzerModularSet")
186 .call_tuple((self, expr.into_expr()?.borrow()))?
187 .try_into()
188 }
189
190 /// Return the integer set `expr` covers, with the variables of `dom_map` over their sets
191 /// (`sym.AnalyzerIntSet`).
192 pub fn int_set(
193 &self,
194 expr: impl IntoExpr<PrimExpr>,
195 dom_map: impl Into<Option<Map<Var, IntSet>>>,
196 ) -> Result<IntSet> {
197 tvm_ffi::cached_global_func!("sym.AnalyzerIntSet")
198 .call_tuple((self, expr.into_expr()?.borrow(), dom_map.into()))?
199 .try_into()
200 }
201
202 /// Simplify `expr`, alternating the rewrite and canonical simplifiers `steps` times
203 /// (`sym.AnalyzerSimplify`).
204 pub fn simplify(&self, expr: impl IntoExpr<PrimExpr>, steps: i32) -> Result<PrimExpr> {
205 tvm_ffi::cached_global_func!("sym.AnalyzerSimplify")
206 .call_tuple((self, expr.into_expr()?.borrow(), steps))?
207 .try_into()
208 }
209
210 /// Simplify `expr` by rewrite rules (`sym.AnalyzerRewriteSimplify`).
211 pub fn rewrite_simplify(&self, expr: impl IntoExpr<PrimExpr>) -> Result<PrimExpr> {
212 tvm_ffi::cached_global_func!("sym.AnalyzerRewriteSimplify")
213 .call_tuple((self, expr.into_expr()?.borrow()))?
214 .try_into()
215 }
216
217 /// Simplify `expr` into canonical form (`sym.AnalyzerCanonicalSimplify`).
218 pub fn canonical_simplify(&self, expr: impl IntoExpr<PrimExpr>) -> Result<PrimExpr> {
219 tvm_ffi::cached_global_func!("sym.AnalyzerCanonicalSimplify")
220 .call_tuple((self, expr.into_expr()?.borrow()))?
221 .try_into()
222 }
223
224 /// Return the counters of the rewrite simplifier (`sym.AnalyzerGetRewriteSimplifyStats`).
225 pub fn rewrite_simplify_stats(&self) -> Result<RewriteSimplifierStats> {
226 tvm_ffi::cached_global_func!("sym.AnalyzerGetRewriteSimplifyStats")
227 .call_tuple((self,))?
228 .try_into()
229 }
230
231 /// Zero the counters of the rewrite simplifier (`sym.AnalyzerResetRewriteSimplifyStats`).
232 pub fn reset_rewrite_simplify_stats(&self) -> Result<()> {
233 tvm_ffi::cached_global_func!("sym.AnalyzerResetRewriteSimplifyStats")
234 .call_tuple((self,))?;
235 Ok(())
236 }
237
238 /// Cap the rewrites of one rewrite simplification at `maximum`, or 0 for no cap
239 /// (`sym.AnalyzerSetMaximumRewriteSteps`).
240 pub fn set_maximum_rewrite_steps(&self, maximum: i64) -> Result<()> {
241 tvm_ffi::cached_global_func!("sym.AnalyzerSetMaximumRewriteSteps")
242 .call_tuple((self, maximum))?;
243 Ok(())
244 }
245
246 /// Return whether `expr` is provably true (`sym.AnalyzerCanProve`).
247 pub fn can_prove(
248 &self,
249 expr: impl IntoExpr<PrimExpr>,
250 strength: ProofStrength,
251 ) -> Result<bool> {
252 tvm_ffi::cached_global_func!("sym.AnalyzerCanProve")
253 .call_tuple((self, expr.into_expr()?.borrow(), strength as i32))?
254 .try_into()
255 }
256
257 /// Return whether `lhs == rhs` is provably true (`sym.AnalyzerCanProveEqual`).
258 pub fn can_prove_equal(
259 &self,
260 lhs: impl IntoExpr<PrimExpr>,
261 rhs: impl IntoExpr<PrimExpr>,
262 ) -> Result<bool> {
263 tvm_ffi::cached_global_func!("sym.AnalyzerCanProveEqual")
264 .call_tuple((self, lhs.into_expr()?.borrow(), rhs.into_expr()?.borrow()))?
265 .try_into()
266 }
267
268 /// Return the relation of `lhs` to `rhs` that the known comparisons imply
269 /// (`sym.AnalyzerTryCompare`).
270 pub fn try_compare(
271 &self,
272 lhs: impl IntoExpr<PrimExpr>,
273 rhs: impl IntoExpr<PrimExpr>,
274 ) -> Result<CompareResult> {
275 let result: i64 = tvm_ffi::cached_global_func!("sym.AnalyzerTryCompare")
276 .call_tuple((self, lhs.into_expr()?.borrow(), rhs.into_expr()?.borrow()))?
277 .try_into()?;
278 result.try_into()
279 }
280
281 /// Return whether TIRx was built with the Z3 prover (`sym.AnalyzerIsZ3Enabled`).
282 pub fn is_z3_enabled(&self) -> Result<bool> {
283 tvm_ffi::cached_global_func!("sym.AnalyzerIsZ3Enabled").call_tuple((self,))?.try_into()
284 }
285
286 /// Return the facts the Z3 prover knows, and `expr` to prove if given, as an SMT-LIB2 script
287 /// (`sym.AnalyzerGetSMTLIB2`).
288 pub fn smtlib2(&self, expr: Option<&PrimExpr>) -> Result<String> {
289 tvm_ffi::cached_global_func!("sym.AnalyzerGetSMTLIB2")
290 .call_tuple((self, expr.cloned()))?
291 .try_into()
292 }
293
294 /// Bound each Z3 proof by `timeout_ms` milliseconds (`sym.AnalyzerSetZ3TimeoutMs`).
295 pub fn set_z3_timeout_ms(&self, timeout_ms: u32) -> Result<()> {
296 tvm_ffi::cached_global_func!("sym.AnalyzerSetZ3TimeoutMs")
297 .call_tuple((self, timeout_ms))?;
298 Ok(())
299 }
300
301 /// Bound each Z3 proof by the resource limit `rlimit` (`sym.AnalyzerSetZ3RLimit`).
302 pub fn set_z3_rlimit(&self, rlimit: u32) -> Result<()> {
303 tvm_ffi::cached_global_func!("sym.AnalyzerSetZ3RLimit").call_tuple((self, rlimit))?;
304 Ok(())
305 }
306
307 /// Return the statistics of the Z3 prover (`sym.AnalyzerGetZ3Stats`).
308 pub fn z3_stats(&self) -> Result<String> {
309 tvm_ffi::cached_global_func!("sym.AnalyzerGetZ3Stats").call_tuple((self,))?.try_into()
310 }
311}
312
313/// How hard [`Analyzer::can_prove`] tries.
314#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
315#[repr(i32)]
316pub enum ProofStrength {
317 /// The default, inexpensive analyses.
318 #[default]
319 Default = 0,
320 /// Also prove through symbolic bounds, which is more expensive.
321 SymbolicBound = 1,
322}
323
324/// The result of [`Analyzer::try_compare`].
325///
326/// The relations other than `Inconsistent` and `Unknown` say what is known of `lhs` against `rhs`.
327#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
328#[repr(i32)]
329pub enum CompareResult {
330 /// The known facts contradict each other.
331 Inconsistent = 0,
332 /// `lhs == rhs`.
333 Eq = 1,
334 /// `lhs < rhs`.
335 Lt = 2,
336 /// `lhs <= rhs`.
337 Le = 3,
338 /// `lhs > rhs`.
339 Gt = 4,
340 /// `lhs >= rhs`.
341 Ge = 5,
342 /// `lhs != rhs`.
343 Ne = 6,
344 /// Nothing is known of the relation.
345 Unknown = 7,
346}
347
348impl TryFrom<i64> for CompareResult {
349 type Error = Error;
350 fn try_from(value: i64) -> Result<Self> {
351 Ok(match value {
352 0 => Self::Inconsistent,
353 1 => Self::Eq,
354 2 => Self::Lt,
355 3 => Self::Le,
356 4 => Self::Gt,
357 5 => Self::Ge,
358 6 => Self::Ne,
359 7 => Self::Unknown,
360 _ => {
361 tvm_ffi::bail!(VALUE_ERROR, "{value} is not a sym::CompareResult");
362 }
363 })
364 }
365}
366
367/// A scope in which unsigned scalars are index types, returned by [`allow_uint_as_index`].
368///
369/// The assumption is a depth counter of the thread, so a scope stays on the thread that opened it.
370///
371/// ```compile_fail
372/// fn send<T: Send>() {}
373/// send::<tvm_tirx::sym::AllowUintAsIndexScope>();
374/// ```
375#[must_use = "the assumption ends when the scope is dropped"]
376pub struct AllowUintAsIndexScope {
377 _exit: ExitOnDrop,
378}
379
380/// Treat `uint32` and `uint64` scalars as non-wrapping index types until the returned scope is
381/// dropped (`sym.AnalyzerEnterAllowUintAsIndex`).
382///
383/// For compile-time layout proofs, not for code whose unsigned arithmetic may wrap around.
384pub fn allow_uint_as_index() -> Result<AllowUintAsIndexScope> {
385 let exit: tvm_ffi::Function = tvm_ffi::cached_global_func!("sym.AnalyzerEnterAllowUintAsIndex")
386 .call_tuple(())?
387 .try_into()?;
388 Ok(AllowUintAsIndexScope { _exit: ExitOnDrop::new(exit) })
389}
390
391// ---------------------------------------------------------------------------------------------
392// Results of the analyses
393
394/// The inclusive constant bounds `[min_value, max_value]` of an integer expression, where
395/// `i64::MAX` and `-i64::MAX` stand for unbounded ends.
396// tvm-ffi-stubgen(begin): object/sym.ConstIntBound
397#[allow(missing_docs)]
398#[repr(C)]
399#[derive(tvm_ffi::derive::ObjectRef, Clone)]
400pub struct ConstIntBound {
401 data_: ObjectArc<ConstIntBoundObj>,
402}
403
404/// The object behind [`ConstIntBound`].
405// Complete: reflected fields fill [24, 40) exactly.
406#[allow(missing_docs)]
407#[repr(C)]
408#[derive(tvm_ffi::derive::Object)]
409#[object(type_key = "sym.ConstIntBound", final, immutable)]
410pub struct ConstIntBoundObj {
411 base_: Object,
412 pub min_value: i64,
413 pub max_value: i64,
414}
415
416const _: () = {
417 assert!(::core::mem::size_of::<ConstIntBoundObj>() == 40);
418 assert!(::core::mem::align_of::<ConstIntBoundObj>() == 8);
419};
420
421#[allow(missing_docs)]
422impl ConstIntBoundObj {
423 pub(crate) fn new(min_value: i64, max_value: i64) -> Self {
424 let base_ = Object::new();
425 Self { base_, min_value, max_value }
426 }
427}
428
429#[allow(missing_docs)]
430impl ConstIntBound {
431 /// Create a `ConstIntBound` from its field values.
432 pub fn new(min_value: i64, max_value: i64) -> Self {
433 let obj = ConstIntBoundObj::new(min_value, max_value);
434 Self { data_: ObjectArc::new(obj) }
435 }
436}
437// tvm-ffi-stubgen(end)
438
439/// The congruence class `{coeff * x + base}` over the integers `x` that an integer expression lies
440/// in: a `coeff` of 0 is the single value `base`, and a `coeff` of 1 any integer.
441// tvm-ffi-stubgen(begin): object/sym.ModularSet
442#[allow(missing_docs)]
443#[repr(C)]
444#[derive(tvm_ffi::derive::ObjectRef, Clone)]
445pub struct ModularSet {
446 data_: ObjectArc<ModularSetObj>,
447}
448
449/// The object behind [`ModularSet`].
450// Complete: reflected fields fill [24, 40) exactly.
451#[allow(missing_docs)]
452#[repr(C)]
453#[derive(tvm_ffi::derive::Object)]
454#[object(type_key = "sym.ModularSet", final, immutable)]
455pub struct ModularSetObj {
456 base_: Object,
457 pub coeff: i64,
458 pub base: i64,
459}
460
461const _: () = {
462 assert!(::core::mem::size_of::<ModularSetObj>() == 40);
463 assert!(::core::mem::align_of::<ModularSetObj>() == 8);
464};
465
466#[allow(missing_docs)]
467impl ModularSetObj {
468 pub(crate) fn new(coeff: i64, base: i64) -> Self {
469 let base_ = Object::new();
470 Self { base_, coeff, base }
471 }
472}
473
474#[allow(missing_docs)]
475impl ModularSet {
476 /// Create a `ModularSet` from its field values.
477 pub fn new(coeff: i64, base: i64) -> Self {
478 let obj = ModularSetObj::new(coeff, base);
479 Self { data_: ObjectArc::new(obj) }
480 }
481}
482// tvm-ffi-stubgen(end)
483
484/// The counters of an analyzer's rewrite simplifier: the nodes it visited, the constraints it
485/// entered, the rewrites it attempted and performed, its deepest recursion and its recursive
486/// rewrites.
487// tvm-ffi-stubgen(begin): object/sym.RewriteSimplifierStats
488#[allow(missing_docs)]
489#[repr(C)]
490#[derive(tvm_ffi::derive::ObjectRef, Clone)]
491pub struct RewriteSimplifierStats {
492 data_: ObjectArc<RewriteSimplifierStatsObj>,
493}
494
495/// The object behind [`RewriteSimplifierStats`].
496// Complete: reflected fields fill [24, 72) exactly.
497#[allow(missing_docs)]
498#[repr(C)]
499#[derive(tvm_ffi::derive::Object)]
500#[object(type_key = "sym.RewriteSimplifierStats", final, immutable)]
501pub struct RewriteSimplifierStatsObj {
502 base_: Object,
503 pub nodes_visited: i64,
504 pub constraints_entered: i64,
505 pub rewrites_attempted: i64,
506 pub rewrites_performed: i64,
507 pub max_recursive_depth: i64,
508 pub num_recursive_rewrites: i64,
509}
510
511const _: () = {
512 assert!(::core::mem::size_of::<RewriteSimplifierStatsObj>() == 72);
513 assert!(::core::mem::align_of::<RewriteSimplifierStatsObj>() == 8);
514};
515
516#[allow(missing_docs)]
517impl RewriteSimplifierStatsObj {
518 pub(crate) fn new(
519 nodes_visited: i64,
520 constraints_entered: i64,
521 rewrites_attempted: i64,
522 rewrites_performed: i64,
523 max_recursive_depth: i64,
524 num_recursive_rewrites: i64,
525 ) -> Self {
526 let base_ = Object::new();
527 Self {
528 base_,
529 nodes_visited,
530 constraints_entered,
531 rewrites_attempted,
532 rewrites_performed,
533 max_recursive_depth,
534 num_recursive_rewrites,
535 }
536 }
537}
538
539#[allow(missing_docs)]
540impl RewriteSimplifierStats {
541 /// Create a `RewriteSimplifierStats` from its field values.
542 pub fn new(
543 nodes_visited: i64,
544 constraints_entered: i64,
545 rewrites_attempted: i64,
546 rewrites_performed: i64,
547 max_recursive_depth: i64,
548 num_recursive_rewrites: i64,
549 ) -> Self {
550 let obj = RewriteSimplifierStatsObj::new(
551 nodes_visited,
552 constraints_entered,
553 rewrites_attempted,
554 rewrites_performed,
555 max_recursive_depth,
556 num_recursive_rewrites,
557 );
558 Self { data_: ObjectArc::new(obj) }
559 }
560}
561// tvm-ffi-stubgen(end)