tvm
Loading...
Searching...
No Matches
analyzer.h
Go to the documentation of this file.
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
24#ifndef TVM_SYM_ANALYZER_H_
25#define TVM_SYM_ANALYZER_H_
26
27#include <tvm/ffi/cast.h>
28#include <tvm/ffi/object.h>
29#include <tvm/ffi/reflection/registry.h>
30#include <tvm/ffi/string.h>
31#include <tvm/ir/expr.h>
32#include <tvm/ir/with_context.h>
33#include <tvm/sym/constraint.h>
34#include <tvm/sym/int_set.h>
35
36#include <functional>
37#include <limits>
38#include <memory>
39#include <unordered_map>
40#include <utility>
41#include <vector>
42
43namespace tvm {
45namespace sym {
46//-------------------------------------------------------
47// Base integer analysis API.
48//
49// We have multiple type of analyzers to do relaxed
50// integer set analysis(bound analysis, modulo) and
51// equivalence checking and simplification.
52//
53// Importantly, each analyzer may need result from
54// another analyzer.
55//-------------------------------------------------------
56
57// Forward declare the analyzer object and its reference handle.
58class AnalyzerObj;
59class Analyzer;
60enum class CompareResult : int;
61namespace detail {
62class TempConstraintScope;
63} // namespace detail
64
72
80enum class ProofStrength : int {
82 kDefault = 0,
87};
88
94class ConstIntBoundObj : public ffi::Object {
95 public:
97 int64_t min_value;
99 int64_t max_value;
100
102 static void RegisterReflection() {
103 namespace refl = tvm::ffi::reflection;
104 refl::ObjectDef<ConstIntBoundObj>()
105 .def_ro("min_value", &ConstIntBoundObj::min_value)
106 .def_ro("max_value", &ConstIntBoundObj::max_value);
107 }
108
110 static const constexpr int64_t kPosInf = std::numeric_limits<int64_t>::max();
115 static const constexpr int64_t kNegInf = -kPosInf;
116
118 static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind = kTVMFFISEqHashKindTreeNode;
119 TVM_FFI_DECLARE_OBJECT_INFO_FINAL("sym.ConstIntBound", ConstIntBoundObj, ffi::Object);
120};
121
126class ConstIntBound : public ffi::ObjectRef {
127 public:
129 TVM_TIRX_DLL ConstIntBound(int64_t min_value, int64_t max_value);
130
132 static const constexpr int64_t kPosInf = ConstIntBoundObj::kPosInf;
134 static const constexpr int64_t kNegInf = ConstIntBoundObj::kNegInf;
136};
137
142 public:
145 std::unordered_map<PrimExpr, ConstIntBound, ffi::ObjectPtrHash, ffi::ObjectPtrEqual>;
152
161
167 TVM_TIRX_DLL bool IsBound(const Var& var) const;
168
169 private:
170 friend class AnalyzerObj;
171 // Clear context-derived facts before replay; retain query settings and diagnostics.
172 void Reset();
173 // Record a value binding after AnalyzerObj validates and orders the premises.
174 void IngestBinding(const Var& var, const PrimExpr& expr);
175 // Record a half-open variable range from the accepted premise prefix.
176 void IngestBinding(const Var& var, const Range& range);
177 // Consume a predicate prepared against the preceding premise prefix.
178 void IngestPredicate(const PrimExpr& constraint);
179 // Borrow the owning analyzer for cross-backend queries.
180 explicit ConstIntBoundAnalyzer(AnalyzerObj* parent);
181 // Exported for destruction through the inline Analyzer object allocator.
183 // Copy durable facts/settings into this backend without sharing mutable query state.
184 void CopyFrom(const ConstIntBoundAnalyzer& other);
185 struct Entry;
186 class Impl;
187 // Owned backend state; its definition stays inside the compiler library.
188 std::unique_ptr<Impl> impl_;
189};
190
198class ModularSetObj : public ffi::Object {
199 public:
201 int64_t coeff;
203 int64_t base;
204
206 static void RegisterReflection() {
207 namespace refl = tvm::ffi::reflection;
208 refl::ObjectDef<ModularSetObj>()
209 .def_ro("coeff", &ModularSetObj::coeff)
210 .def_ro("base", &ModularSetObj::base);
211 }
212
214 static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind = kTVMFFISEqHashKindTreeNode;
215 TVM_FFI_DECLARE_OBJECT_INFO_FINAL("sym.ModularSet", ModularSetObj, ffi::Object);
216};
217
222class ModularSet : public ffi::ObjectRef {
223 public:
225 TVM_TIRX_DLL ModularSet(int64_t coeff, int64_t base);
226
228};
229
234 public:
241
242 private:
243 friend class AnalyzerObj;
244 // Clear context-derived facts before replay; retain query settings and diagnostics.
245 void Reset();
246 // Record a value binding after AnalyzerObj validates and orders the premises.
247 void IngestBinding(const Var& var, const PrimExpr& expr);
248 // Consume a predicate prepared against the preceding premise prefix.
249 void IngestPredicate(const PrimExpr& constraint);
250 // Borrow the owning analyzer for cross-backend queries.
251 explicit ModularSetAnalyzer(AnalyzerObj* parent);
252 // Exported for destruction through the inline Analyzer object allocator.
254 // Copy durable facts/settings into this backend without sharing mutable query state.
255 void CopyFrom(const ModularSetAnalyzer& other);
256 struct Entry;
257 class Impl;
258 // Owned backend state; its definition stays inside the compiler library.
259 std::unique_ptr<Impl> impl_;
260};
261
266 public:
273
281
286 TVM_TIRX_DLL ffi::ObjectRef GetStatsCounters() const;
287
290
309
310 private:
311 friend class AnalyzerObj;
312 // Clear context-derived facts before replay; retain query settings and diagnostics.
313 void Reset();
314 // Keep the original relation alongside the simplified substitution.
315 void IngestBinding(const Var& var, const PrimExpr& value, const PrimExpr& original);
316 // Record a range relation after AnalyzerObj validates and orders the premises.
317 void IngestBinding(const Var& var, const Range& range);
318 // Consume a predicate prepared against the preceding premise prefix.
319 void IngestPredicate(const PrimExpr& constraint);
321 // Borrow the owning analyzer for cross-backend queries.
322 explicit RewriteSimplifier(AnalyzerObj* parent);
323 // Exported for destruction through the inline Analyzer object allocator.
325 // Copy durable facts/settings into this backend without sharing mutable query state.
326 void CopyFrom(const RewriteSimplifier& other);
327 class Impl;
328 // Owned backend state; its definition stays inside the compiler library.
329 ffi::ObjectPtr<Impl> impl_;
330};
331
336 public:
343
344 private:
345 friend class AnalyzerObj;
346 // Clear context-derived facts before replay; retain query settings and diagnostics.
347 void Reset();
348 // Record a value binding after AnalyzerObj validates and orders the premises.
349 void IngestBinding(const Var& var, const PrimExpr& expr);
350 // Borrow the owning analyzer for cross-backend queries.
351 explicit CanonicalSimplifier(AnalyzerObj* parent);
352 // Exported for destruction through the inline Analyzer object allocator.
354 // Copy durable facts/settings into this backend without sharing mutable query state.
355 void CopyFrom(const CanonicalSimplifier& other);
356 class Impl;
357 // Owned backend state; its definition stays inside the compiler library.
358 ffi::ObjectPtr<Impl> impl_;
359};
360
367enum class CompareResult : int {
369 kInconsistent = 0,
371 kEQ = 1,
373 kLT = 2,
375 kLE = 3,
377 kGT = 4,
379 kGE = 5,
381 kNE = 6,
383 kUnknown = 7
384};
385
393 return CompareResult(static_cast<int>(lhs) & static_cast<int>(rhs));
394}
402 return CompareResult(static_cast<int>(lhs) | static_cast<int>(rhs));
403}
404
409 public:
418 TVM_TIRX_DLL IntSet operator()(const PrimExpr& expr, const ffi::Map<Var, IntSet>& dom_map);
419
428
429 private:
430 friend class AnalyzerObj;
431 // Clear context-derived facts before replay; retain query settings and diagnostics.
432 void Reset();
433 // Record a value binding after AnalyzerObj validates and orders the premises.
434 void IngestBinding(const Var& var, const PrimExpr& expr);
435 // Record a half-open variable range from the accepted premise prefix.
436 void IngestBinding(const Var& var, const Range& range);
437 // Consume a predicate prepared against the preceding premise prefix.
438 void IngestPredicate(const PrimExpr& constraint);
439 // Borrow the owning analyzer for cross-backend queries.
440 explicit IntSetAnalyzer(AnalyzerObj* parent);
441 // Exported for destruction through the inline Analyzer object allocator.
443 // Copy durable facts/settings into this backend without sharing mutable query state.
444 void CopyFrom(const IntSetAnalyzer& other);
445 class Impl;
446 // Owned backend state; its definition stays inside the compiler library.
447 Impl* impl_;
448};
449
456class Z3Prover {
457 public:
464
471 TVM_TIRX_DLL bool CanProve(const PrimExpr& expr);
472
479 TVM_TIRX_DLL ffi::String GetSMTLIB2(const ffi::Optional<PrimExpr> expr);
480
486 TVM_TIRX_DLL ffi::String GetStats();
487
493 TVM_TIRX_DLL void SetTimeoutMs(unsigned timeout_ms);
494
500 TVM_TIRX_DLL void SetRLimit(unsigned rlimit);
501
509 TVM_TIRX_DLL ffi::String GetModel(const PrimExpr& expr);
510
524 TVM_TIRX_DLL int64_t CountSatisfyingValues(const Var& var, int64_t max_count = 2048,
525 int64_t min_consecutive = 1);
526
527 private:
528 friend class AnalyzerObj;
529 // Clear facts, translations, and solver state; retain resource limits.
530 void Reset();
531 // Record a value binding after AnalyzerObj validates and orders the premises.
532 void IngestBinding(const Var& var, const PrimExpr& expr);
533 // Record a half-open variable range from the accepted premise prefix.
534 void IngestBinding(const Var& var, const Range& range);
535 // Consume a predicate prepared against the preceding premise prefix.
536 void IngestPredicate(const PrimExpr& constraint);
537 friend class Analyzer;
538 // Borrow the owning analyzer for cross-backend queries.
539 explicit Z3Prover(AnalyzerObj* parent);
540 // Exported for destruction through the inline Analyzer object allocator.
542 // Copy durable facts/settings into this backend without sharing mutable query state.
543 void CopyFrom(const Z3Prover& other);
544 class Impl;
545 std::unique_ptr<Impl> impl_;
546};
547
556class TVM_TIRX_DLL AnalyzerObj : public ffi::Object {
557 public:
580 void SetZ3DefaultFallback(bool enabled);
619 bool CanProveGreaterEqual(const PrimExpr& expr, int64_t lower_bound);
631 bool CanProveLess(const PrimExpr& expr, int64_t upper_bound);
641 bool CanProveEqual(const PrimExpr& lhs, const PrimExpr& rhs);
674 bool CanProve(const PrimExpr& cond, ProofStrength strength = ProofStrength::kDefault);
675
688 PrimExpr Simplify(const PrimExpr& expr, int steps = 2);
689
702
712 static constexpr bool _type_mutable = true;
713 TVM_FFI_DECLARE_OBJECT_INFO_FINAL("sym.Analyzer", AnalyzerObj, ffi::Object);
714
715 private:
716 friend class detail::TempConstraintScope;
717 // Policy for DEFAULT-strength queries; explicit stronger queries can still use Z3.
718 bool z3_default_fallback_{true};
719 // Record a value binding after AnalyzerObj validates and orders the premises.
720 void IngestBinding(const Var& var, const PrimExpr& expr);
721 // Record a half-open variable range from the accepted premise prefix.
722 void IngestBinding(const Var& var, const Range& range);
723 // Dispatch a supported pure premise to the participating backends.
724 void IngestConstraint(const Constraint& constraint);
725 // Normalize and derive predicate facts using only the already valid prefix.
726 std::vector<PrimExpr> PreparePredicate(const PrimExpr& condition);
727 // Accepted premise prefix, advanced after each fact during synchronization.
728 ConstraintContext last_snapshot_;
729 // Query-local premises, managed in LIFO order by TempConstraintScope.
730 std::vector<Constraint> temp_constraints_;
731 // Prevent reentry and reuse after an incomplete synchronization.
732 bool synchronizing_{false};
733 // Nested query count; synchronization requires zero active queries.
734 int active_queries_{0};
735};
736
750class Analyzer : public ffi::ObjectRef {
751 public:
753 Analyzer() : Analyzer(ffi::make_object<AnalyzerObj>()) {}
755 explicit Analyzer(ffi::ObjectPtr<AnalyzerObj> n) : ffi::ObjectRef(std::move(n)) {
756 TVM_FFI_ICHECK(this->get() != nullptr);
757 }
759};
760
771 public:
776 TVM_TIRX_DLL static bool Enabled();
777
778 private:
779 friend class With<AllowUIntAsIndex>;
780 // Called across the DLL boundary by the inline With<> constructor.
781 TVM_TIRX_DLL void EnterWithScope();
782 // Called across the DLL boundary by the inline With<> destructor.
783 TVM_TIRX_DLL void ExitWithScope();
784 // Number of active scopes in this thread.
785 static thread_local int depth_;
786};
787
788} // namespace sym
789} // namespace tvm
790#endif // TVM_SYM_ANALYZER_H_
Base expr nodes in TVM.
#define TVM_TIRX_DLL
Definition base.h:55
Typed reference/view over any Expr whose ExprObj::ty is PrimType.
Definition expr.h:187
Range container
Definition expr.h:883
Managed reference to VarObj.
Definition expr.h:571
RAII wrapper function to enter and exit a context object similar to python's with syntax.
Definition with_context.h:58
Scoped no-overflow assumption for unsigned index arithmetic.
Definition analyzer.h:770
static TVM_TIRX_DLL bool Enabled()
Check the current thread's unsigned-index assumption.
Coordinated symbolic analyses over an explicitly synchronized premise environment.
Definition analyzer.h:556
RewriteSimplifier rewrite_simplify
sub-analyzer rewrite simplify
Definition analyzer.h:563
bool CanProve(const PrimExpr &cond, ProofStrength strength=ProofStrength::kDefault)
Attempt to prove a condition under the current premises.
Analyzer Clone() const
Copy accepted facts and query settings into an independent analyzer.
bool CanProveGreaterEqual(const PrimExpr &expr, int64_t lower_bound)
Attempt to prove expr >= lower_bound.
IntSetAnalyzer int_set
sub-analyzer: int set
Definition analyzer.h:567
void SetZ3DefaultFallback(bool enabled)
Set whether DEFAULT-strength queries try Z3 after native analysis fails.
Z3Prover z3_prover
sub-analyzer using Z3
Definition analyzer.h:569
CanonicalSimplifier canonical_simplify
sub-analyzer canonical simplify
Definition analyzer.h:565
ConstraintContext GetConstraintContext() const
Snapshot the accepted premise environment.
bool CanProveEqual(const PrimExpr &lhs, const PrimExpr &rhs)
Attempt to prove lhs == rhs.
PrimExpr Simplify(const PrimExpr &expr, int steps=2)
Simplify expr.
ConstIntBoundAnalyzer const_int_bound
sub-analyzer: const integer bound
Definition analyzer.h:559
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("sym.Analyzer", AnalyzerObj, ffi::Object)
AnalyzerObj()
Construct an analyzer with no accepted premises and default query settings.
bool CanProveLessEqualThanSymbolicShapeValue(const PrimExpr &lhs, const PrimExpr &shape)
Attempt to prove lhs <= a possibly symbolic shape.
void SyncConstraintContext(const ConstraintContext &context)
Synchronize all derived facts to the supplied premise environment.
bool CanProveLess(const PrimExpr &expr, int64_t upper_bound)
Attempt to prove expr < upper_bound.
ModularSetAnalyzer modular_set
sub-analyzer: modular set
Definition analyzer.h:561
Managed reference to AnalyzerObj.
Definition analyzer.h:750
Analyzer()
Construct a fresh analyzer.
Definition analyzer.h:753
Analyzer(ffi::ObjectPtr< AnalyzerObj > n)
Adopt a reference to a non-null analyzer object.
Definition analyzer.h:755
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(Analyzer, ffi::ObjectRef, AnalyzerObj)
Canonical-form based simplifier.
Definition analyzer.h:335
TVM_TIRX_DLL PrimExpr operator()(const PrimExpr &expr)
Simplify an expression under the current premises.
Analyzer to get constant integer bound over expression.
Definition analyzer.h:141
TVM_TIRX_DLL bool IsBound(const Var &var) const
Check whether a binding or recognized predicate supplies bounds for a variable.
TVM_TIRX_DLL ConstIntBound operator()(const PrimExpr &expr) const
Compute conservative constant bounds under the current premises.
TVM_TIRX_DLL ConstIntBound operator()(const PrimExpr &expr, BoundMapType *bound)
Compute bounds and optionally collect intermediate query results.
std::unordered_map< PrimExpr, ConstIntBound, ffi::ObjectPtrHash, ffi::ObjectPtrEqual > BoundMapType
Query results keyed by expression object identity.
Definition analyzer.h:145
Inclusive constant integer bounds, representing [min_value, max_value].
Definition analyzer.h:94
static const constexpr int64_t kPosInf
Number to represent +inf.
Definition analyzer.h:110
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("sym.ConstIntBound", ConstIntBoundObj, ffi::Object)
static void RegisterReflection()
Register the fields exposed through FFI reflection.
Definition analyzer.h:102
int64_t min_value
Inclusive lower endpoint, or kNegInf when unbounded.
Definition analyzer.h:97
int64_t max_value
Inclusive upper endpoint, or kPosInf when unbounded.
Definition analyzer.h:99
static const constexpr int64_t kNegInf
Number to represent -inf.
Definition analyzer.h:115
static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind
Compare and hash these value objects structurally.
Definition analyzer.h:118
Managed reference to ConstIntBoundObj.
Definition analyzer.h:126
TVM_TIRX_DLL ConstIntBound(int64_t min_value, int64_t max_value)
Construct inclusive bounds; endpoints may use the infinity sentinels.
static const constexpr int64_t kNegInf
Sentinel for an unbounded lower endpoint.
Definition analyzer.h:134
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(ConstIntBound, ffi::ObjectRef, ConstIntBoundObj)
static const constexpr int64_t kPosInf
Sentinel for an unbounded upper endpoint.
Definition analyzer.h:132
Managed reference to ConstraintContextObj. Copies share the same context.
Definition constraint.h:306
A binding, range, or predicate, without inference or normalization.
Definition constraint.h:49
Integer set analyzer.
Definition analyzer.h:408
TVM_TIRX_DLL IntSet operator()(const PrimExpr &expr, const ffi::Map< Var, IntSet > &dom_map)
Find a symbolic integer set that contains all possible values of expr given the supplied variable dom...
TVM_TIRX_DLL IntSet operator()(const PrimExpr &expr)
Find a symbolic integer set that contains all possible values of expr using current bindings,...
Managed reference to IntSetObj.
Definition int_set.h:63
Analyzer to get modular information over expression.
Definition analyzer.h:233
TVM_TIRX_DLL ModularSet operator()(const PrimExpr &expr)
Compute conservative congruence information under the current premises.
Integer congruence class {coeff * x + base | x in Z}.
Definition analyzer.h:198
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("sym.ModularSet", ModularSetObj, ffi::Object)
int64_t base
Constant offset of the congruence class.
Definition analyzer.h:203
int64_t coeff
Coefficient of the arbitrary integer multiplier.
Definition analyzer.h:201
static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind
Compare and hash these value objects structurally.
Definition analyzer.h:214
static void RegisterReflection()
Register the fields exposed through FFI reflection.
Definition analyzer.h:206
Managed reference to ModularSetObj.
Definition analyzer.h:222
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(ModularSet, ffi::ObjectRef, ModularSetObj)
TVM_TIRX_DLL ModularSet(int64_t coeff, int64_t base)
Store coeff and base as supplied, without normalization.
Rewrite-rule based simplifier.
Definition analyzer.h:265
TVM_TIRX_DLL PrimExpr operator()(const PrimExpr &expr)
Simplify an expression under the current premises.
TVM_TIRX_DLL CompareResult TryCompare(const PrimExpr &lhs, const PrimExpr &rhs)
Compare signed integer expressions using active premises and constant offsets.
TVM_TIRX_DLL void SetMaximumRewriteSteps(int64_t maximum)
Set the maximum allowed cumulative number of successful rewrites.
TVM_TIRX_DLL void ResetStatsCounters()
Clear cumulative rewrite counters without changing facts or the rewrite limit.
TVM_TIRX_DLL ffi::ObjectRef GetStatsCounters() const
Read cumulative rewrite statistics.
Optional Z3-backed prover over the analyzer's accepted premises.
Definition analyzer.h:456
TVM_TIRX_DLL ffi::String GetModel(const PrimExpr &expr)
Get a counterexample model for a boolean expression.
TVM_TIRX_DLL bool IsEnabled() const
Whether the Z3 backend is compiled into this build (TVM_TIRX_USE_Z3=ON).
TVM_TIRX_DLL void SetTimeoutMs(unsigned timeout_ms)
Set timeout in milliseconds for Z3 prover.
TVM_TIRX_DLL bool CanProve(const PrimExpr &expr)
Attempt to prove that expr holds under the current premises.
TVM_TIRX_DLL void SetRLimit(unsigned rlimit)
Set resource limitation for Z3 prover.
TVM_TIRX_DLL ffi::String GetSMTLIB2(const ffi::Optional< PrimExpr > expr)
Get the SMTLIB2 representation of the current context.
TVM_TIRX_DLL ffi::String GetStats()
Get statistics about Z3 prover.
TVM_TIRX_DLL int64_t CountSatisfyingValues(const Var &var, int64_t max_count=2048, int64_t min_consecutive=1)
Count the number of integer values that satisfy the current constraints.
Data-only symbolic premises collected during traversal.
Integer set.
@ kUnknown
Definition int_set.h:47
CompareResult
Possible orderings of two expressions, represented as a bit set.
Definition analyzer.h:367
@ kLE
Less than or equal.
@ kGT
Strictly greater.
@ kGE
Greater than or equal.
@ kLT
Strictly less.
@ kInconsistent
No ordering is possible under the known facts.
DivMode
Integer division semantics used by symbolic analysis.
Definition analyzer.h:66
@ kFloorDiv
Floor division.
Definition analyzer.h:70
@ kTruncDiv
Truncated division.
Definition analyzer.h:68
constexpr CompareResult operator|(CompareResult lhs, CompareResult rhs)
Unite the possible orderings.
Definition analyzer.h:401
ProofStrength
The strength used for top-level condition proofs.
Definition analyzer.h:80
@ kSymbolicBound
Prove using symbolic bound analysis.
@ kDefault
Default analysis followed by the optional Z3 fallback.
constexpr CompareResult operator&(CompareResult lhs, CompareResult rhs)
Intersect the possible orderings.
Definition analyzer.h:392
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition analysis.h:41
RAII wrapper function to enter and exit a context object similar to python's with syntax.