Skip to main content

tvm_tirx/ir/
expr.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//! Expressions. Every expression is an [`Expr`] that carries its type; [`PrimExpr`] and
21//! [`IntExpr`] are expressions known to have a primitive or scalar integer type, the operands of
22//! arithmetic (in [`prim`](super::prim)).
23
24// tvm-ffi-stubgen(file): mod(missing_docs = allow)
25// `custom_new` reserves `new` for a hand-written constructor (checks, defaults, implicit
26// conversions, a derived type); the generated `from_fields` allocates the fields as given,
27// inherited fields first.
28// tvm-ffi-stubgen(object): ir.GlobalVar(custom_new)
29// tvm-ffi-stubgen(object): ir.Tuple(custom_new)
30// tvm-ffi-stubgen(object): ir.TensorLoad(custom_new, upcast = PrimExpr)
31// tvm-ffi-stubgen(object): ir.StringImm(custom_new)
32// tvm-ffi-stubgen(object): ir.Call(custom_new)
33// tvm-ffi-stubgen(object): ir.LambdaExpr(custom_new)
34// tvm-ffi-stubgen(object): ir.Range(custom_new)
35// tvm-ffi-stubgen(object): ir.TupleGetItem(custom_new)
36// tvm-ffi-stubgen(object): ir.FloatImm(custom_new, upcast = PrimExpr)
37// tvm-ffi-stubgen(object): ir.IntImm(custom_new, upcast = PrimExpr)
38// tvm-ffi-stubgen(object): ir.GenericConst(custom_new)
39// tvm-ffi-stubgen(object): ir.DataTypeImm(custom_new)
40// tvm-ffi-stubgen(object): ir.TensorRegion(custom_new)
41// `no_new` generates no allocator for the abstract bases: a value is one of its subtypes.
42// tvm-ffi-stubgen(object): ir.Expr(no_new)
43// tvm-ffi-stubgen(object): ir.StagingExpr(no_new)
44// tvm-ffi-stubgen(object): ir.OpaqueExpr(no_new)
45// tvm-ffi-stubgen(object): ir.Constant(no_new)
46// `Var::new` is the only allocator of `ir.Var`; `no_new` generates no other.
47// tvm-ffi-stubgen(object): ir.Var(no_new)
48// Constants and loads are typed by a `PrimType`: their allocators take one, and they convert into
49// a `PrimExpr` without a check.
50// tvm-ffi-stubgen(field): ir.IntImm.ty(type = PrimType)
51// tvm-ffi-stubgen(field): ir.FloatImm.ty(type = PrimType)
52// tvm-ffi-stubgen(field): ir.TensorLoad.ty(type = PrimType)
53// tvm-ffi-stubgen(field): ir.TensorLoad.indices(type = Array<PrimExpr>)
54// A range is bounded by `PrimExpr`s, as C++ `RangeObj` holds `PrimExpr begin, extent`.
55// tvm-ffi-stubgen(field): ir.Range.begin(type = PrimExpr)
56// tvm-ffi-stubgen(field): ir.Range.extent(type = PrimExpr)
57// tvm-ffi-stubgen(field): ir.TupleGetItem.index(type = i32)
58// Names the hand-written wrappers use: the import section keeps them even when no generated block
59// does.
60// tvm-ffi-stubgen(import): crate::ir::prim::op::ExprResult
61// tvm-ffi-stubgen(import): crate::ir::r#type::PrimTypeObj
62// tvm-ffi-stubgen(import): tvm_ffi::Error
63// tvm-ffi-stubgen(import): tvm_ffi::ObjectRefCore
64// tvm-ffi-stubgen(import): tvm_ffi::AnyView
65// tvm-ffi-stubgen(import): tvm_ffi::Result
66// tvm-ffi-stubgen(import): tvm_ffi::reflection::NativeFunction
67// tvm-ffi-stubgen(import): tvm_ffi::reflection::TypeAttrColumn
68// tvm-ffi-stubgen(import): std::sync::LazyLock
69// tvm-ffi-stubgen(import): tvm_ffi::tvm_ffi_sys::TVMFFITypeIndex
70// tvm-ffi-stubgen(import): crate::ir::location::UNKNOWN_LOC
71// tvm-ffi-stubgen(import): crate::ir::op::OpObj
72// tvm-ffi-stubgen(import): crate::ir::prim::AddObj
73// tvm-ffi-stubgen(import): crate::ir::r#type::AnyType
74// tvm-ffi-stubgen(import): crate::ir::r#type::FuncType
75// tvm-ffi-stubgen(import): crate::ir::r#type::FuncTypeObj
76// tvm-ffi-stubgen(import): crate::ir::r#type::MissingType
77// tvm-ffi-stubgen(import): crate::ir::r#type::MissingTypeObj
78// tvm-ffi-stubgen(import): crate::ir::r#type::PrimType
79// tvm-ffi-stubgen(import): crate::ir::r#type::StringType
80// tvm-ffi-stubgen(import): crate::ir::r#type::TupleType
81// tvm-ffi-stubgen(import): crate::ir::r#type::TupleTypeObj
82// tvm-ffi-stubgen(import): crate::ir::support
83// tvm-ffi-stubgen(import): std::borrow::Borrow
84// tvm-ffi-stubgen(import): tvm_ffi::IntoArg
85
86// tvm-ffi-stubgen(begin): import-section
87use crate::ir::attrs::Attrs;
88use crate::ir::location::Location;
89use crate::ir::location::UNKNOWN_LOC;
90use crate::ir::op::OpObj;
91use crate::ir::prim::AddObj;
92use crate::ir::prim::op::ExprResult;
93use crate::ir::r#type::AnyType;
94use crate::ir::r#type::FuncType;
95use crate::ir::r#type::FuncTypeObj;
96use crate::ir::r#type::MissingType;
97use crate::ir::r#type::MissingTypeObj;
98use crate::ir::r#type::PrimType;
99use crate::ir::r#type::PrimTypeObj;
100use crate::ir::r#type::StringType;
101use crate::ir::r#type::TupleType;
102use crate::ir::r#type::TupleTypeObj;
103use crate::ir::r#type::Type;
104use crate::ir::support;
105use std::borrow::Borrow;
106use std::ops::Deref;
107use std::sync::LazyLock;
108use tvm_ffi::Any;
109use tvm_ffi::AnyView;
110use tvm_ffi::Array;
111use tvm_ffi::BigInt;
112use tvm_ffi::DLDataType;
113use tvm_ffi::Error;
114use tvm_ffi::IntoArg;
115use tvm_ffi::Object;
116use tvm_ffi::ObjectArc;
117use tvm_ffi::ObjectRefCore;
118use tvm_ffi::Result;
119use tvm_ffi::String;
120use tvm_ffi::reflection::NativeFunction;
121use tvm_ffi::reflection::TypeAttrColumn;
122use tvm_ffi::tvm_ffi_sys::TVMFFITypeIndex;
123// tvm-ffi-stubgen(end)
124
125/// The base of every expression: its source location `loc` and its type `ty`.
126///
127/// The type may be a [`MissingType`] while the expression is under construction. Each kind of
128/// expression is a subtype that adds its operands. [`PrimExpr`] and [`IntExpr`] are expressions
129/// checked to have a primitive or an integer type.
130///
131// tvm-ffi-stubgen(begin): object/ir.Expr
132#[allow(missing_docs)]
133#[repr(C)]
134#[derive(tvm_ffi::derive::ObjectRef, Clone)]
135pub struct Expr {
136    data_: ObjectArc<ExprObj>,
137}
138
139/// The object behind [`Expr`].
140// Complete: reflected fields fill [24, 40) exactly.
141#[allow(missing_docs)]
142#[repr(C)]
143#[derive(tvm_ffi::derive::Object)]
144#[object(type_key = "ir.Expr", immutable, rs_parent)]
145pub struct ExprObj {
146    base_: Object,
147    pub loc: Location,
148    pub ty: Type,
149}
150
151const _: () = {
152    assert!(::core::mem::size_of::<ExprObj>() == 40);
153    assert!(::core::mem::align_of::<ExprObj>() == 8);
154};
155
156#[allow(missing_docs)]
157impl ExprObj {
158    pub fn new(loc: Location, ty: Type) -> Self {
159        let base_ = Object::new();
160        Self { base_, loc, ty }
161    }
162}
163// tvm-ffi-stubgen(end)
164
165impl Expr {
166    /// Return `self[indices]`, as the subscript rule of its type realizes it: a [`TupleGetItem`] of
167    /// a tuple, a [`TensorLoad`] or [`TensorRegion`] of a tensor (`ir.SubscriptExprRealize`).
168    ///
169    /// # Errors
170    ///
171    /// Returns a `TypeError` if the type of the expression has no subscript rule, or the error the
172    /// rule raises.
173    pub fn subscript(
174        &self,
175        indices: impl IntoIterator<Item = Subscript>,
176        loc: impl IntoArg<Location>,
177    ) -> Result<Any> {
178        let indices = indices.into_iter().map(|index| Any::from(&index)).collect::<Array<Any>>();
179        tvm_ffi::cached_global_func!("ir.SubscriptExprRealize").call_tuple((
180            self,
181            &indices,
182            loc.into_arg().borrow(),
183        ))
184    }
185}
186
187/// An index of [`Expr::subscript`]: a primitive expression, or a `start:stop:step` slice.
188#[derive(Clone)]
189pub enum Subscript {
190    /// The point index `index`.
191    Index(PrimExpr),
192    /// The slice `start:stop:step`, whose missing bounds are `None`.
193    Slice(Option<PrimExpr>, Option<PrimExpr>, Option<PrimExpr>),
194}
195
196impl From<&Subscript> for Any {
197    fn from(subscript: &Subscript) -> Self {
198        match subscript {
199            Subscript::Index(index) => Any::from(index.clone()),
200            Subscript::Slice(start, stop, step) => Any::from(
201                [start, stop, step]
202                    .into_iter()
203                    .map(|bound| Any::from(bound.clone()))
204                    .collect::<Array<Any>>(),
205            ),
206        }
207    }
208}
209
210// ---------------------------------------------------------------------------------------------
211// Conversions into an expression
212
213/// A value that converts into the expression type `T`, possibly failing: a `T` or a subtype of it,
214/// owned or borrowed, a Rust literal, or an [`ExprResult`] under construction.
215///
216/// `T` is [`Expr`] by default, and [`PrimExpr`] for an operand that must be primitive. The
217/// subtypes of `T` are the types with an upcast to it, for which tvm-ffi generates an
218/// [`IntoArg<T>`]; every `IntoArg<T>` is an `IntoExpr<T>`, so a new expression type
219/// converts into each type it upcasts to without a list to maintain. The conversion never checks a
220/// type: an [`Expr`] or a [`Var`] is not a `PrimExpr` until it is checked, by `downcast_ref`, which
221/// borrows it in place, or `downcast`, which takes it. Its one
222/// error is the first error an [`ExprResult`] operand raised.
223///
224/// # Examples
225///
226/// ```
227/// use tvm_tirx::ir::prim::Add;
228/// use tvm_tirx::ir::{PrimExpr, PrimType, PrimVar, Var, UNKNOWN_LOC};
229/// use tvm_tirx::script::script;
230/// use tvm_tirx::tvm_ffi::ObjectRefCore;
231///
232/// let x = PrimVar::new("x", PrimType::int(32), UNKNOWN_LOC);
233/// let sum = Add::new(&x + 1, 2, UNKNOWN_LOC)?;
234/// assert_eq!(script(&sum)?, "x + 1 + 2");
235///
236/// let f = PrimVar::new("f", PrimType::float(32), UNKNOWN_LOC);
237/// assert!(Add::new(&f << 1, 2, UNKNOWN_LOC).is_err());
238///
239/// // A variable of any type is checked first, here borrowed in place.
240/// let var = Var::new("y", PrimType::int(32), UNKNOWN_LOC);
241/// let y = var.downcast_ref::<PrimVar>().expect("an int32 variable");
242/// assert_eq!(script(&Add::new(y, &x, UNKNOWN_LOC)?)?, "y + x");
243/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
244/// ```
245///
246/// An [`Expr`] is not an `IntoExpr<PrimExpr>`:
247///
248/// ```compile_fail
249/// # use tvm_tirx::ir::prim::Add;
250/// # use tvm_tirx::ir::{Expr, UNKNOWN_LOC};
251/// fn add(a: &Expr, b: &Expr) -> tvm_tirx::tvm_ffi::Result<Add> {
252///     Add::new(a, b, UNKNOWN_LOC)
253/// }
254/// ```
255pub trait IntoExpr<T = Expr> {
256    /// The expression: an owned `T` for an owned value or a literal, or a borrowed `&T` for a
257    /// reference, which converts without a reference-count change.
258    ///
259    /// A function that only reads the expression borrows it with `.borrow()`; one that keeps
260    /// it takes ownership with [`into_owned_expr`](Self::into_owned_expr).
261    type Output: Borrow<T> + Into<T>;
262
263    /// Convert into an expression, or return the first error an [`ExprResult`] raised.
264    fn into_expr(self) -> Result<Self::Output>;
265
266    /// Convert into an owned expression, as [`Cow::into_owned`](std::borrow::Cow::into_owned)
267    /// does: an owned value moves, and only a borrowed expression is cloned.
268    fn into_owned_expr(self) -> Result<T>
269    where
270        Self: Sized,
271    {
272        self.into_expr().map(Into::into)
273    }
274}
275
276// A `T` or a subtype of it, owned or borrowed, through the `IntoArg<T>` its upcast to `T`
277// generates. Rust literals join through their own `IntoArg` below, and `ExprResult`
278// implements `IntoExpr` for each target it builds.
279impl<T, S: IntoArg<T>> IntoExpr<T> for S
280where
281    S::Output: Into<T>,
282{
283    type Output = S::Output;
284
285    fn into_expr(self) -> Result<S::Output> {
286        Ok(self.into_arg())
287    }
288}
289
290// Rust literals are expressions too, owned and built on conversion, as `From` builds them.
291macro_rules! impl_literal_into_expr {
292    ($target:ty: $($t:ty),*) => {$(
293        impl IntoArg<$target> for $t {
294            type Output = $target;
295
296            fn into_arg(self) -> $target {
297                self.into()
298            }
299
300            fn into_owned(self) -> $target {
301                self.into()
302            }
303        }
304    )*};
305}
306impl_literal_into_expr!(Expr: i32, i64, bool, f32, f64);
307impl_literal_into_expr!(PrimExpr: i32, i64, bool, f32, f64);
308impl_literal_into_expr!(IntExpr: i32, i64);
309impl_literal_into_expr!(IntImm: i32, i64, bool);
310impl_literal_into_expr!(FloatImm: f32, f64);
311
312// Rust literals, as C++ converts them into an expression: an `i32` and an `f32` through the
313// constructors `PrimExpr(int32_t)` and `PrimExpr(float)`, the others as constants of their type.
314
315impl From<i32> for Expr {
316    fn from(value: i32) -> Self {
317        IntImm::int32(value).into()
318    }
319}
320
321impl From<i64> for Expr {
322    fn from(value: i64) -> Self {
323        IntImm::int64(value).into()
324    }
325}
326
327impl From<bool> for Expr {
328    fn from(value: bool) -> Self {
329        IntImm::bool(value).into()
330    }
331}
332
333impl From<f32> for Expr {
334    fn from(value: f32) -> Self {
335        FloatImm::float32(value).into()
336    }
337}
338
339impl From<f64> for Expr {
340    fn from(value: f64) -> Self {
341        FloatImm::float64(value).into()
342    }
343}
344
345// ---------------------------------------------------------------------------------------------
346// Typed expressions: `PrimExpr` and `IntExpr`
347
348/// An expression typed by a `PrimType`: a constant, a variable, an operator on scalars or
349/// vectors, or a call that returns one.
350///
351/// `PrimExpr` and [`IntExpr`] are typed expressions: an [`Expr`] checked when the reference
352/// is made, so a function that takes one needs no check of its own. A typed expression
353/// converts into an `Expr` for free; an `Expr` converts into one only through `TryFrom`, whose
354/// error names the expression and its type.
355///
356/// # Examples
357///
358/// ```
359/// use tvm_tirx::ir::{dtype, Expr, PrimExpr, PrimType, PrimVar, StringImm, Var, UNKNOWN_LOC};
360///
361/// fn is_scalar(expr: &PrimExpr) -> bool {
362///     expr.prim_ty().is_scalar()
363/// }
364///
365/// let x = PrimVar::new("x", PrimType::int(32), UNKNOWN_LOC);
366/// assert!(is_scalar(&PrimExpr::try_from(&x + 1)?));
367///
368/// let text = Expr::from(StringImm::new("hi", UNKNOWN_LOC));
369/// let error = PrimExpr::try_from(text).err().unwrap();
370/// assert!(error.message().contains("ir.StringImm[ty=ir.StringType]"));
371/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
372/// ```
373///
374/// An `Expr` is not a `PrimExpr` until it is checked, nor a `PrimExpr` an `IntExpr`:
375///
376/// ```compile_fail
377/// # use tvm_tirx::ir::{Expr, PrimExpr};
378/// fn widen(expr: Expr) -> PrimExpr {
379///     expr
380/// }
381/// ```
382///
383/// ```compile_fail
384/// # use tvm_tirx::ir::{IntExpr, PrimExpr};
385/// fn narrow(expr: PrimExpr) -> IntExpr {
386///     expr.into()
387/// }
388/// ```
389#[repr(transparent)]
390#[derive(Clone, tvm_ffi::derive::ObjectRef)]
391#[object_ref(parent = Expr, skip_any_compatible)]
392pub struct PrimExpr {
393    data_: ObjectArc<ExprObj>,
394}
395
396// SAFETY: a `PrimExpr` is an `Expr` typed by a `PrimType`, and the literals it converts are
397// constants, which are.
398unsafe impl tvm_ffi::object::ObjectRefAnyCompatible for PrimExpr {
399    #[inline]
400    fn extra_check(obj: &ExprObj) -> bool {
401        obj.ty.downcast_ref::<PrimTypeObj>().is_some()
402    }
403
404    // As C++ converts an `Any` into a `PrimExpr`: a bool is a boolean constant, an int an `int32`
405    // constant when it fits and an `int64` one otherwise, and a float a `float32` constant.
406    fn convert_fallback(value: AnyView<'_>) -> Option<Self> {
407        let index = value.type_index();
408        if index == TVMFFITypeIndex::kTVMFFIBool as i32 {
409            Some(IntImm::bool(bool::try_from(value).ok()?).into())
410        } else if index == TVMFFITypeIndex::kTVMFFIInt as i32 {
411            // C++ `TypeTraits<IntImm>::ConvertFallbackValue` keeps an int that fits as `int32`.
412            let value = i64::try_from(value).ok()?;
413            let constant = match i32::try_from(value) {
414                Ok(value) => IntImm::int32(value),
415                Err(_) => IntImm::int64(value),
416            };
417            Some(constant.into())
418        } else if index == TVMFFITypeIndex::kTVMFFIFloat as i32 {
419            let value = f64::try_from(value).ok()?;
420            FloatImm::new(PrimType::float(32), value, UNKNOWN_LOC).ok().map(Into::into)
421        } else {
422            None
423        }
424    }
425
426    fn custom_type_str() -> std::string::String {
427        "ir.PrimExpr".into()
428    }
429
430    fn custom_mismatch_type_info(value: tvm_ffi::AnyView<'_>) -> std::string::String {
431        typed_expr_mismatch(value)
432    }
433}
434
435crate::def_expr_op_over_loads!(PrimExpr);
436
437impl PrimExpr {
438    /// Return the type of this expression, the [`PrimType`] its check guarantees.
439    pub fn prim_ty(&self) -> &PrimType {
440        self.data_.ty.downcast_ref::<PrimType>().expect("a typed expression has a `PrimType`")
441    }
442}
443
444/// A [`PrimExpr`] of a scalar signed or unsigned integer type of any width, such as an index or
445/// an extent.
446///
447/// # Examples
448///
449/// ```
450/// use tvm_tirx::ir::{IntExpr, PrimType, PrimVar, Var, UNKNOWN_LOC};
451/// use tvm_tirx::script::script;
452///
453/// let i = PrimVar::new("i", PrimType::int(64), UNKNOWN_LOC);
454/// let offset = IntExpr::try_from(&i * 4)?;
455/// assert_eq!(script(&offset)?, "i * T.int64(4)");
456///
457/// let f = PrimVar::new("f", PrimType::float(32), UNKNOWN_LOC);
458/// assert!(IntExpr::try_from(&f * 4).is_err());
459/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
460/// ```
461#[repr(transparent)]
462#[derive(Clone, tvm_ffi::derive::ObjectRef)]
463#[object_ref(unsafe parent = PrimExpr, skip_any_compatible)]
464pub struct IntExpr {
465    data_: ObjectArc<ExprObj>,
466}
467
468// SAFETY: an `IntExpr` is a `PrimExpr` typed by a scalar integer type, and the int literal it
469// converts is an integer constant.
470unsafe impl tvm_ffi::object::ObjectRefAnyCompatible for IntExpr {
471    #[inline]
472    fn extra_check(obj: &ExprObj) -> bool {
473        obj.ty.downcast_ref::<PrimType>().is_some_and(scalar_int)
474    }
475
476    // An int converts as it does into a `PrimExpr`; no other literal does.
477    fn convert_fallback(value: AnyView<'_>) -> Option<Self> {
478        if value.type_index() != TVMFFITypeIndex::kTVMFFIInt as i32 {
479            return None;
480        }
481        let expr = <PrimExpr as tvm_ffi::object::ObjectRefAnyCompatible>::convert_fallback(value)?;
482        IntExpr::try_from(expr).ok()
483    }
484
485    fn custom_type_str() -> std::string::String {
486        "ir.IntExpr".into()
487    }
488
489    fn custom_mismatch_type_info(value: tvm_ffi::AnyView<'_>) -> std::string::String {
490        typed_expr_mismatch(value)
491    }
492}
493
494crate::def_expr_op_over_loads!(IntExpr);
495
496impl IntExpr {
497    /// Return the type of this expression, the [`PrimType`] its check guarantees.
498    pub fn prim_ty(&self) -> &PrimType {
499        self.data_.ty.downcast_ref::<PrimType>().expect("a typed expression has a `PrimType`")
500    }
501}
502
503tvm_ffi::impl_object_ref_upcast!(IntExpr => Expr);
504
505/// The built expression, checked to be an integer, or the first error raised while building it.
506impl TryFrom<ExprResult> for IntExpr {
507    type Error = Error;
508
509    fn try_from(value: ExprResult) -> Result<Self> {
510        PrimExpr::try_from(value)?.try_into()
511    }
512}
513
514// Rust literals, as they convert into an `Expr`. C++ has the constructors `PrimExpr(int32_t)` and
515// `PrimExpr(float)`; the other literals are constants of their own type.
516
517/// An `i32` is an `int32` constant.
518impl From<i32> for PrimExpr {
519    fn from(value: i32) -> Self {
520        IntImm::int32(value).into()
521    }
522}
523
524/// An `i64` is an `int64` constant.
525impl From<i64> for PrimExpr {
526    fn from(value: i64) -> Self {
527        IntImm::int64(value).into()
528    }
529}
530
531/// A `bool` is a boolean constant.
532impl From<bool> for PrimExpr {
533    fn from(value: bool) -> Self {
534        IntImm::bool(value).into()
535    }
536}
537
538/// An `f32` is a `float32` constant.
539impl From<f32> for PrimExpr {
540    fn from(value: f32) -> Self {
541        FloatImm::float32(value).into()
542    }
543}
544
545/// An `f64` is a `float64` constant.
546impl From<f64> for PrimExpr {
547    fn from(value: f64) -> Self {
548        FloatImm::float64(value).into()
549    }
550}
551
552/// An `i32` is an `int32` constant.
553impl From<i32> for IntExpr {
554    fn from(value: i32) -> Self {
555        int_constant(IntImm::int32(value))
556    }
557}
558
559/// An `i64` is an `int64` constant.
560impl From<i64> for IntExpr {
561    fn from(value: i64) -> Self {
562        int_constant(IntImm::int64(value))
563    }
564}
565
566/// The `IntExpr` of an integer constant, which `int32` and `int64` constants are.
567fn int_constant(constant: IntImm) -> IntExpr {
568    Expr::from(constant).downcast().expect("an integer constant is an `IntExpr`")
569}
570
571// The checks and conversions of the typed expressions.
572
573/// A scalar signed or unsigned integer type.
574fn scalar_int(ty: &PrimType) -> bool {
575    use tvm_ffi::DLDataTypeCode::{kDLInt, kDLUInt};
576    ty.is_scalar() && ty.matches_code(&[kDLInt, kDLUInt])
577}
578
579/// What a typed expression's conversion error names a value it rejects: an expression with its
580/// type, `ir.StringImm[ty=ir.StringType]`, or the type key of another value.
581fn typed_expr_mismatch(value: AnyView<'_>) -> std::string::String {
582    let key = |index: i32| tvm_ffi::reflection::type_key(index).unwrap_or_default();
583    let Some(expr) = value.downcast_ref::<ExprObj>() else {
584        return key(value.type_index()).to_string();
585    };
586    let ty = match expr.ty.downcast_ref::<PrimTypeObj>() {
587        Some(prim) => support::dtype_name(prim.dtype),
588        None => key(AnyView::from(&expr.ty).type_index()).to_string(),
589    };
590    format!("{}[ty={ty}]", key(value.type_index()))
591}
592
593// ---------------------------------------------------------------------------------------------
594// Expression nodes
595
596/// The base of the expressions that compilation eliminates, such as [`LambdaExpr`]: traversals
597/// visit them like any expression, but none remains in executable IR.
598///
599// tvm-ffi-stubgen(begin): object/ir.StagingExpr
600#[allow(missing_docs)]
601#[repr(C)]
602#[derive(tvm_ffi::derive::ObjectRef, Clone)]
603pub struct StagingExpr {
604    data_: ObjectArc<StagingExprObj>,
605}
606
607/// The object behind [`StagingExpr`].
608// Complete: reflected fields fill [40, 40) exactly.
609#[allow(missing_docs)]
610#[repr(C)]
611#[derive(tvm_ffi::derive::Object)]
612#[object(type_key = "ir.StagingExpr", immutable, rs_parent)]
613pub struct StagingExprObj {
614    base_: ExprObj,
615}
616
617const _: () = {
618    assert!(::core::mem::size_of::<StagingExprObj>() == 40);
619    assert!(::core::mem::align_of::<StagingExprObj>() == 8);
620};
621
622impl Deref for StagingExprObj {
623    type Target = ExprObj;
624    fn deref(&self) -> &ExprObj {
625        &self.base_
626    }
627}
628
629#[allow(missing_docs)]
630impl StagingExprObj {
631    pub fn new(loc: Location, ty: Type) -> Self {
632        let base_ = ExprObj::new(loc, ty);
633        Self { base_ }
634    }
635}
636
637tvm_ffi::impl_object_ref_upcast!(StagingExpr => Expr);
638// tvm-ffi-stubgen(end)
639
640/// The base of opaque construction-time expressions, which generic expression visitors and
641/// mutators pass through. None may remain in finished IR.
642///
643// tvm-ffi-stubgen(begin): object/ir.OpaqueExpr
644#[allow(missing_docs)]
645#[repr(C)]
646#[derive(tvm_ffi::derive::ObjectRef, Clone)]
647pub struct OpaqueExpr {
648    data_: ObjectArc<OpaqueExprObj>,
649}
650
651/// The object behind [`OpaqueExpr`].
652// Complete: reflected fields fill [40, 40) exactly.
653#[allow(missing_docs)]
654#[repr(C)]
655#[derive(tvm_ffi::derive::Object)]
656#[object(type_key = "ir.OpaqueExpr", immutable, rs_parent)]
657pub struct OpaqueExprObj {
658    base_: ExprObj,
659}
660
661const _: () = {
662    assert!(::core::mem::size_of::<OpaqueExprObj>() == 40);
663    assert!(::core::mem::align_of::<OpaqueExprObj>() == 8);
664};
665
666impl Deref for OpaqueExprObj {
667    type Target = ExprObj;
668    fn deref(&self) -> &ExprObj {
669        &self.base_
670    }
671}
672
673#[allow(missing_docs)]
674impl OpaqueExprObj {
675    pub fn new(loc: Location, ty: Type) -> Self {
676        let base_ = ExprObj::new(loc, ty);
677        Self { base_ }
678    }
679}
680
681tvm_ffi::impl_object_ref_upcast!(OpaqueExpr => Expr);
682// tvm-ffi-stubgen(end)
683
684/// A global variable: a reference to a function of the module, by which functions call each
685/// other, recursively too.
686///
687/// Each [`GlobalVar::new`] creates a distinct object even when the names match, so a call uses
688/// the variable the module stores, from
689/// [`IRModule::get_global_var`](crate::ir::IRModule::get_global_var). Structural equality compares
690/// `name_hint` and ignores the type, which comes from the function definition.
691///
692// tvm-ffi-stubgen(begin): object/ir.GlobalVar
693#[allow(missing_docs)]
694#[repr(C)]
695#[derive(tvm_ffi::derive::ObjectRef, Clone)]
696pub struct GlobalVar {
697    data_: ObjectArc<GlobalVarObj>,
698}
699
700/// The object behind [`GlobalVar`].
701// Complete: reflected fields fill [40, 56) exactly.
702#[allow(missing_docs)]
703#[repr(C)]
704#[derive(tvm_ffi::derive::Object)]
705#[object(type_key = "ir.GlobalVar", final, immutable)]
706pub struct GlobalVarObj {
707    base_: ExprObj,
708    pub name_hint: String,
709}
710
711const _: () = {
712    assert!(::core::mem::size_of::<GlobalVarObj>() == 56);
713    assert!(::core::mem::align_of::<GlobalVarObj>() == 8);
714};
715
716impl Deref for GlobalVarObj {
717    type Target = ExprObj;
718    fn deref(&self) -> &ExprObj {
719        &self.base_
720    }
721}
722
723#[allow(missing_docs)]
724impl GlobalVarObj {
725    pub(crate) fn new(loc: Location, ty: Type, name_hint: String) -> Self {
726        let base_ = ExprObj::new(loc, ty);
727        Self { base_, name_hint }
728    }
729}
730
731#[allow(missing_docs)]
732impl GlobalVar {
733    /// Create a `GlobalVar` from its field values.
734    pub fn from_fields(
735        loc: impl IntoArg<Location>,
736        ty: impl IntoArg<Type>,
737        name_hint: impl Into<String>,
738    ) -> Self {
739        let obj = GlobalVarObj::new(loc.into_owned(), ty.into_owned(), name_hint.into());
740        Self { data_: ObjectArc::new(obj) }
741    }
742}
743
744tvm_ffi::impl_object_ref_upcast!(GlobalVar => Expr);
745// tvm-ffi-stubgen(end)
746
747impl GlobalVar {
748    /// Create the global variable `name_hint`, of a missing type.
749    pub fn new(name_hint: &str, loc: impl IntoArg<Location>) -> Self {
750        let ty = MissingType::new();
751        Self::from_fields(loc.into_owned(), ty, String::from(name_hint))
752    }
753}
754
755/// The tuple of the expressions `fields`, `(a, b, ...)`.
756///
757/// [`Tuple::new`] types it by the [`TupleType`] of the field types when all of them are known,
758/// and by [`MissingType`] otherwise.
759///
760// tvm-ffi-stubgen(begin): object/ir.Tuple
761#[allow(missing_docs)]
762#[repr(C)]
763#[derive(tvm_ffi::derive::ObjectRef, Clone)]
764pub struct Tuple {
765    data_: ObjectArc<TupleObj>,
766}
767
768/// The object behind [`Tuple`].
769// Complete: reflected fields fill [40, 48) exactly.
770#[allow(missing_docs)]
771#[repr(C)]
772#[derive(tvm_ffi::derive::Object)]
773#[object(type_key = "ir.Tuple", final, immutable)]
774pub struct TupleObj {
775    base_: ExprObj,
776    pub fields: Array<Expr>,
777}
778
779const _: () = {
780    assert!(::core::mem::size_of::<TupleObj>() == 48);
781    assert!(::core::mem::align_of::<TupleObj>() == 8);
782};
783
784impl Deref for TupleObj {
785    type Target = ExprObj;
786    fn deref(&self) -> &ExprObj {
787        &self.base_
788    }
789}
790
791#[allow(missing_docs)]
792impl TupleObj {
793    pub(crate) fn new(loc: Location, ty: Type, fields: Array<Expr>) -> Self {
794        let base_ = ExprObj::new(loc, ty);
795        Self { base_, fields }
796    }
797}
798
799#[allow(missing_docs)]
800impl Tuple {
801    /// Create a `Tuple` from its field values.
802    pub fn from_fields(
803        loc: impl IntoArg<Location>,
804        ty: impl IntoArg<Type>,
805        fields: impl Into<Array<Expr>>,
806    ) -> Self {
807        let obj = TupleObj::new(loc.into_owned(), ty.into_owned(), fields.into());
808        Self { data_: ObjectArc::new(obj) }
809    }
810}
811
812tvm_ffi::impl_object_ref_upcast!(Tuple => Expr);
813// tvm-ffi-stubgen(end)
814
815impl Tuple {
816    /// Create the tuple of `fields`, typed by the types of its fields when they are all known.
817    pub fn new(
818        fields: impl IntoIterator<Item = impl IntoArg<Expr>>,
819        loc: impl IntoArg<Location>,
820    ) -> Self {
821        let fields = fields.into_iter().map(IntoArg::into_owned).collect::<Array<Expr>>();
822        let ty: Type =
823            match fields.iter().any(|field| field.ty.downcast_ref::<MissingTypeObj>().is_some()) {
824                true => MissingType::new().into(),
825                false => {
826                    let field_types = fields.iter().map(|field| field.ty.clone());
827                    TupleType::new(field_types, UNKNOWN_LOC).into()
828                }
829            };
830        Self::from_fields(loc.into_owned(), ty, fields)
831    }
832}
833
834/// The field `index` of the tuple `tuple_value`.
835///
836// tvm-ffi-stubgen(begin): object/ir.TupleGetItem
837#[allow(missing_docs)]
838#[repr(C)]
839#[derive(tvm_ffi::derive::ObjectRef, Clone)]
840pub struct TupleGetItem {
841    data_: ObjectArc<TupleGetItemObj>,
842}
843
844/// The object behind [`TupleGetItem`].
845// Complete: reflected fields fill [40, 56) exactly (alignment padding [52, 56)).
846#[allow(missing_docs)]
847#[repr(C)]
848#[derive(tvm_ffi::derive::Object)]
849#[object(type_key = "ir.TupleGetItem", final, immutable)]
850pub struct TupleGetItemObj {
851    base_: ExprObj,
852    pub tuple_value: Expr,
853    pub index: i32,
854}
855
856const _: () = {
857    assert!(::core::mem::size_of::<TupleGetItemObj>() == 56);
858    assert!(::core::mem::align_of::<TupleGetItemObj>() == 8);
859};
860
861impl Deref for TupleGetItemObj {
862    type Target = ExprObj;
863    fn deref(&self) -> &ExprObj {
864        &self.base_
865    }
866}
867
868#[allow(missing_docs)]
869impl TupleGetItemObj {
870    pub(crate) fn new(loc: Location, ty: Type, tuple_value: Expr, index: i32) -> Self {
871        let base_ = ExprObj::new(loc, ty);
872        Self { base_, tuple_value, index }
873    }
874}
875
876#[allow(missing_docs)]
877impl TupleGetItem {
878    /// Create a `TupleGetItem` from its field values.
879    pub fn from_fields(
880        loc: impl IntoArg<Location>,
881        ty: impl IntoArg<Type>,
882        tuple_value: impl IntoArg<Expr>,
883        index: i32,
884    ) -> Self {
885        let obj = TupleGetItemObj::new(
886            loc.into_owned(),
887            ty.into_owned(),
888            tuple_value.into_owned(),
889            index,
890        );
891        Self { data_: ObjectArc::new(obj) }
892    }
893}
894
895tvm_ffi::impl_object_ref_upcast!(TupleGetItem => Expr);
896// tvm-ffi-stubgen(end)
897
898impl TupleGetItem {
899    /// Create the access to field `index` of `tuple_value`, typed by the field type and checked
900    /// against the tuple type when it is known.
901    ///
902    /// # Errors
903    ///
904    /// Returns an `IndexError` if `index` is negative, or not less than the number of fields of a
905    /// tuple of known type.
906    pub fn new(
907        tuple_value: impl IntoExpr,
908        index: i32,
909        loc: impl IntoArg<Location>,
910    ) -> Result<Self> {
911        let tuple_value = tuple_value.into_owned_expr()?;
912        if index < 0 {
913            let message = format!(
914                "Index out of bounds: Tuple {} cannot be accessed with negative index {index}",
915                tuple_value
916            );
917            return Err(support::compare_failed(
918                tvm_ffi::INDEX_ERROR,
919                "index >= 0",
920                index,
921                0,
922                &message,
923            ));
924        }
925        let ty: Type = match tuple_value.ty.downcast_ref::<TupleTypeObj>() {
926            Some(tuple_type) => {
927                let size = tuple_type.fields.len();
928                if index as usize >= size {
929                    let message = format!(
930                        "Index out of bounds: Tuple {} is of size {size}, and cannot be accessed \
931                         with index {index}",
932                        tuple_value
933                    );
934                    let condition = "index < tuple_type->fields.size()";
935                    let error = support::compare_failed(
936                        tvm_ffi::INDEX_ERROR,
937                        condition,
938                        index,
939                        size,
940                        &message,
941                    );
942                    return Err(error);
943                }
944                tuple_type.fields[index as usize].clone()
945            }
946            None => MissingType::new().into(),
947        };
948        Ok(Self::from_fields(loc, ty, tuple_value, index))
949    }
950}
951
952/// The element or vector of `source` at `indices`: a load from a tensor, or from any expression
953/// whose type supports it.
954///
955/// The type of `source` interprets the indices, in dimension order, and infers the [`PrimType`]
956/// of the load.
957///
958// tvm-ffi-stubgen(begin): object/ir.TensorLoad
959#[allow(missing_docs)]
960#[repr(C)]
961#[derive(tvm_ffi::derive::ObjectRef, Clone)]
962pub struct TensorLoad {
963    data_: ObjectArc<TensorLoadObj>,
964}
965
966/// The object behind [`TensorLoad`].
967// Complete: reflected fields fill [40, 56) exactly.
968#[allow(missing_docs)]
969#[repr(C)]
970#[derive(tvm_ffi::derive::Object)]
971#[object(type_key = "ir.TensorLoad", final, immutable)]
972pub struct TensorLoadObj {
973    base_: ExprObj,
974    pub source: Expr,
975    pub indices: Array<PrimExpr>,
976}
977
978const _: () = {
979    assert!(::core::mem::size_of::<TensorLoadObj>() == 56);
980    assert!(::core::mem::align_of::<TensorLoadObj>() == 8);
981};
982
983impl Deref for TensorLoadObj {
984    type Target = ExprObj;
985    fn deref(&self) -> &ExprObj {
986        &self.base_
987    }
988}
989
990#[allow(missing_docs)]
991impl TensorLoadObj {
992    pub(crate) fn new(loc: Location, ty: PrimType, source: Expr, indices: Array<PrimExpr>) -> Self {
993        let base_ = ExprObj::new(loc, ty.into());
994        Self { base_, source, indices }
995    }
996}
997
998#[allow(missing_docs)]
999impl TensorLoad {
1000    /// Create a `TensorLoad` from its field values.
1001    pub fn from_fields(
1002        loc: impl IntoArg<Location>,
1003        ty: impl IntoArg<PrimType>,
1004        source: impl IntoArg<Expr>,
1005        indices: impl Into<Array<PrimExpr>>,
1006    ) -> Self {
1007        let obj = TensorLoadObj::new(
1008            loc.into_owned(),
1009            ty.into_owned(),
1010            source.into_owned(),
1011            indices.into(),
1012        );
1013        Self { data_: ObjectArc::new(obj) }
1014    }
1015}
1016
1017tvm_ffi::impl_object_ref_upcast!(TensorLoad => Expr);
1018tvm_ffi::impl_object_ref_upcast!(unsafe TensorLoad => PrimExpr);
1019// tvm-ffi-stubgen(end)
1020
1021impl TensorLoad {
1022    /// Create the load of the element of `source` at `indices`, typed by the element type that the
1023    /// type of `source` infers.
1024    ///
1025    /// # Errors
1026    ///
1027    /// Returns a `TypeError` if the type of `source` does not support `TensorLoad`, or the error
1028    /// its type inference raises.
1029    pub fn new(
1030        source: impl IntoExpr,
1031        indices: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>,
1032        loc: impl IntoArg<Location>,
1033    ) -> Result<Self> {
1034        // The native library registers the column when it loads, so one lookup suffices.
1035        static INFER_TYPE: LazyLock<Option<TypeAttrColumn>> =
1036            LazyLock::new(|| TypeAttrColumn::lookup("__tvm_tensor_load_infer_type__"));
1037        let (source, loc) = (source.into_owned_expr()?, loc.into_owned());
1038        let indices = indices
1039            .into_iter()
1040            .map(IntoExpr::<PrimExpr>::into_owned_expr)
1041            .collect::<Result<Array<PrimExpr>>>()?;
1042        let ty_index = AnyView::from(&source.ty).type_index();
1043        let Some(infer) = INFER_TYPE.and_then(|column| column.get(ty_index)) else {
1044            let message = format!(
1045                "Type {} does not support TensorLoad",
1046                tvm_ffi::reflection::type_key(ty_index).unwrap_or_default()
1047            );
1048            return Err(support::check_failed(tvm_ffi::TYPE_ERROR, "infer.has_value()", &message));
1049        };
1050        // The hook types a load that has no type yet. Such a load is no `TensorLoad`, which is
1051        // typed by a `PrimType`, so only its object is made.
1052        let base_ = ExprObj::new(loc.clone(), MissingType::new().into());
1053        let untyped = TensorLoadObj { base_, source: source.clone(), indices: indices.clone() };
1054        // SAFETY: the column holds `PrimType(const TensorLoadObj*)` hooks.
1055        let infer: NativeFunction<(&TensorLoadObj,), PrimType> =
1056            unsafe { NativeFunction::from_any(infer)? };
1057        let ty = infer.call((&*ObjectArc::new(untyped),))?;
1058        Ok(Self::from_fields(loc, ty, source, indices))
1059    }
1060}
1061
1062/// The base of literal constants: [`IntImm`], [`FloatImm`], [`StringImm`], [`DataTypeImm`] and
1063/// [`GenericConst`].
1064///
1065// tvm-ffi-stubgen(begin): object/ir.Constant
1066#[allow(missing_docs)]
1067#[repr(C)]
1068#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1069pub struct Constant {
1070    data_: ObjectArc<ConstantObj>,
1071}
1072
1073/// The object behind [`Constant`].
1074// Complete: reflected fields fill [40, 40) exactly.
1075#[allow(missing_docs)]
1076#[repr(C)]
1077#[derive(tvm_ffi::derive::Object)]
1078#[object(type_key = "ir.Constant", immutable, rs_parent)]
1079pub struct ConstantObj {
1080    base_: ExprObj,
1081}
1082
1083const _: () = {
1084    assert!(::core::mem::size_of::<ConstantObj>() == 40);
1085    assert!(::core::mem::align_of::<ConstantObj>() == 8);
1086};
1087
1088impl Deref for ConstantObj {
1089    type Target = ExprObj;
1090    fn deref(&self) -> &ExprObj {
1091        &self.base_
1092    }
1093}
1094
1095#[allow(missing_docs)]
1096impl ConstantObj {
1097    pub fn new(loc: Location, ty: Type) -> Self {
1098        let base_ = ExprObj::new(loc, ty);
1099        Self { base_ }
1100    }
1101}
1102
1103tvm_ffi::impl_object_ref_upcast!(Constant => Expr);
1104// tvm-ffi-stubgen(end)
1105
1106/// A floating-point constant of a scalar floating-point type, its value held as an `f64`.
1107///
1108// tvm-ffi-stubgen(begin): object/ir.FloatImm
1109#[allow(missing_docs)]
1110#[repr(C)]
1111#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1112pub struct FloatImm {
1113    data_: ObjectArc<FloatImmObj>,
1114}
1115
1116/// The object behind [`FloatImm`].
1117// Complete: reflected fields fill [40, 48) exactly.
1118#[allow(missing_docs)]
1119#[repr(C)]
1120#[derive(tvm_ffi::derive::Object)]
1121#[object(type_key = "ir.FloatImm", final, immutable)]
1122pub struct FloatImmObj {
1123    base_: ConstantObj,
1124    pub value: f64,
1125}
1126
1127const _: () = {
1128    assert!(::core::mem::size_of::<FloatImmObj>() == 48);
1129    assert!(::core::mem::align_of::<FloatImmObj>() == 8);
1130};
1131
1132impl Deref for FloatImmObj {
1133    type Target = ConstantObj;
1134    fn deref(&self) -> &ConstantObj {
1135        &self.base_
1136    }
1137}
1138
1139#[allow(missing_docs)]
1140impl FloatImmObj {
1141    pub(crate) fn new(loc: Location, ty: PrimType, value: f64) -> Self {
1142        let base_ = ConstantObj::new(loc, ty.into());
1143        Self { base_, value }
1144    }
1145}
1146
1147#[allow(missing_docs)]
1148impl FloatImm {
1149    /// Create a `FloatImm` from its field values.
1150    pub fn from_fields(
1151        loc: impl IntoArg<Location>,
1152        ty: impl IntoArg<PrimType>,
1153        value: f64,
1154    ) -> Self {
1155        let obj = FloatImmObj::new(loc.into_owned(), ty.into_owned(), value);
1156        Self { data_: ObjectArc::new(obj) }
1157    }
1158}
1159
1160tvm_ffi::impl_object_ref_upcast!(FloatImm => Expr, FloatImm => Constant);
1161tvm_ffi::impl_object_ref_upcast!(unsafe FloatImm => PrimExpr);
1162// tvm-ffi-stubgen(end)
1163
1164impl FloatImm {
1165    /// Create the floating-point constant `value` of type `ty`, checked to fit it.
1166    ///
1167    /// ```
1168    /// use tvm_tirx::ir::{FloatImm, PrimType, UNKNOWN_LOC};
1169    /// let half = FloatImm::new(PrimType::float(16), 0.5, UNKNOWN_LOC)?;
1170    /// assert_eq!(half.value, 0.5);
1171    /// assert!(FloatImm::new(PrimType::int(32), 0.5, UNKNOWN_LOC).is_err());
1172    /// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
1173    /// ```
1174    ///
1175    /// # Errors
1176    ///
1177    /// Returns a `ValueError` if `ty` is not a scalar floating-point type, or a finite `value` is
1178    /// out of its range.
1179    pub fn new(
1180        ty: impl IntoArg<PrimType>,
1181        value: f64,
1182        loc: impl IntoArg<Location>,
1183    ) -> Result<Self> {
1184        let ty = ty.into_owned();
1185        check_float_imm(&ty, value)?;
1186        Ok(Self::from_fields(loc, ty, value))
1187    }
1188
1189    /// Create the `float32` constant `value` at the unknown location.
1190    pub fn float32(value: f32) -> Self {
1191        Self::builtin(PrimType::float(32), value as f64)
1192    }
1193
1194    /// Create the `float64` constant `value` at the unknown location.
1195    pub fn float64(value: f64) -> Self {
1196        Self::builtin(PrimType::float(64), value)
1197    }
1198
1199    /// [`FloatImm::new`] of a value its type holds, which fails only when the compiler
1200    /// library is not loaded.
1201    fn builtin(ty: PrimType, value: f64) -> Self {
1202        support::infallible(Self::new(ty, value, UNKNOWN_LOC))
1203    }
1204}
1205
1206/// An `f32` is a `float32` constant.
1207impl From<f32> for FloatImm {
1208    fn from(value: f32) -> Self {
1209        Self::float32(value)
1210    }
1211}
1212
1213/// An `f64` is a `float64` constant.
1214impl From<f64> for FloatImm {
1215    fn from(value: f64) -> Self {
1216        Self::float64(value)
1217    }
1218}
1219
1220/// An integer or boolean constant of a scalar integer or boolean type. The value is a [`BigInt`],
1221/// exact at any width.
1222///
1223// tvm-ffi-stubgen(begin): object/ir.IntImm
1224#[allow(missing_docs)]
1225#[repr(C)]
1226#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1227pub struct IntImm {
1228    data_: ObjectArc<IntImmObj>,
1229}
1230
1231/// The object behind [`IntImm`].
1232// Complete: reflected fields fill [40, 56) exactly.
1233#[allow(missing_docs)]
1234#[repr(C)]
1235#[derive(tvm_ffi::derive::Object)]
1236#[object(type_key = "ir.IntImm", final, immutable)]
1237pub struct IntImmObj {
1238    base_: ConstantObj,
1239    pub value: BigInt,
1240}
1241
1242const _: () = {
1243    assert!(::core::mem::size_of::<IntImmObj>() == 56);
1244    assert!(::core::mem::align_of::<IntImmObj>() == 8);
1245};
1246
1247impl Deref for IntImmObj {
1248    type Target = ConstantObj;
1249    fn deref(&self) -> &ConstantObj {
1250        &self.base_
1251    }
1252}
1253
1254#[allow(missing_docs)]
1255impl IntImmObj {
1256    pub(crate) fn new(loc: Location, ty: PrimType, value: BigInt) -> Self {
1257        let base_ = ConstantObj::new(loc, ty.into());
1258        Self { base_, value }
1259    }
1260}
1261
1262#[allow(missing_docs)]
1263impl IntImm {
1264    /// Create a `IntImm` from its field values.
1265    pub fn from_fields(
1266        loc: impl IntoArg<Location>,
1267        ty: impl IntoArg<PrimType>,
1268        value: impl Into<BigInt>,
1269    ) -> Self {
1270        let obj = IntImmObj::new(loc.into_owned(), ty.into_owned(), value.into());
1271        Self { data_: ObjectArc::new(obj) }
1272    }
1273}
1274
1275tvm_ffi::impl_object_ref_upcast!(IntImm => Expr, IntImm => Constant);
1276tvm_ffi::impl_object_ref_upcast!(unsafe IntImm => PrimExpr);
1277// tvm-ffi-stubgen(end)
1278
1279impl IntImm {
1280    /// Create the integer constant `value` of the scalar integer or boolean type `ty`, checked to
1281    /// fit it.
1282    ///
1283    /// ```
1284    /// use tvm_tirx::ir::{IntImm, PrimType, UNKNOWN_LOC};
1285    /// let byte = IntImm::new(PrimType::uint(8), 255, UNKNOWN_LOC)?;
1286    /// assert_eq!(byte.value.to_string(), "255");
1287    /// assert!(IntImm::new(PrimType::uint(8), 256, UNKNOWN_LOC).is_err());
1288    /// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
1289    /// ```
1290    ///
1291    /// # Errors
1292    ///
1293    /// Returns a `ValueError` if `ty` is not a scalar integer or boolean type, or `value` is out of
1294    /// its range.
1295    pub fn new(
1296        ty: impl IntoArg<PrimType>,
1297        value: impl Into<BigInt>,
1298        loc: impl IntoArg<Location>,
1299    ) -> Result<Self> {
1300        let (ty, value) = (ty.into_owned(), value.into());
1301        check_int_imm(&ty, &value)?;
1302        Ok(Self::from_fields(loc, ty, value))
1303    }
1304
1305    /// Create the `int32` constant `value` at the unknown location.
1306    pub fn int32(value: i32) -> Self {
1307        Self::builtin(PrimType::int(32), value)
1308    }
1309
1310    /// Create the `int64` constant `value` at the unknown location.
1311    pub fn int64(value: i64) -> Self {
1312        Self::builtin(PrimType::int(64), value)
1313    }
1314
1315    /// Create the boolean constant `value` at the unknown location.
1316    pub fn bool(value: bool) -> Self {
1317        Self::builtin(PrimType::bool(), value)
1318    }
1319
1320    /// [`IntImm::new`] of a value its type holds, which fails only when the compiler
1321    /// library is not loaded.
1322    fn builtin(ty: PrimType, value: impl Into<BigInt>) -> Self {
1323        support::infallible(Self::new(ty, value, UNKNOWN_LOC))
1324    }
1325}
1326
1327/// An `i32` is an `int32` constant.
1328impl From<i32> for IntImm {
1329    fn from(value: i32) -> Self {
1330        Self::int32(value)
1331    }
1332}
1333
1334/// An `i64` is an `int64` constant.
1335impl From<i64> for IntImm {
1336    fn from(value: i64) -> Self {
1337        Self::int64(value)
1338    }
1339}
1340
1341/// A `bool` is a boolean constant.
1342impl From<bool> for IntImm {
1343    fn from(value: bool) -> Self {
1344        Self::bool(value)
1345    }
1346}
1347
1348/// A constant of any value, with an explicit [`Type`] held apart from the value.
1349///
1350/// Primitive literals have their own constants: integers and booleans are [`IntImm`], floats
1351/// [`FloatImm`] and strings [`StringImm`].
1352///
1353// tvm-ffi-stubgen(begin): object/ir.GenericConst
1354#[allow(missing_docs)]
1355#[repr(C)]
1356#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1357pub struct GenericConst {
1358    data_: ObjectArc<GenericConstObj>,
1359}
1360
1361/// The object behind [`GenericConst`].
1362// Complete: reflected fields fill [40, 56) exactly.
1363#[allow(missing_docs)]
1364#[repr(C)]
1365#[derive(tvm_ffi::derive::Object)]
1366#[object(type_key = "ir.GenericConst", final, immutable)]
1367pub struct GenericConstObj {
1368    base_: ConstantObj,
1369    pub value: Any,
1370}
1371
1372const _: () = {
1373    assert!(::core::mem::size_of::<GenericConstObj>() == 56);
1374    assert!(::core::mem::align_of::<GenericConstObj>() == 8);
1375};
1376
1377impl Deref for GenericConstObj {
1378    type Target = ConstantObj;
1379    fn deref(&self) -> &ConstantObj {
1380        &self.base_
1381    }
1382}
1383
1384#[allow(missing_docs)]
1385impl GenericConstObj {
1386    pub(crate) fn new(loc: Location, ty: Type, value: Any) -> Self {
1387        let base_ = ConstantObj::new(loc, ty);
1388        Self { base_, value }
1389    }
1390}
1391
1392#[allow(missing_docs)]
1393impl GenericConst {
1394    /// Create a `GenericConst` from its field values.
1395    pub fn from_fields(
1396        loc: impl IntoArg<Location>,
1397        ty: impl IntoArg<Type>,
1398        value: impl Into<Any>,
1399    ) -> Self {
1400        let obj = GenericConstObj::new(loc.into_owned(), ty.into_owned(), value.into());
1401        Self { data_: ObjectArc::new(obj) }
1402    }
1403}
1404
1405tvm_ffi::impl_object_ref_upcast!(GenericConst => Expr, GenericConst => Constant);
1406// tvm-ffi-stubgen(end)
1407
1408impl GenericConst {
1409    /// Create the constant `value` of type `ty`, checked to have a type and not to be a primitive
1410    /// literal.
1411    ///
1412    /// # Errors
1413    ///
1414    /// Returns a `TypeError` if `ty` is a [`MissingType`], or `value` is an integer, a boolean, a
1415    /// float or a string.
1416    pub fn new(
1417        ty: impl IntoArg<Type>,
1418        value: impl Into<Any>,
1419        loc: impl IntoArg<Location>,
1420    ) -> Result<Self> {
1421        use TVMFFITypeIndex::*;
1422        let (ty, value) = (ty.into_owned(), value.into());
1423        if ty.downcast_ref::<MissingTypeObj>().is_some() {
1424            let condition = "!ty.as<MissingType>().has_value()";
1425            let message = "GenericConst requires an expression type";
1426            return Err(support::check_failed(tvm_ffi::TYPE_ERROR, condition, message));
1427        }
1428        let primitive =
1429            [kTVMFFIInt, kTVMFFIBigInt, kTVMFFIBool, kTVMFFIFloat, kTVMFFISmallStr, kTVMFFIStr]
1430                .into_iter()
1431                .any(|index| value.type_index() == index as i32);
1432        if primitive {
1433            let condition = "!value.as<ffi::BigInt>() && !value.as<bool>() && !value.as<double>() && \
1434                             !value.as<ffi::String>()";
1435            let message = "Primitive literals use IntImm, FloatImm, or StringImm";
1436            return Err(support::check_failed(tvm_ffi::TYPE_ERROR, condition, message));
1437        }
1438        Ok(Self::from_fields(loc, ty, value))
1439    }
1440}
1441
1442/// A data type as a constant, of type [`AnyType`].
1443///
1444// tvm-ffi-stubgen(begin): object/ir.DataTypeImm
1445#[allow(missing_docs)]
1446#[repr(C)]
1447#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1448pub struct DataTypeImm {
1449    data_: ObjectArc<DataTypeImmObj>,
1450}
1451
1452/// The object behind [`DataTypeImm`].
1453// Complete: reflected fields fill [40, 48) exactly (alignment padding [44, 48)).
1454#[allow(missing_docs)]
1455#[repr(C)]
1456#[derive(tvm_ffi::derive::Object)]
1457#[object(type_key = "ir.DataTypeImm", final, immutable)]
1458pub struct DataTypeImmObj {
1459    base_: ConstantObj,
1460    pub value: DLDataType,
1461}
1462
1463const _: () = {
1464    assert!(::core::mem::size_of::<DataTypeImmObj>() == 48);
1465    assert!(::core::mem::align_of::<DataTypeImmObj>() == 8);
1466};
1467
1468impl Deref for DataTypeImmObj {
1469    type Target = ConstantObj;
1470    fn deref(&self) -> &ConstantObj {
1471        &self.base_
1472    }
1473}
1474
1475#[allow(missing_docs)]
1476impl DataTypeImmObj {
1477    pub(crate) fn new(loc: Location, ty: Type, value: DLDataType) -> Self {
1478        let base_ = ConstantObj::new(loc, ty);
1479        Self { base_, value }
1480    }
1481}
1482
1483#[allow(missing_docs)]
1484impl DataTypeImm {
1485    /// Create a `DataTypeImm` from its field values.
1486    pub fn from_fields(
1487        loc: impl IntoArg<Location>,
1488        ty: impl IntoArg<Type>,
1489        value: impl Into<DLDataType>,
1490    ) -> Self {
1491        let obj = DataTypeImmObj::new(loc.into_owned(), ty.into_owned(), value.into());
1492        Self { data_: ObjectArc::new(obj) }
1493    }
1494}
1495
1496tvm_ffi::impl_object_ref_upcast!(DataTypeImm => Expr, DataTypeImm => Constant);
1497// tvm-ffi-stubgen(end)
1498
1499impl DataTypeImm {
1500    /// Create the data type `value` as a constant of type [`AnyType`].
1501    pub fn new(value: DLDataType, loc: impl IntoArg<Location>) -> Self {
1502        let ty = AnyType::new(UNKNOWN_LOC);
1503        Self::from_fields(loc, ty, value)
1504    }
1505}
1506
1507/// A string constant, of type [`StringType`].
1508///
1509// tvm-ffi-stubgen(begin): object/ir.StringImm
1510#[allow(missing_docs)]
1511#[repr(C)]
1512#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1513pub struct StringImm {
1514    data_: ObjectArc<StringImmObj>,
1515}
1516
1517/// The object behind [`StringImm`].
1518// Complete: reflected fields fill [40, 56) exactly.
1519#[allow(missing_docs)]
1520#[repr(C)]
1521#[derive(tvm_ffi::derive::Object)]
1522#[object(type_key = "ir.StringImm", final, immutable)]
1523pub struct StringImmObj {
1524    base_: ConstantObj,
1525    pub value: String,
1526}
1527
1528const _: () = {
1529    assert!(::core::mem::size_of::<StringImmObj>() == 56);
1530    assert!(::core::mem::align_of::<StringImmObj>() == 8);
1531};
1532
1533impl Deref for StringImmObj {
1534    type Target = ConstantObj;
1535    fn deref(&self) -> &ConstantObj {
1536        &self.base_
1537    }
1538}
1539
1540#[allow(missing_docs)]
1541impl StringImmObj {
1542    pub(crate) fn new(loc: Location, ty: Type, value: String) -> Self {
1543        let base_ = ConstantObj::new(loc, ty);
1544        Self { base_, value }
1545    }
1546}
1547
1548#[allow(missing_docs)]
1549impl StringImm {
1550    /// Create a `StringImm` from its field values.
1551    pub fn from_fields(
1552        loc: impl IntoArg<Location>,
1553        ty: impl IntoArg<Type>,
1554        value: impl Into<String>,
1555    ) -> Self {
1556        let obj = StringImmObj::new(loc.into_owned(), ty.into_owned(), value.into());
1557        Self { data_: ObjectArc::new(obj) }
1558    }
1559}
1560
1561tvm_ffi::impl_object_ref_upcast!(StringImm => Expr, StringImm => Constant);
1562// tvm-ffi-stubgen(end)
1563
1564impl StringImm {
1565    /// Create the string constant `value`, of type [`StringType`].
1566    pub fn new(value: &str, loc: impl IntoArg<Location>) -> Self {
1567        let ty = StringType::new();
1568        Self::from_fields(loc.into_owned(), ty, String::from(value))
1569    }
1570}
1571
1572/// The call of `op` on `args`.
1573///
1574/// `op` is a registered [`Op`](crate::ir::Op), a [`GlobalVar`], or another callable expression;
1575/// `attrs` holds operator-specific attributes and `ty_args` explicit type arguments. The type of
1576/// the call is its result type, which [`Call::new`] infers when none is given.
1577///
1578// tvm-ffi-stubgen(begin): object/ir.Call
1579#[allow(missing_docs)]
1580#[repr(C)]
1581#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1582pub struct Call {
1583    data_: ObjectArc<CallObj>,
1584}
1585
1586/// The object behind [`Call`].
1587// Complete: reflected fields fill [40, 72) exactly.
1588#[allow(missing_docs)]
1589#[repr(C)]
1590#[derive(tvm_ffi::derive::Object)]
1591#[object(type_key = "ir.Call", final, immutable)]
1592pub struct CallObj {
1593    base_: ExprObj,
1594    pub op: Expr,
1595    pub args: Array<Expr>,
1596    pub attrs: Option<Attrs>,
1597    pub ty_args: Array<Type>,
1598}
1599
1600const _: () = {
1601    assert!(::core::mem::size_of::<CallObj>() == 72);
1602    assert!(::core::mem::align_of::<CallObj>() == 8);
1603};
1604
1605impl Deref for CallObj {
1606    type Target = ExprObj;
1607    fn deref(&self) -> &ExprObj {
1608        &self.base_
1609    }
1610}
1611
1612#[allow(missing_docs)]
1613impl CallObj {
1614    pub(crate) fn new(
1615        loc: Location,
1616        ty: Type,
1617        op: Expr,
1618        args: Array<Expr>,
1619        attrs: Option<Attrs>,
1620        ty_args: Array<Type>,
1621    ) -> Self {
1622        let base_ = ExprObj::new(loc, ty);
1623        Self { base_, op, args, attrs, ty_args }
1624    }
1625}
1626
1627#[allow(missing_docs)]
1628impl Call {
1629    /// Create a `Call` from its field values.
1630    pub fn from_fields(
1631        loc: impl IntoArg<Location>,
1632        ty: impl IntoArg<Type>,
1633        op: impl IntoArg<Expr>,
1634        args: impl Into<Array<Expr>>,
1635        attrs: impl Into<Option<Attrs>>,
1636        ty_args: impl Into<Array<Type>>,
1637    ) -> Self {
1638        let obj = CallObj::new(
1639            loc.into_owned(),
1640            ty.into_owned(),
1641            op.into_owned(),
1642            args.into(),
1643            attrs.into(),
1644            ty_args.into(),
1645        );
1646        Self { data_: ObjectArc::new(obj) }
1647    }
1648}
1649
1650tvm_ffi::impl_object_ref_upcast!(Call => Expr);
1651// tvm-ffi-stubgen(end)
1652
1653impl Call {
1654    /// Create the call of `op` on `args`, of type `ty` or the type
1655    /// [`reinfer_type`](Self::reinfer_type) gives it when `None`.
1656    ///
1657    /// The call is not validated; [`validate`](Self::validate) checks it.
1658    ///
1659    /// # Errors
1660    ///
1661    /// Returns the error of the type inference when `ty` is `None`.
1662    pub fn new(
1663        ty: Option<&Type>,
1664        op: impl IntoExpr,
1665        args: impl IntoIterator<Item = impl IntoExpr>,
1666        attrs: Option<&Attrs>,
1667        ty_args: impl IntoIterator<Item = impl IntoArg<Type>>,
1668        loc: impl IntoArg<Location>,
1669    ) -> Result<Self> {
1670        let (op, attrs, loc) = (op.into_owned_expr()?, attrs.cloned(), loc.into_owned());
1671        let args =
1672            args.into_iter().map(IntoExpr::into_owned_expr).collect::<Result<Array<Expr>>>()?;
1673        let ty_args = ty_args.into_iter().map(IntoArg::into_owned).collect::<Array<Type>>();
1674        if let Some(ty) = ty {
1675            return Ok(Self::from_fields(loc, ty.clone(), op, args, attrs, ty_args));
1676        }
1677        let call = Self::from_fields(loc, MissingType::new(), op, args, attrs, ty_args);
1678        let ty = call.reinfer_type()?;
1679        Ok(Self::from_fields(
1680            call.loc.clone(),
1681            ty,
1682            call.op.clone(),
1683            call.args.clone(),
1684            call.attrs.clone(),
1685            call.ty_args.clone(),
1686        ))
1687    }
1688
1689    /// Check the call against the contract its operator registered: the operator's validator, if it
1690    /// has one.
1691    ///
1692    /// # Errors
1693    ///
1694    /// Returns the error the validator raises.
1695    pub fn validate(&self) -> Result<()> {
1696        let Some(op) = self.op.downcast_ref::<OpObj>() else { return Ok(()) };
1697        if op.validator().is_none() {
1698            return Ok(());
1699        }
1700        // SAFETY: an operator validator is a `void(const CallObj*)` hook.
1701        let validate: NativeFunction<(&CallObj,)> =
1702            unsafe { NativeFunction::from_any(op.validator().clone())? };
1703        validate.call((&**self,))
1704    }
1705
1706    /// Return the result type the operator infers from the current inputs, without changing the
1707    /// call.
1708    ///
1709    /// # Errors
1710    ///
1711    /// Returns the error of the operator's `FInferType`, or a `TypeError` if its `TFixedReturnType`
1712    /// is not a type.
1713    pub fn reinfer_type(&self) -> Result<Type> {
1714        let Some(op) = self.op.downcast_ref::<OpObj>() else {
1715            return match self.op.ty.downcast_ref::<FuncTypeObj>() {
1716                Some(func_type) => Ok(func_type.ret_type.clone()),
1717                None => Ok(MissingType::new().into()),
1718            };
1719        };
1720        if let Some(fixed) = support::op_attr(op, "TFixedReturnType")? {
1721            return fixed.try_into();
1722        }
1723        // SAFETY: `FInferType` holds `Type(const CallObj*)` hooks.
1724        match unsafe { support::op_hook::<(&CallObj,), Type>(op, "FInferType")? } {
1725            Some(infer) => infer.call((&**self,)),
1726            None => Ok(MissingType::new().into()),
1727        }
1728    }
1729}
1730
1731/// The region of `source` that the ranges `region` select, such as a slice of a tensor, of the
1732/// type it is created with.
1733///
1734// tvm-ffi-stubgen(begin): object/ir.TensorRegion
1735#[allow(missing_docs)]
1736#[repr(C)]
1737#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1738pub struct TensorRegion {
1739    data_: ObjectArc<TensorRegionObj>,
1740}
1741
1742/// The object behind [`TensorRegion`].
1743// Complete: reflected fields fill [40, 56) exactly.
1744#[allow(missing_docs)]
1745#[repr(C)]
1746#[derive(tvm_ffi::derive::Object)]
1747#[object(type_key = "ir.TensorRegion", final, immutable)]
1748pub struct TensorRegionObj {
1749    base_: ExprObj,
1750    pub source: Expr,
1751    pub region: Array<Range>,
1752}
1753
1754const _: () = {
1755    assert!(::core::mem::size_of::<TensorRegionObj>() == 56);
1756    assert!(::core::mem::align_of::<TensorRegionObj>() == 8);
1757};
1758
1759impl Deref for TensorRegionObj {
1760    type Target = ExprObj;
1761    fn deref(&self) -> &ExprObj {
1762        &self.base_
1763    }
1764}
1765
1766#[allow(missing_docs)]
1767impl TensorRegionObj {
1768    pub(crate) fn new(loc: Location, ty: Type, source: Expr, region: Array<Range>) -> Self {
1769        let base_ = ExprObj::new(loc, ty);
1770        Self { base_, source, region }
1771    }
1772}
1773
1774#[allow(missing_docs)]
1775impl TensorRegion {
1776    /// Create a `TensorRegion` from its field values.
1777    pub fn from_fields(
1778        loc: impl IntoArg<Location>,
1779        ty: impl IntoArg<Type>,
1780        source: impl IntoArg<Expr>,
1781        region: impl Into<Array<Range>>,
1782    ) -> Self {
1783        let obj = TensorRegionObj::new(
1784            loc.into_owned(),
1785            ty.into_owned(),
1786            source.into_owned(),
1787            region.into(),
1788        );
1789        Self { data_: ObjectArc::new(obj) }
1790    }
1791}
1792
1793tvm_ffi::impl_object_ref_upcast!(TensorRegion => Expr);
1794// tvm-ffi-stubgen(end)
1795
1796impl TensorRegion {
1797    /// Create the region `region` of `source`, of type `ty`.
1798    pub fn new(
1799        source: impl IntoArg<Expr>,
1800        region: impl Into<Array<Range>>,
1801        ty: impl IntoArg<Type>,
1802        loc: impl IntoArg<Location>,
1803    ) -> Self {
1804        Self::from_fields(loc, ty, source, region)
1805    }
1806}
1807
1808/// A local variable.
1809///
1810/// A variable is identified by the object itself: two variables named alike are distinct, and
1811/// `name` is a hint for printing that structural equality and hashing ignore. A variable of a
1812/// [`PrimType`] is checked into a [`PrimVar`] to take part in arithmetic.
1813///
1814// tvm-ffi-stubgen(begin): object/ir.Var
1815#[allow(missing_docs)]
1816#[repr(C)]
1817#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1818pub struct Var {
1819    data_: ObjectArc<VarObj>,
1820}
1821
1822/// The object behind [`Var`].
1823// Complete: reflected fields fill [40, 56) exactly.
1824#[allow(missing_docs)]
1825#[repr(C)]
1826#[derive(tvm_ffi::derive::Object)]
1827#[object(type_key = "ir.Var", immutable, rs_parent)]
1828pub struct VarObj {
1829    base_: ExprObj,
1830    pub name: String,
1831}
1832
1833const _: () = {
1834    assert!(::core::mem::size_of::<VarObj>() == 56);
1835    assert!(::core::mem::align_of::<VarObj>() == 8);
1836};
1837
1838impl Deref for VarObj {
1839    type Target = ExprObj;
1840    fn deref(&self) -> &ExprObj {
1841        &self.base_
1842    }
1843}
1844
1845#[allow(missing_docs)]
1846impl VarObj {
1847    pub fn new(loc: Location, ty: Type, name: String) -> Self {
1848        let base_ = ExprObj::new(loc, ty);
1849        Self { base_, name }
1850    }
1851}
1852
1853tvm_ffi::impl_object_ref_upcast!(Var => Expr);
1854// tvm-ffi-stubgen(end)
1855
1856impl Var {
1857    /// Create the variable `name` of type `ty`; a variable whose type is not known yet takes
1858    /// [`MissingType::new`].
1859    pub fn new(name: &str, ty: impl IntoArg<Type>, loc: impl IntoArg<Location>) -> Self {
1860        let obj = VarObj::new(loc.into_owned(), ty.into_owned(), String::from(name));
1861        Self { data_: ObjectArc::new(obj) }
1862    }
1863}
1864
1865/// A [`Var`] typed by a `PrimType`: a scalar or vector variable, which takes part in arithmetic
1866/// as a [`PrimExpr`].
1867///
1868/// A `PrimVar` is a typed `Var`, as [`PrimExpr`] is a typed `Expr`: [`PrimVar::new`] types it
1869/// by a `PrimType`, and a `Var` becomes one only once checked to have a `PrimType`, by
1870/// `downcast_ref`, which borrows it in place, or `downcast`, which takes it. It converts into a
1871/// `Var`, a `PrimExpr` and an `Expr` for free, and reads the variable through `Deref`.
1872///
1873/// # Examples
1874///
1875/// ```
1876/// use tvm_tirx::ir::{MissingType, PrimExpr, PrimType, PrimVar, Var, UNKNOWN_LOC};
1877/// use tvm_tirx::script::script;
1878/// use tvm_tirx::tvm_ffi::{ObjectRefCore};
1879///
1880/// let i = PrimVar::new("i", PrimType::int(32), UNKNOWN_LOC);
1881/// assert_eq!(i.name.as_str(), "i");
1882/// assert_eq!(script(&PrimExpr::try_from(&i * 4 + 1)?)?, "i * 4 + 1");
1883///
1884/// let var: Var = i.into();
1885/// assert!(var.downcast_ref::<PrimVar>().is_some());
1886/// let untyped = Var::new("u", MissingType::new(), UNKNOWN_LOC);
1887/// assert!(untyped.downcast::<PrimVar>().is_err());
1888/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
1889/// ```
1890///
1891/// A `Var` takes no part in arithmetic until it is checked:
1892///
1893/// ```compile_fail
1894/// # use tvm_tirx::ir::{PrimType, Var, UNKNOWN_LOC};
1895/// let x = Var::new("x", PrimType::int(32), UNKNOWN_LOC);
1896/// let _ = &x + 1;
1897/// ```
1898#[repr(transparent)]
1899#[derive(Clone, tvm_ffi::derive::ObjectRef)]
1900#[object_ref(parent = Var, skip_any_compatible)]
1901pub struct PrimVar {
1902    data_: ObjectArc<VarObj>,
1903}
1904
1905// SAFETY: a `PrimVar` is a `Var` typed by a `PrimType`; nothing else converts into one.
1906unsafe impl tvm_ffi::object::ObjectRefAnyCompatible for PrimVar {
1907    #[inline]
1908    fn extra_check(obj: &VarObj) -> bool {
1909        obj.ty.downcast_ref::<PrimTypeObj>().is_some()
1910    }
1911
1912    fn custom_type_str() -> std::string::String {
1913        "ir.Var".into()
1914    }
1915}
1916
1917crate::def_expr_op_over_loads!(PrimVar);
1918
1919impl PrimVar {
1920    /// Return the type of this expression, the [`PrimType`] its check guarantees.
1921    pub fn prim_ty(&self) -> &PrimType {
1922        self.data_.ty.downcast_ref::<PrimType>().expect("a typed expression has a `PrimType`")
1923    }
1924}
1925
1926tvm_ffi::impl_object_ref_upcast!(PrimVar => Expr);
1927tvm_ffi::impl_object_ref_upcast!(unsafe PrimVar => PrimExpr);
1928
1929impl PrimVar {
1930    /// Create the variable `name` of the primitive type `ty`.
1931    pub fn new(name: &str, ty: impl IntoArg<PrimType>, loc: impl IntoArg<Location>) -> Self {
1932        Var::new(name, ty.into_owned(), loc)
1933            .downcast()
1934            .expect("a variable of a `PrimType` is a `PrimVar`")
1935    }
1936}
1937
1938/// A function of `vars` that evaluates to `body`, such as a reduction combiner or a predication
1939/// rule.
1940///
1941/// Its type is the [`FuncType`] from the types of `vars` to the type of `body`, and
1942/// [`apply`](LambdaExpr::apply) substitutes arguments for the variables. It is a
1943/// [`StagingExpr`]: compilation eliminates it.
1944///
1945// tvm-ffi-stubgen(begin): object/ir.LambdaExpr
1946#[allow(missing_docs)]
1947#[repr(C)]
1948#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1949pub struct LambdaExpr {
1950    data_: ObjectArc<LambdaExprObj>,
1951}
1952
1953/// The object behind [`LambdaExpr`].
1954// Complete: reflected fields fill [40, 56) exactly.
1955#[allow(missing_docs)]
1956#[repr(C)]
1957#[derive(tvm_ffi::derive::Object)]
1958#[object(type_key = "ir.LambdaExpr", final, immutable)]
1959pub struct LambdaExprObj {
1960    base_: StagingExprObj,
1961    pub vars: Array<Var>,
1962    pub body: Expr,
1963}
1964
1965const _: () = {
1966    assert!(::core::mem::size_of::<LambdaExprObj>() == 56);
1967    assert!(::core::mem::align_of::<LambdaExprObj>() == 8);
1968};
1969
1970impl Deref for LambdaExprObj {
1971    type Target = StagingExprObj;
1972    fn deref(&self) -> &StagingExprObj {
1973        &self.base_
1974    }
1975}
1976
1977#[allow(missing_docs)]
1978impl LambdaExprObj {
1979    pub(crate) fn new(loc: Location, ty: Type, vars: Array<Var>, body: Expr) -> Self {
1980        let base_ = StagingExprObj::new(loc, ty);
1981        Self { base_, vars, body }
1982    }
1983}
1984
1985#[allow(missing_docs)]
1986impl LambdaExpr {
1987    /// Create a `LambdaExpr` from its field values.
1988    pub fn from_fields(
1989        loc: impl IntoArg<Location>,
1990        ty: impl IntoArg<Type>,
1991        vars: impl Into<Array<Var>>,
1992        body: impl IntoArg<Expr>,
1993    ) -> Self {
1994        let obj =
1995            LambdaExprObj::new(loc.into_owned(), ty.into_owned(), vars.into(), body.into_owned());
1996        Self { data_: ObjectArc::new(obj) }
1997    }
1998}
1999
2000tvm_ffi::impl_object_ref_upcast!(LambdaExpr => Expr, LambdaExpr => StagingExpr);
2001// tvm-ffi-stubgen(end)
2002
2003impl LambdaExpr {
2004    /// Create the lambda of `vars` that evaluates to `body`, of the function type from the types of
2005    /// `vars` to the type of `body`.
2006    pub fn new(
2007        vars: impl IntoIterator<Item = impl IntoArg<Var>>,
2008        body: impl IntoArg<Expr>,
2009        loc: impl IntoArg<Location>,
2010    ) -> Self {
2011        let (vars, body) =
2012            (vars.into_iter().map(IntoArg::into_owned).collect::<Array<Var>>(), body.into_owned());
2013        let arg_types = vars.iter().map(|var| var.ty.clone()).collect::<Vec<Type>>();
2014        let ty = FuncType::new(arg_types, body.ty.clone());
2015        Self::from_fields(loc.into_owned(), ty, vars, body)
2016    }
2017
2018    /// Return the body with `arguments` substituted for the variables (`ir.LambdaExprApply`).
2019    ///
2020    /// # Errors
2021    ///
2022    /// Returns a `ValueError` if the number of arguments is not the number of variables.
2023    pub fn apply(&self, arguments: impl IntoIterator<Item = impl IntoExpr>) -> Result<Expr> {
2024        let arguments = arguments
2025            .into_iter()
2026            .map(IntoExpr::into_owned_expr)
2027            .collect::<Result<Array<Expr>>>()?;
2028        tvm_ffi::cached_global_func!("ir.LambdaExprApply")
2029            .call_tuple((self, &arguments))?
2030            .try_into()
2031    }
2032}
2033
2034/// The half-open interval `[begin, begin + extent)`.
2035///
2036/// [`Range::new`] takes the end and folds the extent; [`Range::from_min_extent`] takes the extent.
2037///
2038/// # Examples
2039///
2040/// ```
2041/// use tvm_tirx::ir::{PrimType, PrimVar, Range, UNKNOWN_LOC};
2042/// use tvm_tirx::script::script;
2043///
2044/// let i = PrimVar::new("i", PrimType::int(32), UNKNOWN_LOC);
2045/// let range = Range::new(&i, &i + 4, UNKNOWN_LOC)?;
2046/// assert_eq!(script(&range.extent)?, "4");
2047/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
2048/// ```
2049///
2050// tvm-ffi-stubgen(begin): object/ir.Range
2051#[allow(missing_docs)]
2052#[repr(C)]
2053#[derive(tvm_ffi::derive::ObjectRef, Clone)]
2054pub struct Range {
2055    data_: ObjectArc<RangeObj>,
2056}
2057
2058/// The object behind [`Range`].
2059// Complete: reflected fields fill [24, 48) exactly.
2060#[allow(missing_docs)]
2061#[repr(C)]
2062#[derive(tvm_ffi::derive::Object)]
2063#[object(type_key = "ir.Range", final, immutable)]
2064pub struct RangeObj {
2065    base_: Object,
2066    pub begin: PrimExpr,
2067    pub extent: PrimExpr,
2068    pub loc: Location,
2069}
2070
2071const _: () = {
2072    assert!(::core::mem::size_of::<RangeObj>() == 48);
2073    assert!(::core::mem::align_of::<RangeObj>() == 8);
2074};
2075
2076#[allow(missing_docs)]
2077impl RangeObj {
2078    pub(crate) fn new(begin: PrimExpr, extent: PrimExpr, loc: Location) -> Self {
2079        let base_ = Object::new();
2080        Self { base_, begin, extent, loc }
2081    }
2082}
2083
2084#[allow(missing_docs)]
2085impl Range {
2086    /// Create a `Range` from its field values.
2087    pub fn from_fields(
2088        begin: impl IntoArg<PrimExpr>,
2089        extent: impl IntoArg<PrimExpr>,
2090        loc: impl IntoArg<Location>,
2091    ) -> Self {
2092        let obj = RangeObj::new(begin.into_owned(), extent.into_owned(), loc.into_owned());
2093        Self { data_: ObjectArc::new(obj) }
2094    }
2095}
2096// tvm-ffi-stubgen(end)
2097
2098impl Range {
2099    /// Create the range `[begin, end)`; [`from_min_extent`](Self::from_min_extent) takes the
2100    /// extent instead of the end.
2101    pub fn new(
2102        begin: impl IntoExpr<PrimExpr>,
2103        end: impl IntoExpr<PrimExpr>,
2104        loc: impl IntoArg<Location>,
2105    ) -> Result<Self> {
2106        let (begin, end) = (begin.into_owned_expr()?, end.into_owned_expr()?);
2107        let extent = Self::get_extent_from_begin_end(&begin, end)?;
2108        Ok(Self::from_fields(begin, extent, loc.into_owned()))
2109    }
2110
2111    /// Create the range of `extent` values from `min_value`.
2112    pub fn from_min_extent(
2113        min_value: impl IntoExpr<PrimExpr>,
2114        extent: impl IntoExpr<PrimExpr>,
2115        loc: impl IntoArg<Location>,
2116    ) -> Result<Self> {
2117        let (min_value, extent) = (min_value.into_owned_expr()?, extent.into_owned_expr()?);
2118        Ok(Self::from_fields(min_value, extent, loc.into_owned()))
2119    }
2120
2121    /// Return the extent `end - begin` of the range `[begin, end)`, folded.
2122    pub fn get_extent_from_begin_end(
2123        begin: impl IntoExpr<PrimExpr>,
2124        end: impl IntoExpr<PrimExpr>,
2125    ) -> Result<PrimExpr> {
2126        let (begin, end) = (begin.into_owned_expr()?, end.into_owned_expr()?);
2127        if let Some(add) = end.downcast_ref::<AddObj>() {
2128            if crate::ir::prim::expr_deep_equal(&add.a, &begin)? {
2129                return Ok(add.b.clone());
2130            }
2131            if crate::ir::prim::expr_deep_equal(&add.b, &begin)? {
2132                return Ok(add.a.clone());
2133            }
2134        }
2135        let is_zero =
2136            begin.downcast_ref::<IntImmObj>().is_some_and(|imm| imm.value == BigInt::from(0i64));
2137        match is_zero {
2138            true => Ok(end),
2139            false => crate::ir::prim::op::sub(end, begin),
2140        }
2141    }
2142}
2143
2144// The operators apply to the expressions typed by a `PrimType`, the subtypes of `PrimExpr`, as the
2145// C++ operators take `PrimExpr`; the typed expressions get theirs where they are defined. An `Expr`, a
2146// `Var` or a `Call` is checked first, with `downcast_ref` or `downcast`.
2147crate::def_expr_op_over_loads!(IntImm);
2148crate::def_expr_op_over_loads!(FloatImm);
2149crate::def_expr_op_over_loads!(TensorLoad);
2150
2151// Primitive operator and vector reference classes inherit C++ PrimExpr.
2152crate::def_expr_op_over_loads!(crate::ir::prim::Cast);
2153crate::def_expr_op_over_loads!(crate::ir::prim::LShift);
2154crate::def_expr_op_over_loads!(crate::ir::prim::RShift);
2155crate::def_expr_op_over_loads!(crate::ir::prim::BitwiseAnd);
2156crate::def_expr_op_over_loads!(crate::ir::prim::BitwiseOr);
2157crate::def_expr_op_over_loads!(crate::ir::prim::BitwiseXor);
2158crate::def_expr_op_over_loads!(crate::ir::prim::BitwiseNot);
2159crate::def_expr_op_over_loads!(crate::ir::prim::Add);
2160crate::def_expr_op_over_loads!(crate::ir::prim::Sub);
2161crate::def_expr_op_over_loads!(crate::ir::prim::Mul);
2162crate::def_expr_op_over_loads!(crate::ir::prim::Div);
2163crate::def_expr_op_over_loads!(crate::ir::prim::Mod);
2164crate::def_expr_op_over_loads!(crate::ir::prim::FloorDiv);
2165crate::def_expr_op_over_loads!(crate::ir::prim::FloorMod);
2166crate::def_expr_op_over_loads!(crate::ir::prim::Min);
2167crate::def_expr_op_over_loads!(crate::ir::prim::Max);
2168crate::def_expr_op_over_loads!(crate::ir::prim::EQ);
2169crate::def_expr_op_over_loads!(crate::ir::prim::NE);
2170crate::def_expr_op_over_loads!(crate::ir::prim::LT);
2171crate::def_expr_op_over_loads!(crate::ir::prim::LE);
2172crate::def_expr_op_over_loads!(crate::ir::prim::GT);
2173crate::def_expr_op_over_loads!(crate::ir::prim::GE);
2174crate::def_expr_op_over_loads!(crate::ir::prim::And);
2175crate::def_expr_op_over_loads!(crate::ir::prim::Or);
2176crate::def_expr_op_over_loads!(crate::ir::prim::Not);
2177crate::def_expr_op_over_loads!(crate::ir::prim::Select);
2178crate::def_expr_op_over_loads!(crate::ir::prim::Let);
2179crate::def_expr_op_over_loads!(crate::ir::prim::Ramp);
2180crate::def_expr_op_over_loads!(crate::ir::prim::Broadcast);
2181crate::def_expr_op_over_loads!(crate::ir::prim::Shuffle);
2182
2183// These symbolic reference classes also inherit C++ PrimExpr; attaching operators only forwards
2184// their handles.
2185crate::def_expr_op_over_loads!(crate::sym::iter_affine_map::IterMapExpr);
2186crate::def_expr_op_over_loads!(crate::sym::iter_affine_map::IterSplitExpr);
2187crate::def_expr_op_over_loads!(crate::sym::iter_affine_map::IterSumExpr);
2188
2189// ---------------------------------------------------------------------------------------------
2190// What the constant constructors check
2191
2192/// The checks of [`FloatImm::new`]: a scalar floating-point type whose range holds a finite
2193/// `value`.
2194fn check_float_imm(ty: &PrimType, value: f64) -> Result<()> {
2195    use support::{check_failed, compare_failed, CppDouble};
2196    use tvm_ffi::DLDataTypeCode::{kDLBfloat, kDLFloat, kDLFloat4_e2m1fn};
2197    use tvm_ffi::VALUE_ERROR;
2198    /// `ffi::DLExtDataTypeCode::kDLExtCustomBegin`.
2199    const CUSTOM_BEGIN: u8 = 129;
2200    let dtype = ty.dtype;
2201    if ty.is_scalable_vector() || ty.is_fixed_length_vector() {
2202        let condition = "!value_ty.IsScalableVector() && !value_ty.IsFixedLengthVector()";
2203        return Err(check_failed(VALUE_ERROR, condition, "FloatImm can only take scalar."));
2204    }
2205    let (code, bits) = (dtype.code, ty.bits());
2206    let float8 = support::float8_bound(code);
2207    let float6 = support::float6_bound(code);
2208    let supported = ty.matches_code(&[kDLFloat])
2209        || float8.is_some()
2210        || float6.is_some()
2211        || (ty.matches_code(&[kDLBfloat]) && bits == 16)
2212        || (ty.matches_code(&[kDLFloat4_e2m1fn]) && bits == 4)
2213        || code >= CUSTOM_BEGIN;
2214    let name = || support::dtype_name(dtype);
2215    if !supported {
2216        let condition = "value_ty.MatchesCode(DLDataTypeCode::kDLFloat, \
2217                         DLDataTypeCode::kDLFloat8_e3m4, DLDataTypeCode::kDLFloat8_e4m3, \
2218                         DLDataTypeCode::kDLFloat8_e4m3b11fnuz, DLDataTypeCode::kDLFloat8_e4m3fn, \
2219                         DLDataTypeCode::kDLFloat8_e4m3fnuz, DLDataTypeCode::kDLFloat8_e5m2, \
2220                         DLDataTypeCode::kDLFloat8_e5m2fnuz, DLDataTypeCode::kDLFloat8_e8m0fnu, \
2221                         DLDataTypeCode::kDLFloat6_e2m3fn, DLDataTypeCode::kDLFloat6_e3m2fn) || \
2222                         value_ty.MatchesElementType(DLDataTypeCode::kDLBfloat, 16) || \
2223                         value_ty.MatchesElementType(DLDataTypeCode::kDLFloat4_e2m1fn, 4) || \
2224                         static_cast<int>(code) >= \
2225                         static_cast<int>(ffi::DLExtDataTypeCode::kDLExtCustomBegin)";
2226        let message = format!("FloatImm supports only float, but {} was supplied.", name());
2227        return Err(check_failed(VALUE_ERROR, condition, &message));
2228    }
2229    if value.is_infinite() || value.is_nan() {
2230        return Ok(());
2231    }
2232    // The bound checked from below and how its message says so, and the bound from above.
2233    let (low, high): ((&str, f64, &str), (&str, f64)) = if bits == 32 {
2234        (
2235            (
2236                "value >= std::numeric_limits<float>::lowest()",
2237                f32::MIN as f64,
2238                "exceeds minimum of",
2239            ),
2240            ("value <= std::numeric_limits<float>::max()", f32::MAX as f64),
2241        )
2242    } else if ty.matches_code(&[kDLFloat]) && bits == 16 {
2243        (
2244            ("value >= -support::kMaxFloat16", -support::MAX_FLOAT16, "exceeds minimum of"),
2245            ("value <= support::kMaxFloat16", support::MAX_FLOAT16),
2246        )
2247    } else if ty.matches_code(&[kDLBfloat]) && bits == 16 {
2248        (
2249            ("value >= -support::kMaxBFloat16", -support::MAX_BFLOAT16, "exceeds minimum of"),
2250            ("value <= support::kMaxBFloat16", support::MAX_BFLOAT16),
2251        )
2252    } else if let Some((bound, nonneg)) = float8 {
2253        let low = match nonneg {
2254            true => ("value >= 0", 0.0, "below zero for unsigned"),
2255            false => ("value >= -bound", -bound, "below minimum of"),
2256        };
2257        (low, ("value <= bound", bound))
2258    } else if let Some(bound) = float6 {
2259        (("value >= -bound", -bound, "below minimum of"), ("value <= bound", bound))
2260    } else if ty.matches_code(&[kDLFloat4_e2m1fn]) {
2261        (("value >= -bound", -6.0, "below minimum of"), ("value <= bound", 6.0))
2262    } else {
2263        return Ok(());
2264    };
2265    let failed = |condition: &str, bound: f64, what: &str| {
2266        let message = format!("Literal value {} {what} {}", CppDouble(value), name());
2267        compare_failed(VALUE_ERROR, condition, CppDouble(value), CppDouble(bound), &message)
2268    };
2269    if value < low.1 {
2270        return Err(failed(low.0, low.1, low.2));
2271    }
2272    if value > high.1 {
2273        return Err(failed(high.0, high.1, "exceeds maximum of"));
2274    }
2275    Ok(())
2276}
2277
2278/// The checks of [`IntImm::new`]: a scalar integer or boolean type whose range holds `value`. The messages are built only when a check fails.
2279fn check_int_imm(ty: &PrimType, value: &BigInt) -> Result<()> {
2280    use support::{check_failed, compare_failed};
2281    use tvm_ffi::DLDataTypeCode::{kDLBool, kDLInt, kDLUInt};
2282    use tvm_ffi::VALUE_ERROR;
2283    let dtype = ty.dtype;
2284    let name = || support::dtype_name(dtype);
2285    if ty.is_scalable_vector() || ty.is_fixed_length_vector() {
2286        let condition = "!value_ty.IsScalableVector() && !value_ty.IsFixedLengthVector()";
2287        let message = format!("IntImm can only take scalar, but {} was supplied.", name());
2288        return Err(check_failed(VALUE_ERROR, condition, &message));
2289    }
2290    if !ty.matches_code(&[kDLInt, kDLUInt, kDLBool]) {
2291        let condition = "value_ty.MatchesCode(DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt, \
2292                         DLDataTypeCode::kDLBool)";
2293        let message =
2294            format!("IntImm supports only int or uint or bool type, but {} was supplied.", name());
2295        return Err(check_failed(VALUE_ERROR, condition, &message));
2296    }
2297    let bits = u32::from(ty.bits());
2298    if bits == 0 {
2299        let message = "IntImm requires a positive integer width";
2300        return Err(compare_failed(VALUE_ERROR, "bits > 0", bits, 0, message));
2301    }
2302    let zero = BigInt::from(0i64);
2303    if ty.matches_code(&[kDLUInt]) {
2304        if *value < zero {
2305            let message =
2306                format!("Literal value {value} is negative for unsigned integer type {}", name());
2307            return Err(compare_failed(VALUE_ERROR, "value >= 0", value, 0, &message));
2308        }
2309        let message = || format!("Literal value {value} exceeds maximum of {}", name());
2310        if bits <= 64 {
2311            if !value.to_u64().is_some_and(|small| bits == 64 || small < 1u64 << bits) {
2312                let condition =
2313                    "small.has_value() && (bits == 64 || *small < (uint64_t{1} << bits))";
2314                return Err(check_failed(VALUE_ERROR, condition, &message()));
2315            }
2316        } else {
2317            let limit = BigInt::from(1i64).try_shl(bits as i64)?;
2318            if *value >= limit {
2319                let condition = "value < ffi::BigInt(1) << bits";
2320                return Err(compare_failed(VALUE_ERROR, condition, value, &limit, &message()));
2321            }
2322        }
2323    } else if bits == 1 || ty.matches_code(&[kDLBool]) {
2324        if *value != zero && *value != BigInt::from(1i64) {
2325            let message = format!("{value} exceeds range of {}", name());
2326            return Err(check_failed(VALUE_ERROR, "value == 0 || value == 1", &message));
2327        }
2328    } else {
2329        let message = || format!("Literal value {value} exceeds range of {}", name());
2330        if bits <= 64 {
2331            let half = 1i128 << (bits - 1);
2332            let fits = value.to_i64().is_some_and(|small| {
2333                bits == 64 || ((small as i128) >= -half && (small as i128) < half)
2334            });
2335            if !fits {
2336                let condition = "small.has_value() && (bits == 64 || (*small >= -(int64_t{1} << \
2337                                 (bits - 1)) && *small < (int64_t{1} << (bits - 1))))";
2338                return Err(check_failed(VALUE_ERROR, condition, &message()));
2339            }
2340        } else {
2341            let limit = BigInt::from(1i64).try_shl(bits as i64 - 1)?;
2342            if *value < -limit.clone() || *value >= limit {
2343                let condition = "value >= -limit && value < limit";
2344                return Err(check_failed(VALUE_ERROR, condition, &message()));
2345            }
2346        }
2347    }
2348    Ok(())
2349}