Skip to main content

tvm_tirx/sym/
int_set.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//! Integer sets. An [`IntSet`], such as the interval [`IntervalSet`], bounds the values an
21//! expression takes; [`deduce_bound`] solves a condition for a variable, and the
22//! `estimate_region_*` functions bound the region a set of accesses covers.
23
24// tvm-ffi-stubgen(file): mod(missing_docs = allow)
25// The sets are hand-written: C++ constructs them, so they have no field-wise allocator.
26// tvm-ffi-stubgen(object): sym.IntSet(ty_map = crate::sym::int_set::IntSet)
27// tvm-ffi-stubgen(object): sym.IntervalSet(ty_map = crate::sym::int_set::IntervalSet)
28// tvm-ffi-stubgen(import): std::ops::Deref
29// tvm-ffi-stubgen(import): tvm_ffi::Object
30// tvm-ffi-stubgen(import): tvm_ffi::ObjectArc
31// Names the hand-written wrappers use: the import section keeps them even when no generated block
32// does.
33// tvm-ffi-stubgen(import): tvm_ffi::Array
34// tvm-ffi-stubgen(import): tvm_ffi::Map
35// tvm-ffi-stubgen(import): tvm_ffi::Result
36// tvm-ffi-stubgen(import): crate::ir::expr::Range
37// tvm-ffi-stubgen(import): crate::ir::expr::Var
38// tvm-ffi-stubgen(import): crate::sym::analyzer::Analyzer
39// tvm-ffi-stubgen(import): crate::ir::support
40// tvm-ffi-stubgen(import): crate::ir::expr::IntoExpr
41// tvm-ffi-stubgen(import): crate::ir::expr::PrimExpr
42// tvm-ffi-stubgen(import): std::borrow::Borrow
43// tvm-ffi-stubgen(import): tvm_ffi::IntoArg
44// tvm-ffi-stubgen(begin): import-section
45use crate::ir::expr::IntoExpr;
46use crate::ir::expr::PrimExpr;
47use crate::ir::expr::Range;
48use crate::ir::expr::Var;
49use crate::ir::support;
50use crate::sym::analyzer::Analyzer;
51use std::borrow::Borrow;
52use std::ops::Deref;
53use tvm_ffi::Array;
54use tvm_ffi::IntoArg;
55use tvm_ffi::Map;
56use tvm_ffi::Object;
57use tvm_ffi::ObjectArc;
58use tvm_ffi::Result;
59// tvm-ffi-stubgen(end)
60
61/// The base of every set of integers, one dimension each, that bounds the values an expression
62/// takes; [`Analyzer::int_set`] computes one.
63///
64/// # Examples
65///
66/// ```
67/// use tvm_tirx::ir::prim::op::PrimOps;
68/// use tvm_tirx::ir::{PrimType, PrimVar, Var, UNKNOWN_LOC};
69/// use tvm_tirx::script::script;
70/// use tvm_tirx::sym::{self, Analyzer, IntSet, IntervalSet};
71/// use tvm_tirx::tvm_ffi::Map;
72///
73/// let i = PrimVar::new("i", PrimType::int(32), UNKNOWN_LOC);
74/// let dom_map = Map::from_iter([(Var::from(&i), IntSet::from(IntervalSet::new(0, 15)))]);
75/// let set = Analyzer::new().int_set(&i * 2 + 1, dom_map)?;
76/// assert_eq!(script(&set)?, "sym.IntervalSet(min_value=1, max_value=31)");
77///
78/// let none = Map::<Var, IntSet>::new();
79/// let bound = sym::deduce_bound(&i, (&i * 4 + 3).less(64), &none, &none)?;
80/// assert_eq!(script(&bound)?, "sym.IntervalSet(min_value=neg_inf, max_value=15)");
81/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
82/// ```
83#[allow(missing_docs)]
84#[repr(C)]
85#[derive(tvm_ffi::derive::ObjectRef, Clone)]
86pub struct IntSet {
87    data_: ObjectArc<IntSetObj>,
88}
89
90/// The object behind [`IntSet`].
91///
92/// Complete: reflected fields fill [24, 24) exactly.
93#[allow(missing_docs)]
94#[repr(C)]
95#[derive(tvm_ffi::derive::Object)]
96#[object(type_key = "sym.IntSet", immutable, rs_parent)]
97pub struct IntSetObj {
98    base_: Object,
99}
100
101const _: () = {
102    assert!(::core::mem::size_of::<IntSetObj>() == 24);
103    assert!(::core::mem::align_of::<IntSetObj>() == 8);
104};
105
106impl IntSet {
107    /// Return whether the set is empty (`sym.IntSetIsNothing`).
108    pub fn is_nothing(&self) -> Result<bool> {
109        tvm_ffi::cached_global_func!("sym.IntSetIsNothing").call_tuple((self,))?.try_into()
110    }
111
112    /// Return whether the set holds every integer (`sym.IntSetIsEverything`).
113    pub fn is_everything(&self) -> Result<bool> {
114        tvm_ffi::cached_global_func!("sym.IntSetIsEverything").call_tuple((self,))?.try_into()
115    }
116
117    /// Return the set of the lanes of the vector `vec`, or of its value for a scalar
118    /// (`sym.IntSetVector`).
119    pub fn vector(vec: impl IntoExpr<PrimExpr>) -> Result<Self> {
120        tvm_ffi::cached_global_func!("sym.IntSetVector")
121            .call_tuple((vec.into_expr()?.borrow(),))?
122            .try_into()
123    }
124
125    /// Return the set that holds only `point` (`sym.IntSetSinglePoint`).
126    pub fn single_point(point: impl IntoExpr<PrimExpr>) -> Result<Self> {
127        tvm_ffi::cached_global_func!("sym.IntSetSinglePoint")
128            .call_tuple((point.into_expr()?.borrow(),))?
129            .try_into()
130    }
131}
132
133/// The interval `[min_value, max_value]` of integers, whose bounds are symbolic expressions and
134/// may be [`neg_inf`] or [`pos_inf`].
135#[allow(missing_docs)]
136#[repr(C)]
137#[derive(tvm_ffi::derive::ObjectRef, Clone)]
138pub struct IntervalSet {
139    data_: ObjectArc<IntervalSetObj>,
140}
141
142/// The object behind [`IntervalSet`].
143///
144/// Complete: reflected fields fill [24, 40) exactly.
145#[allow(missing_docs)]
146#[repr(C)]
147#[derive(tvm_ffi::derive::Object)]
148#[object(type_key = "sym.IntervalSet", final, immutable)]
149pub struct IntervalSetObj {
150    base_: IntSetObj,
151    pub min_value: PrimExpr,
152    pub max_value: PrimExpr,
153}
154
155const _: () = {
156    assert!(::core::mem::size_of::<IntervalSetObj>() == 40);
157    assert!(::core::mem::align_of::<IntervalSetObj>() == 8);
158};
159
160impl Deref for IntervalSetObj {
161    type Target = IntSetObj;
162    fn deref(&self) -> &IntSetObj {
163        &self.base_
164    }
165}
166
167tvm_ffi::impl_object_ref_upcast!(IntervalSet => IntSet);
168
169impl IntervalSet {
170    /// Create the interval `[min_value, max_value]`, whose bounds may be [`neg_inf`] and
171    /// [`pos_inf`] (`sym.IntervalSet`).
172    pub fn new(min_value: impl IntoArg<PrimExpr>, max_value: impl IntoArg<PrimExpr>) -> Self {
173        support::infallible(
174            tvm_ffi::cached_global_func!("sym.IntervalSet")
175                .call_tuple((min_value.into_arg().borrow(), max_value.into_arg().borrow()))
176                .and_then(|any| any.try_into()),
177        )
178    }
179}
180
181/// Return the region a set of affine accesses covers at least, given the domains of their variables
182/// and a predicate, or `None` when the accesses are not affine (`sym.EstimateRegionLowerBound`).
183///
184/// Without an `analyzer`, a fresh one proves.
185pub fn estimate_region_lower_bound(
186    region: impl IntoIterator<Item = impl IntoArg<Range>>,
187    var_dom: impl Into<Map<Var, Range>>,
188    predicate: impl IntoExpr<PrimExpr>,
189    analyzer: Option<&Analyzer>,
190) -> Result<Option<Array<IntSet>>> {
191    let region = region.into_iter().map(IntoArg::into_owned).collect::<Array<Range>>();
192    tvm_ffi::cached_global_func!("sym.EstimateRegionLowerBound")
193        .call_tuple((&region, &var_dom.into(), predicate.into_expr()?.borrow(), analyzer.cloned()))?
194        .try_into()
195}
196
197/// Return the exact region a set of affine accesses covers, given the domains of their variables
198/// and a predicate, or `None` when the accesses are not affine (`sym.EstimateRegionStrictBound`).
199pub fn estimate_region_strict_bound(
200    region: impl IntoIterator<Item = impl IntoArg<Range>>,
201    var_dom: impl Into<Map<Var, Range>>,
202    predicate: impl IntoExpr<PrimExpr>,
203    analyzer: Option<&Analyzer>,
204) -> Result<Option<Array<IntSet>>> {
205    let region = region.into_iter().map(IntoArg::into_owned).collect::<Array<Range>>();
206    tvm_ffi::cached_global_func!("sym.EstimateRegionStrictBound")
207        .call_tuple((&region, &var_dom.into(), predicate.into_expr()?.borrow(), analyzer.cloned()))?
208        .try_into()
209}
210
211/// Return a region that holds what a set of accesses covers, given the domains of their variables
212/// and a predicate, also when the accesses are not affine (`sym.EstimateRegionUpperBound`).
213pub fn estimate_region_upper_bound(
214    region: impl IntoIterator<Item = impl IntoArg<Range>>,
215    var_dom: impl Into<Map<Var, Range>>,
216    predicate: impl IntoExpr<PrimExpr>,
217    analyzer: Option<&Analyzer>,
218) -> Result<Array<IntSet>> {
219    let region = region.into_iter().map(IntoArg::into_owned).collect::<Array<Range>>();
220    tvm_ffi::cached_global_func!("sym.EstimateRegionUpperBound")
221        .call_tuple((&region, &var_dom.into(), predicate.into_expr()?.borrow(), analyzer.cloned()))?
222        .try_into()
223}
224
225/// Return the symbolic positive infinity (`sym.PosInf`).
226pub fn pos_inf() -> Result<PrimExpr> {
227    tvm_ffi::cached_global_func!("sym.PosInf").call_tuple(())?.try_into()
228}
229
230/// Return the symbolic negative infinity (`sym.NegInf`).
231pub fn neg_inf() -> Result<PrimExpr> {
232    tvm_ffi::cached_global_func!("sym.NegInf").call_tuple(())?.try_into()
233}
234
235/// Return a subset of the union of `sets`, which may drop some of their segments
236/// (`sym.UnionLowerBound`).
237pub fn union_lower_bound(sets: impl IntoIterator<Item = impl IntoArg<IntSet>>) -> Result<IntSet> {
238    let sets = sets.into_iter().map(IntoArg::into_owned).collect::<Array<IntSet>>();
239    tvm_ffi::cached_global_func!("sym.UnionLowerBound").call_tuple((&sets,))?.try_into()
240}
241
242/// Return the values of `var` for which `cond` holds, with the variables of `hint_map` over their
243/// sets and those of `relax_map` relaxed to theirs, or the empty set when no bound can be deduced
244/// (`sym.DeduceBound`).
245pub fn deduce_bound(
246    var: impl IntoExpr<PrimExpr>,
247    cond: impl IntoExpr<PrimExpr>,
248    hint_map: impl Into<Map<Var, IntSet>>,
249    relax_map: impl Into<Map<Var, IntSet>>,
250) -> Result<IntSet> {
251    tvm_ffi::cached_global_func!("sym.DeduceBound")
252        .call_tuple((
253            var.into_expr()?.borrow(),
254            cond.into_expr()?.borrow(),
255            &hint_map.into(),
256            &relax_map.into(),
257        ))?
258        .try_into()
259}