Skip to main content

tvm_tirx/ir/prim/
op.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//! Primitive operators. Each function, such as [`add`], matches its operand types and folds
21//! constants, where a node constructor such as [`Add::new`](super::Add::new) takes operands as
22//! given; Rust operators such as `&x + 1` build an [`ExprResult`], and [`PrimOps`] has the rest.
23
24// tvm-ffi-stubgen(file): mod(missing_docs = allow)
25// Names the hand-written code uses: the import section keeps them even when no generated block
26// does.
27// tvm-ffi-stubgen(import): tvm_ffi::Any
28// tvm-ffi-stubgen(import): tvm_ffi::BigInt
29// tvm-ffi-stubgen(import): tvm_ffi::DLDataType
30// tvm-ffi-stubgen(import): tvm_ffi::DLDataTypeCode
31// tvm-ffi-stubgen(import): tvm_ffi::Error
32// tvm-ffi-stubgen(import): tvm_ffi::INTERNAL_ERROR
33// tvm-ffi-stubgen(import): tvm_ffi::ObjectRefCore
34// tvm-ffi-stubgen(import): tvm_ffi::Result
35// tvm-ffi-stubgen(import): tvm_ffi::TYPE_ERROR
36// tvm-ffi-stubgen(import): tvm_ffi::VALUE_ERROR
37// tvm-ffi-stubgen(import): crate::ir::expr::Call
38// tvm-ffi-stubgen(import): crate::ir::expr::CallObj
39// tvm-ffi-stubgen(import): crate::ir::expr::Expr
40// tvm-ffi-stubgen(import): crate::ir::expr::FloatImm
41// tvm-ffi-stubgen(import): crate::ir::expr::FloatImmObj
42// tvm-ffi-stubgen(import): crate::ir::expr::IntImm
43// tvm-ffi-stubgen(import): crate::ir::expr::IntImmObj
44// tvm-ffi-stubgen(import): crate::ir::expr::IntoExpr
45// tvm-ffi-stubgen(import): crate::ir::expr::PrimExpr
46// tvm-ffi-stubgen(import): crate::ir::location::Location
47// tvm-ffi-stubgen(import): crate::ir::location::UNKNOWN_LOC
48// tvm-ffi-stubgen(import): crate::ir::prim::const_fold
49// tvm-ffi-stubgen(import): crate::ir::prim::expr::Add
50// tvm-ffi-stubgen(import): crate::ir::prim::expr::And
51// tvm-ffi-stubgen(import): crate::ir::prim::expr::BitwiseAnd
52// tvm-ffi-stubgen(import): crate::ir::prim::expr::BitwiseNot
53// tvm-ffi-stubgen(import): crate::ir::prim::expr::BitwiseOr
54// tvm-ffi-stubgen(import): crate::ir::prim::expr::BitwiseXor
55// tvm-ffi-stubgen(import): crate::ir::prim::expr::Cast
56// tvm-ffi-stubgen(import): crate::ir::prim::expr::Div
57// tvm-ffi-stubgen(import): crate::ir::prim::expr::EQ
58// tvm-ffi-stubgen(import): crate::ir::prim::expr::FloorDiv
59// tvm-ffi-stubgen(import): crate::ir::prim::expr::FloorMod
60// tvm-ffi-stubgen(import): crate::ir::prim::expr::GE
61// tvm-ffi-stubgen(import): crate::ir::prim::expr::GT
62// tvm-ffi-stubgen(import): crate::ir::prim::expr::LE
63// tvm-ffi-stubgen(import): crate::ir::prim::expr::LShift
64// tvm-ffi-stubgen(import): crate::ir::prim::expr::LT
65// tvm-ffi-stubgen(import): crate::ir::prim::expr::Max
66// tvm-ffi-stubgen(import): crate::ir::prim::expr::Min
67// tvm-ffi-stubgen(import): crate::ir::prim::expr::Mod
68// tvm-ffi-stubgen(import): crate::ir::prim::expr::Mul
69// tvm-ffi-stubgen(import): crate::ir::prim::expr::NE
70// tvm-ffi-stubgen(import): crate::ir::prim::expr::Not
71// tvm-ffi-stubgen(import): crate::ir::prim::expr::Or
72// tvm-ffi-stubgen(import): crate::ir::prim::expr::RShift
73// tvm-ffi-stubgen(import): crate::ir::prim::expr::Select
74// tvm-ffi-stubgen(import): crate::ir::prim::expr::Sub
75// tvm-ffi-stubgen(import): crate::ir::prim::vector_expr::Broadcast
76// tvm-ffi-stubgen(import): crate::ir::prim::vector_expr::BroadcastObj
77// tvm-ffi-stubgen(import): crate::ir::prim::vector_expr::Ramp
78// tvm-ffi-stubgen(import): crate::ir::prim::vector_expr::RampObj
79// tvm-ffi-stubgen(import): crate::ir::r#type::PrimType
80// tvm-ffi-stubgen(import): crate::ir::r#type::Type
81// tvm-ffi-stubgen(import): crate::ir::support
82// tvm-ffi-stubgen(import): crate::sym
83// tvm-ffi-stubgen(import): tvm_ffi::IntoArg
84// tvm-ffi-stubgen(import): std::borrow::Borrow
85
86// tvm-ffi-stubgen(begin): import-section
87use crate::ir::expr::Call;
88use crate::ir::expr::CallObj;
89use crate::ir::expr::Expr;
90use crate::ir::expr::FloatImm;
91use crate::ir::expr::FloatImmObj;
92use crate::ir::expr::IntImm;
93use crate::ir::expr::IntImmObj;
94use crate::ir::expr::IntoExpr;
95use crate::ir::expr::PrimExpr;
96use crate::ir::location::Location;
97use crate::ir::location::UNKNOWN_LOC;
98use crate::ir::prim::const_fold;
99use crate::ir::prim::expr::Add;
100use crate::ir::prim::expr::And;
101use crate::ir::prim::expr::BitwiseAnd;
102use crate::ir::prim::expr::BitwiseNot;
103use crate::ir::prim::expr::BitwiseOr;
104use crate::ir::prim::expr::BitwiseXor;
105use crate::ir::prim::expr::Cast;
106use crate::ir::prim::expr::Div;
107use crate::ir::prim::expr::EQ;
108use crate::ir::prim::expr::FloorDiv;
109use crate::ir::prim::expr::FloorMod;
110use crate::ir::prim::expr::GE;
111use crate::ir::prim::expr::GT;
112use crate::ir::prim::expr::LE;
113use crate::ir::prim::expr::LShift;
114use crate::ir::prim::expr::LT;
115use crate::ir::prim::expr::Max;
116use crate::ir::prim::expr::Min;
117use crate::ir::prim::expr::Mod;
118use crate::ir::prim::expr::Mul;
119use crate::ir::prim::expr::NE;
120use crate::ir::prim::expr::Not;
121use crate::ir::prim::expr::Or;
122use crate::ir::prim::expr::RShift;
123use crate::ir::prim::expr::Select;
124use crate::ir::prim::expr::Sub;
125use crate::ir::prim::vector_expr::Broadcast;
126use crate::ir::prim::vector_expr::BroadcastObj;
127use crate::ir::prim::vector_expr::Ramp;
128use crate::ir::prim::vector_expr::RampObj;
129use crate::ir::r#type::PrimType;
130use crate::ir::r#type::Type;
131use crate::ir::support;
132use crate::sym;
133use std::borrow::Borrow;
134use tvm_ffi::Any;
135use tvm_ffi::BigInt;
136use tvm_ffi::DLDataType;
137use tvm_ffi::DLDataTypeCode;
138use tvm_ffi::Error;
139use tvm_ffi::INTERNAL_ERROR;
140use tvm_ffi::IntoArg;
141use tvm_ffi::ObjectRefCore;
142use tvm_ffi::Result;
143use tvm_ffi::TYPE_ERROR;
144use tvm_ffi::VALUE_ERROR;
145// tvm-ffi-stubgen(end)
146
147// ---------------------------------------------------------------------------------------------
148// `ExprResult`: expressions under construction
149
150/// An expression being built by operators, or the first error any step raised.
151///
152/// It is an [`IntoExpr`], so it passes into any function that takes one, whose `?` reports the
153/// error; `PrimExpr::try_from` takes the expression out. `/` and `%` are not defined: name the
154/// division, such as [`PrimOps::floordiv`].
155///
156/// # Examples
157///
158/// ```
159/// use tvm_tirx::ir::prim::op::{ExprResult, PrimOps};
160/// use tvm_tirx::ir::prim::Ramp;
161/// use tvm_tirx::ir::{PrimExpr, PrimType, PrimVar, UNKNOWN_LOC};
162/// use tvm_tirx::script::script;
163///
164/// let i = PrimVar::new("i", PrimType::int(32), UNKNOWN_LOC);
165/// let j = PrimVar::new("j", PrimType::int(32), UNKNOWN_LOC);
166/// let offset: ExprResult = &i * 16 + &j;
167/// let lanes = Ramp::new(offset, 1, 4, UNKNOWN_LOC)?;
168/// assert_eq!(script(&lanes)?, "T.Ramp(i * 16 + j, 1, 4)");
169///
170/// let f = PrimVar::new("f", PrimType::float(32), UNKNOWN_LOC);
171/// assert!(PrimExpr::try_from(f.truncdiv(2) + 1).is_err());
172/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
173/// ```
174#[derive(Clone)]
175#[must_use = "an `ExprResult` holds the result; pass it on, or convert it with `PrimExpr::try_from`"]
176pub struct ExprResult(Result<PrimExpr>);
177
178impl ExprResult {
179    /// The type a literal next to this expression takes (`MakeConst(this.ty(), v)`).
180    fn prim_ty(&self) -> Result<PrimType> {
181        match &self.0 {
182            Ok(expr) => Ok(expr.prim_ty().clone()),
183            Err(error) => Err(error.clone()),
184        }
185    }
186}
187
188impl TryFrom<ExprResult> for Expr {
189    type Error = Error;
190
191    /// Take out the built expression, or the first error raised while building it.
192    fn try_from(value: ExprResult) -> Result<Self> {
193        value.0.map(Into::into)
194    }
195}
196
197impl TryFrom<ExprResult> for PrimExpr {
198    type Error = Error;
199
200    /// Take out the built expression, or the first error raised while building it.
201    fn try_from(value: ExprResult) -> Result<Self> {
202        value.0
203    }
204}
205
206impl IntoExpr for ExprResult {
207    type Output = Expr;
208
209    fn into_expr(self) -> Result<Expr> {
210        self.0.map(Into::into)
211    }
212}
213
214impl<'a> IntoExpr for &'a ExprResult {
215    type Output = &'a Expr;
216
217    fn into_expr(self) -> Result<&'a Expr> {
218        match &self.0 {
219            Ok(expr) => Ok(expr.as_ref()),
220            Err(error) => Err(error.clone()),
221        }
222    }
223}
224
225impl IntoExpr<PrimExpr> for ExprResult {
226    type Output = PrimExpr;
227
228    fn into_expr(self) -> Result<PrimExpr> {
229        self.0
230    }
231}
232
233impl<'a> IntoExpr<PrimExpr> for &'a ExprResult {
234    type Output = &'a PrimExpr;
235
236    fn into_expr(self) -> Result<&'a PrimExpr> {
237        match &self.0 {
238            Ok(prim) => Ok(prim),
239            Err(error) => Err(error.clone()),
240        }
241    }
242}
243
244/// A step's result: the expression, of a subtype of `PrimExpr`, or its error.
245impl<T: Into<PrimExpr>> From<Result<T>> for ExprResult {
246    fn from(value: Result<T>) -> Self {
247        ExprResult(value.map(Into::into))
248    }
249}
250
251impl From<&ExprResult> for ExprResult {
252    fn from(value: &ExprResult) -> Self {
253        value.clone()
254    }
255}
256
257mod operators {
258    //! The operator traits of [`ExprResult`], and of the expressions and literals that start one.
259
260    use std::ops::{
261        Add, AddAssign, BitAnd, BitOr, BitXor, Mul, MulAssign, Neg, Not, Shl, Shr, Sub, SubAssign,
262    };
263
264    use super::{binary, binary_literal, ExprResult, Operand};
265
266    macro_rules! binary_operators {
267        ($($Trait:ident::$method:ident => $op:ident),+ $(,)?) => {
268            $(
269                impl<R: Operand> $Trait<R> for ExprResult {
270                    type Output = ExprResult;
271                    fn $method(self, rhs: R) -> ExprResult {
272                        binary(self, rhs, super::$op)
273                    }
274                }
275                binary_operators!(@lhs $Trait::$method => $op; &ExprResult);
276                binary_operators!(@literal $Trait::$method => $op; i32, i64, f32, f64);
277            )+
278        };
279        (@lhs $Trait:ident::$method:ident => $op:ident; $($lhs:ty),+) => {
280            $(
281                impl<R: Operand> $Trait<R> for $lhs {
282                    type Output = ExprResult;
283                    fn $method(self, rhs: R) -> ExprResult {
284                        binary(self.into(), rhs, super::$op)
285                    }
286                }
287            )+
288        };
289        (@literal $Trait:ident::$method:ident => $op:ident; $($lit:ty),+) => {
290            $(
291                binary_operators!(@literal_rhs $Trait::$method => $op; $lit; ExprResult, &ExprResult);
292            )+
293        };
294        (@literal_rhs $Trait:ident::$method:ident => $op:ident; $lit:ty; $($rhs:ty),+) => {
295            $(
296                impl $Trait<$rhs> for $lit {
297                    type Output = ExprResult;
298                    fn $method(self, rhs: $rhs) -> ExprResult {
299                        binary_literal(self, rhs.into(), super::$op)
300                    }
301                }
302            )+
303        };
304    }
305
306    binary_operators!(
307        Add::add => add,
308        Sub::sub => sub,
309        Mul::mul => mul,
310        BitAnd::bitand => bitwise_and,
311        BitOr::bitor => bitwise_or,
312        BitXor::bitxor => bitwise_xor,
313        Shl::shl => shift_left,
314        Shr::shr => shift_right,
315    );
316
317    macro_rules! assign_operators {
318        ($($Trait:ident::$method:ident => $op:ident),+ $(,)?) => {
319            $(
320                impl<R: Operand> $Trait<R> for ExprResult {
321                    fn $method(&mut self, rhs: R) {
322                        *self = binary(self.clone(), rhs, super::$op);
323                    }
324                }
325            )+
326        };
327    }
328
329    assign_operators!(AddAssign::add_assign => add, SubAssign::sub_assign => sub, MulAssign::mul_assign => mul);
330
331    macro_rules! unary_operators {
332        ($($ty:ty),+) => {
333            $(
334                /// `-a`: [`neg`](super::neg).
335                impl Neg for $ty {
336                    type Output = ExprResult;
337                    fn neg(self) -> ExprResult {
338                        ExprResult(super::neg(ExprResult::from(self)))
339                    }
340                }
341                /// `!a`: [`logical_not`](super::logical_not).
342                impl Not for $ty {
343                    type Output = ExprResult;
344                    fn not(self) -> ExprResult {
345                        ExprResult(super::logical_not(ExprResult::from(self)))
346                    }
347                }
348            )+
349        };
350    }
351
352    unary_operators!(ExprResult, &ExprResult);
353}
354
355/// `lhs <op> rhs`; a literal `rhs` is typed after `lhs`.
356fn binary(
357    lhs: ExprResult,
358    rhs: impl Operand,
359    op: impl FnOnce(PrimExpr, PrimExpr) -> Result<PrimExpr>,
360) -> ExprResult {
361    let rhs = typed_after(rhs.classify(), &lhs);
362    match (lhs.0, rhs.0) {
363        (Ok(a), Ok(b)) => ExprResult(op(a, b)),
364        (Err(error), _) | (_, Err(error)) => ExprResult(Err(error)),
365    }
366}
367
368/// `lhs <op> rhs` for a literal `lhs`, typed after `rhs`.
369fn binary_literal(
370    lhs: impl Operand,
371    rhs: ExprResult,
372    op: impl FnOnce(PrimExpr, PrimExpr) -> Result<PrimExpr>,
373) -> ExprResult {
374    let lhs = typed_after(lhs.classify(), &rhs);
375    binary(lhs, rhs, op)
376}
377
378// ---------------------------------------------------------------------------------------------
379// `PrimOps`: the operations Rust has no operator for
380
381/// [`PrimOps`] methods that are a function of one expression.
382macro_rules! unary_methods {
383    ($($(#[$doc:meta])* $name:ident;)+) => {
384        $(
385            $(#[$doc])*
386            fn $name(&self) -> ExprResult {
387                ExprResult($name(self.to_expr_result()))
388            }
389        )+
390    };
391}
392
393/// [`PrimOps`] methods that are a function of two expressions, the second typed after the first
394/// when it is a literal.
395macro_rules! binary_methods {
396    ($($(#[$doc:meta])* $name:ident;)+) => {
397        $(
398            $(#[$doc])*
399            fn $name(&self, rhs: impl Operand) -> ExprResult {
400                binary(self.to_expr_result(), rhs, $name)
401            }
402        )+
403    };
404}
405
406/// The operations Rust has no operator for, as methods of [`ExprResult`] and every expression
407/// handle.
408///
409/// The comparisons are named `less`, `equal` and so on, since Rust's `eq` and `lt` return a
410/// `bool`.
411///
412/// # Examples
413///
414/// ```
415/// use tvm_tirx::ir::prim::op::PrimOps;
416/// use tvm_tirx::ir::{PrimExpr, PrimType, PrimVar, Var, UNKNOWN_LOC};
417/// use tvm_tirx::script::script;
418///
419/// let i = PrimVar::new("i", PrimType::int(32), UNKNOWN_LOC);
420/// let n = PrimVar::new("n", PrimType::int(32), UNKNOWN_LOC);
421/// let in_bounds = PrimExpr::try_from(i.greater_equal(0).logical_and(i.less(&n)))?;
422/// assert_eq!(script(&in_bounds)?, "i >= 0 and i < n");
423/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
424/// ```
425pub trait PrimOps {
426    /// Return this expression as an [`ExprResult`].
427    fn to_expr_result(&self) -> ExprResult;
428
429    /// Build the boolean `self < rhs` ([`lt`]).
430    fn less(&self, rhs: impl Operand) -> ExprResult {
431        binary(self.to_expr_result(), rhs, lt)
432    }
433    /// Build the boolean `self <= rhs` ([`le`]).
434    fn less_equal(&self, rhs: impl Operand) -> ExprResult {
435        binary(self.to_expr_result(), rhs, le)
436    }
437    /// Build the boolean `self > rhs` ([`gt`]).
438    fn greater(&self, rhs: impl Operand) -> ExprResult {
439        binary(self.to_expr_result(), rhs, gt)
440    }
441    /// Build the boolean `self >= rhs` ([`ge`]).
442    fn greater_equal(&self, rhs: impl Operand) -> ExprResult {
443        binary(self.to_expr_result(), rhs, ge)
444    }
445    /// Build the boolean `self == rhs` ([`eq`]).
446    fn equal(&self, rhs: impl Operand) -> ExprResult {
447        binary(self.to_expr_result(), rhs, eq)
448    }
449    /// Build the boolean `self != rhs` ([`ne`]).
450    fn not_equal(&self, rhs: impl Operand) -> ExprResult {
451        binary(self.to_expr_result(), rhs, ne)
452    }
453    /// Build the boolean `self && rhs` ([`logical_and`]).
454    fn logical_and(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
455        ExprResult(logical_and(self.to_expr_result(), rhs))
456    }
457    /// Build the boolean `self || rhs` ([`logical_or`]).
458    fn logical_or(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
459        ExprResult(logical_or(self.to_expr_result(), rhs))
460    }
461
462    binary_methods! {
463        /// Build [`div`]`(self, rhs)`.
464        div;
465        /// Build [`truncdiv`]`(self, rhs)`.
466        truncdiv;
467        /// Build [`truncmod`]`(self, rhs)`.
468        truncmod;
469        /// Build [`floordiv`]`(self, rhs)`.
470        floordiv;
471        /// Build [`floormod`]`(self, rhs)`.
472        floormod;
473        /// Build [`indexdiv`]`(self, rhs)`.
474        indexdiv;
475        /// Build [`indexmod`]`(self, rhs)`.
476        indexmod;
477        /// Build [`ceildiv`]`(self, rhs)`.
478        ceildiv;
479        /// Build [`min`]`(self, rhs)`.
480        min;
481        /// Build [`max`]`(self, rhs)`.
482        max;
483    }
484
485    /// Build [`pow`]`(self, rhs)`.
486    fn pow(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
487        ExprResult(pow(self.to_expr_result(), rhs))
488    }
489    /// Build [`fmod`]`(self, rhs)`.
490    fn fmod(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
491        ExprResult(fmod(self.to_expr_result(), rhs))
492    }
493    /// Build [`atan2`]`(self, rhs)`.
494    fn atan2(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
495        ExprResult(atan2(self.to_expr_result(), rhs))
496    }
497    /// Build [`nextafter`]`(self, rhs)`.
498    fn nextafter(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
499        ExprResult(nextafter(self.to_expr_result(), rhs))
500    }
501    /// Build [`copysign`]`(self, rhs)`.
502    fn copysign(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
503        ExprResult(copysign(self.to_expr_result(), rhs))
504    }
505    /// Build [`hypot`]`(self, rhs)`.
506    fn hypot(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
507        ExprResult(hypot(self.to_expr_result(), rhs))
508    }
509    /// Build [`ldexp`]`(self, rhs)`.
510    fn ldexp(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
511        ExprResult(ldexp(self.to_expr_result(), rhs))
512    }
513
514    unary_methods! {
515        /// Build [`bitwise_not`]`(self)`.
516        bitwise_not;
517        /// Build [`floor`]`(self)`.
518        floor;
519        /// Build [`ceil`]`(self)`.
520        ceil;
521        /// Build [`round`]`(self)`.
522        round;
523        /// Build [`nearbyint`]`(self)`.
524        nearbyint;
525        /// Build [`trunc`]`(self)`.
526        trunc;
527        /// Build [`abs`]`(self)`.
528        abs;
529        /// Build [`isnan`]`(self)`.
530        isnan;
531        /// Build [`isinf`]`(self)`.
532        isinf;
533        /// Build [`isfinite`]`(self)`.
534        isfinite;
535        /// Build [`likely`]`(self)`.
536        likely;
537        /// Build [`assume`]`(self)`.
538        assume;
539        /// Build [`clz`]`(self)`.
540        clz;
541        /// Build [`exp`]`(self)`.
542        exp;
543        /// Build [`exp2`]`(self)`.
544        exp2;
545        /// Build [`exp10`]`(self)`.
546        exp10;
547        /// Build [`erf`]`(self)`.
548        erf;
549        /// Build [`sigmoid`]`(self)`.
550        sigmoid;
551        /// Build [`sqrt`]`(self)`.
552        sqrt;
553        /// Build [`rsqrt`]`(self)`.
554        rsqrt;
555        /// Build [`log`]`(self)`.
556        log;
557        /// Build [`log2`]`(self)`.
558        log2;
559        /// Build [`log10`]`(self)`.
560        log10;
561        /// Build [`log1p`]`(self)`.
562        log1p;
563        /// Build [`popcount`]`(self)`.
564        popcount;
565        /// Build [`tanh`]`(self)`.
566        tanh;
567        /// Build [`tan`]`(self)`.
568        tan;
569        /// Build [`cos`]`(self)`.
570        cos;
571        /// Build [`cosh`]`(self)`.
572        cosh;
573        /// Build [`sin`]`(self)`.
574        sin;
575        /// Build [`sinh`]`(self)`.
576        sinh;
577        /// Build [`asin`]`(self)`.
578        asin;
579        /// Build [`acos`]`(self)`.
580        acos;
581        /// Build [`atan`]`(self)`.
582        atan;
583        /// Build [`acosh`]`(self)`.
584        acosh;
585        /// Build [`asinh`]`(self)`.
586        asinh;
587        /// Build [`atanh`]`(self)`.
588        atanh;
589    }
590
591    /// Build [`cast`]`(self, ty)`.
592    fn cast(&self, ty: impl IntoArg<PrimType>) -> ExprResult {
593        ExprResult(cast(self.to_expr_result(), ty))
594    }
595
596    /// Build [`if_then_else`]`(self, t, f)`, with `self` the condition.
597    fn if_then_else(&self, t: impl IntoExpr<PrimExpr>, f: impl IntoExpr<PrimExpr>) -> ExprResult {
598        ExprResult(if_then_else(self.to_expr_result(), t, f))
599    }
600
601    /// Build the raw node `Select(self, t, f)` ([`Select::new`]), with `self` the condition; unlike
602    /// [`if_then_else`](Self::if_then_else), both values are evaluated.
603    fn select(&self, t: impl IntoExpr<PrimExpr>, f: impl IntoExpr<PrimExpr>) -> ExprResult {
604        ExprResult(Select::new(self.to_expr_result(), t, f, UNKNOWN_LOC).map(PrimExpr::from))
605    }
606}
607
608impl PrimOps for ExprResult {
609    fn to_expr_result(&self) -> ExprResult {
610        self.clone()
611    }
612}
613
614// ---------------------------------------------------------------------------------------------
615// Operands
616
617/// An operand of an operator: an expression, an [`ExprResult`] or a literal.
618///
619/// A literal is typed after the expression it meets: an integer takes its type, an `f32` is a
620/// float32 constant and an `f64` a float64 one.
621///
622/// # Examples
623///
624/// ```
625/// use tvm_tirx::ir::prim::op::add;
626/// use tvm_tirx::ir::{PrimType, PrimVar, Var, UNKNOWN_LOC};
627/// use tvm_tirx::script::script;
628///
629/// let n = PrimVar::new("n", PrimType::int(64), UNKNOWN_LOC);
630/// assert_eq!(script(&add(&n, 1)?)?, "n + T.int64(1)");
631/// assert_eq!(script(&add(&n, 0.5)?)?, "T.Cast(\"float64\", n) + T.float64(0.5)");
632/// assert_eq!(script(&add(1, 2)?)?, "3");
633/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
634/// ```
635pub trait Operand {
636    #[doc(hidden)]
637    fn classify(self) -> OperandKind;
638}
639
640/// What an [`Operand`] is.
641#[doc(hidden)]
642pub enum OperandKind {
643    Expr(ExprResult),
644    Int32(i32),
645    Int64(i64),
646    Float32(f32),
647    Float64(f64),
648}
649
650impl<T: Into<ExprResult>> Operand for T {
651    fn classify(self) -> OperandKind {
652        OperandKind::Expr(self.into())
653    }
654}
655
656/// A constant of the other operand's type. `i32` is what an unsuffixed literal falls back to.
657impl Operand for i32 {
658    fn classify(self) -> OperandKind {
659        OperandKind::Int32(self)
660    }
661}
662
663impl Operand for i64 {
664    fn classify(self) -> OperandKind {
665        OperandKind::Int64(self)
666    }
667}
668
669/// A float32 constant, whatever the other side.
670impl Operand for f32 {
671    fn classify(self) -> OperandKind {
672        OperandKind::Float32(self)
673    }
674}
675
676/// A float64 constant, whatever the other side.
677impl Operand for f64 {
678    fn classify(self) -> OperandKind {
679        OperandKind::Float64(self)
680    }
681}
682
683/// An operand next to `peer`: a literal is typed after it.
684fn typed_after(operand: OperandKind, peer: &ExprResult) -> ExprResult {
685    let constant = |value: i64| ExprResult(peer.prim_ty().and_then(|ty| make_const(ty, value)));
686    match operand {
687        OperandKind::Expr(expr) => expr,
688        OperandKind::Int32(value) => constant(i64::from(value)),
689        OperandKind::Int64(value) => constant(value),
690        OperandKind::Float32(value) => ExprResult(Ok(FloatImm::float32(value).into())),
691        OperandKind::Float64(value) => ExprResult(Ok(FloatImm::float64(value).into())),
692    }
693}
694
695/// An operand on its own: a literal is the constant [`From`] makes of it.
696fn on_its_own(operand: OperandKind) -> ExprResult {
697    match operand {
698        OperandKind::Expr(expr) => expr,
699        OperandKind::Int32(value) => ExprResult(Ok(IntImm::int32(value).into())),
700        OperandKind::Int64(value) => ExprResult(Ok(IntImm::int64(value).into())),
701        OperandKind::Float32(value) => ExprResult(Ok(FloatImm::float32(value).into())),
702        OperandKind::Float64(value) => ExprResult(Ok(FloatImm::float64(value).into())),
703    }
704}
705
706/// The two operands of a binary operation as expressions: a literal takes the type of the other
707/// side, two literals their own.
708fn operands(a: impl Operand, b: impl Operand) -> Result<(PrimExpr, PrimExpr)> {
709    let (a, b) = match (a.classify(), b.classify()) {
710        (OperandKind::Expr(a), b) => {
711            let b = typed_after(b, &a);
712            (a, b)
713        }
714        (a, OperandKind::Expr(b)) => {
715            let a = typed_after(a, &b);
716            (a, b)
717        }
718        (a, b) => (on_its_own(a), on_its_own(b)),
719    };
720    Ok((a.into_owned_expr()?, b.into_owned_expr()?))
721}
722
723/// The functions without a location: each builds at the unknown location through its `_at`
724/// variant.
725macro_rules! unlocated {
726    ($($(#[$doc:meta])* $name:ident($($arg:ident: $ty:ty),*) => $at:ident;)+) => {
727        $(
728            $(#[$doc])*
729            pub fn $name($($arg: $ty),*) -> Result<PrimExpr> {
730                $at($($arg,)* UNKNOWN_LOC)
731            }
732        )+
733    };
734}
735
736// ---------------------------------------------------------------------------------------------
737// Constants
738
739/// The value of a constant: an integer or a double.
740///
741/// Rust integers, `bool`, [`BigInt`], `f32` and `f64` convert into one, so [`make_const`] takes
742/// them directly.
743#[derive(Clone, Debug)]
744pub enum ConstValue {
745    /// An integer, exactly.
746    Int(BigInt),
747    /// A floating-point value.
748    Float(f64),
749}
750
751macro_rules! const_value_from_int {
752    ($($int:ty),+) => {
753        $(
754            impl From<$int> for ConstValue {
755                fn from(value: $int) -> Self {
756                    ConstValue::Int(BigInt::from(value))
757                }
758            }
759        )+
760    };
761}
762
763const_value_from_int!(i8, i16, i32, i64, u8, u16, u32, u64, bool, BigInt);
764
765impl From<f64> for ConstValue {
766    fn from(value: f64) -> Self {
767        ConstValue::Float(value)
768    }
769}
770
771impl From<f32> for ConstValue {
772    fn from(value: f32) -> Self {
773        ConstValue::Float(f64::from(value))
774    }
775}
776
777unlocated! {
778    /// Create the constant `value` of the type `ty`, broadcast over the lanes of a vector type.
779    ///
780    /// # Errors
781    ///
782    /// Returns a `ValueError` if `value` is out of the range of `ty`, or an `InternalError` if it
783    /// is negative for an unsigned `ty` or `ty` is not a type of constants, such as `void`.
784    make_const(ty: impl IntoArg<PrimType>, value: impl Into<ConstValue>) => make_const_at;
785}
786
787/// Build [`make_const`] at the location `loc`.
788pub fn make_const_at(
789    ty: impl IntoArg<PrimType>,
790    value: impl Into<ConstValue>,
791    loc: impl IntoArg<Location>,
792) -> Result<PrimExpr> {
793    let (ty, value) = (ty.into_owned(), value.into());
794    if !ty.is_scalable_vector() && !ty.is_fixed_length_vector() {
795        return make_const_scalar(ty, value, loc.into_arg().borrow());
796    }
797    let loc = loc.into_owned();
798    let scalar = make_const_scalar(ty.with_lanes(1)?, value, &loc)?;
799    let lanes = match ty.vscale_factor() {
800        Some(factor) => super::vector_expr::vscale_lanes(i32::from(factor))?,
801        None => IntImm::int32(support::lanes(&ty)?).into(),
802    };
803    Ok(Broadcast::new(scalar, lanes, loc)?.into())
804}
805
806/// Convert `value` into a primitive expression: a Rust `bool`, integer or float becomes a constant
807/// of the default type, and a primitive expression is returned as is (`prim.convert`).
808///
809/// # Errors
810///
811/// Returns a `TypeError` if `value` is not a primitive expression or a literal.
812pub fn convert(value: impl Into<Any>) -> Result<PrimExpr> {
813    tvm_ffi::cached_global_func!("prim.convert").call_tuple((value.into(),))?.try_into()
814}
815
816/// The scalar constant `value` of the type `ty`: an `IntImm` for an integer or boolean type, a
817/// `FloatImm` for a floating-point type.
818pub(crate) fn make_const_scalar(
819    ty: PrimType,
820    value: ConstValue,
821    loc: &Location,
822) -> Result<PrimExpr> {
823    let code = ty.dtype.code;
824    let unsigned = ty.matches_code(&[DLDataTypeCode::kDLUInt]);
825    if ty.matches_code(&INTEGER_OR_BOOL) {
826        let value = match value {
827            ConstValue::Int(value) => value,
828            ConstValue::Float(value) => {
829                if unsigned && value < 0.0 {
830                    let message = format!(
831                        "cannot make uint from negative value {}",
832                        support::CppDouble(value)
833                    );
834                    return Err(support::check_failed(INTERNAL_ERROR, "value >= 0", &message));
835                }
836                BigInt::try_from(value)?
837            }
838        };
839        if unsigned && value.is_negative() {
840            let message = format!("cannot make uint from negative value {value}");
841            return Err(support::check_failed(INTERNAL_ERROR, "value >= 0", &message));
842        }
843        return Ok(IntImm::new(ty, value, loc.clone())?.into());
844    }
845    if ty.matches_code(&[DLDataTypeCode::kDLFloat])
846        || is_float8(code)
847        || is_float6(code)
848        || is_float4(code)
849        || is_bfloat16(&ty)
850    {
851        let value = match value {
852            ConstValue::Int(value) => value.to_f64()?,
853            ConstValue::Float(value) => value,
854        };
855        return Ok(FloatImm::new(ty, value, loc.clone())?.into());
856    }
857    Err(tvm_ffi::format_err!(INTERNAL_ERROR, "cannot make const for type {ty}"))
858}
859
860// ---------------------------------------------------------------------------------------------
861// Casts and type matching
862
863unlocated! {
864    /// Convert `value` to the type `ty`, folding a constant that keeps its value and broadcasting a
865    /// scalar to a vector type.
866    ///
867    /// [`Cast::new`] builds the node without folding.
868    ///
869    /// # Errors
870    ///
871    /// Returns a `TypeError` if `value` has the void type, or an `InternalError` if `value` and
872    /// `ty` are vectors of different lanes.
873    cast(value: impl IntoExpr<PrimExpr>, ty: impl IntoArg<PrimType>) => cast_at;
874}
875
876/// Build [`cast`] at the location `loc`.
877pub fn cast_at(
878    value: impl IntoExpr<PrimExpr>,
879    ty: impl IntoArg<PrimType>,
880    loc: impl IntoArg<Location>,
881) -> Result<PrimExpr> {
882    let (value, ty) = (value.into_owned_expr()?, ty.into_owned());
883    let from = value.prim_ty().clone();
884    if from.dtype == ty.dtype {
885        return Ok(value);
886    }
887    let loc = loc.into_owned();
888    if from.is_void() {
889        let message = "Cannot cast an expression with the void sentinel type";
890        return Err(support::check_failed(TYPE_ERROR, "!value.ty().IsVoid()", message));
891    }
892    if ty.is_scalar() {
893        return cast_scalar(value, ty, &loc);
894    }
895    let element = ty.with_lanes(1)?;
896    if !from.is_scalable_vector() && !from.is_fixed_length_vector() {
897        let value = cast_at(value, element, loc.clone())?;
898        return Ok(Broadcast::new(value, lanes_of(&ty)?, loc)?.into());
899    }
900    if from.is_scalable_vector() != ty.is_scalable_vector() {
901        let condition = "value.ty().IsScalableVector() == dtype.IsScalableVector()";
902        return Err(support::check_failed(INTERNAL_ERROR, condition, ""));
903    }
904    let lanes_match = match from.is_scalable_vector() {
905        true => from.vscale_factor() == ty.vscale_factor(),
906        false => from.lanes() == ty.lanes(),
907    };
908    if !lanes_match {
909        return Err(support::check_failed(INTERNAL_ERROR, "lanes_match", ""));
910    }
911    if let Some(broadcast) = value.downcast_ref::<BroadcastObj>() {
912        let value = cast_at(broadcast.value.clone(), element, loc.clone())?;
913        return Ok(Broadcast::new(value, broadcast.lanes.clone(), loc)?.into());
914    }
915    if let Some(ramp) = value.downcast_ref::<RampObj>() {
916        // Casting the base and the stride is valid only when every lane is the same integer in
917        // both types: widening must not remove an overflow of the source, and a floating-point
918        // cast need not be affine.
919        let integer = ty.matches_code(&INTEGER) && matches!(ty.bits(), 32 | 64);
920        if let (Some(base), Some(stride)) =
921            (const_fold::int(&ramp.base), const_fold::int(&ramp.stride))
922            && ty.is_fixed_length_vector()
923            && integer
924        {
925            let last = base + stride * i64::from(support::lanes(&ty)? - 1);
926            let source = ramp.base.prim_ty();
927            let fits = |value: &BigInt| const_fold::is_representable(value, &element);
928            if fits(base)
929                && fits(stride)
930                && fits(&last)
931                && const_fold::is_representable(&last, source)
932            {
933                let base = cast_at(ramp.base.clone(), element.clone(), loc.clone())?;
934                let stride = cast_at(ramp.stride.clone(), element, loc.clone())?;
935                return Ok(Ramp::new(base, stride, ramp.lanes.clone(), loc)?.into());
936            }
937        }
938    }
939    Ok(Cast::new(ty, value, loc)?.into())
940}
941
942/// Bring `a` and `b` to one type, as every binary operator does first.
943///
944/// A scalar next to a vector is broadcast, and both are cast to the promoted type: the wider float,
945/// a float over an integer, the wider integer, unsigned over signed.
946///
947/// # Errors
948///
949/// Returns an `InternalError` if the lanes of the two differ or their types cannot be promoted to
950/// one.
951pub fn match_types(
952    a: impl IntoExpr<PrimExpr>,
953    b: impl IntoExpr<PrimExpr>,
954) -> Result<(PrimExpr, PrimExpr)> {
955    match_types_at(a, b, UNKNOWN_LOC)
956}
957
958/// Run [`match_types`] with the casts at the location `loc`.
959pub fn match_types_at(
960    a: impl IntoExpr<PrimExpr>,
961    b: impl IntoExpr<PrimExpr>,
962    loc: impl IntoArg<Location>,
963) -> Result<(PrimExpr, PrimExpr)> {
964    let (a, b, loc) = (a.into_owned_expr()?, b.into_owned_expr()?, loc.into_arg());
965    let loc: &Location = loc.borrow();
966    if a.prim_ty().dtype == b.prim_ty().dtype {
967        return Ok((a, b));
968    }
969    let a = broadcast_to_match_lanes(a, b.prim_ty())?;
970    let b = broadcast_to_match_lanes(b, a.prim_ty())?;
971    let (a_ty, b_ty) = (a.prim_ty(), b.prim_ty());
972    if a_ty.is_scalable_vector() != b_ty.is_scalable_vector() {
973        let condition = "lhs_ty.IsScalableVector() == rhs_ty.IsScalableVector()";
974        let message = "Can't match scalable and fixed length vectors";
975        return Err(support::check_failed(INTERNAL_ERROR, condition, message));
976    }
977    let lanes_match = match a_ty.is_scalable_vector() {
978        true => a_ty.vscale_factor() == b_ty.vscale_factor(),
979        false => a_ty.lanes() == b_ty.lanes(),
980    };
981    let (a_dtype, b_dtype) = (a_ty.dtype, b_ty.dtype);
982    if !lanes_match {
983        let (lhs, rhs) = (support::dtype_name(a_dtype), support::dtype_name(b_dtype));
984        let message = format!("Cannot match type {lhs} vs {rhs}");
985        return Err(support::check_failed(INTERNAL_ERROR, "lanes_match", &message));
986    }
987    let promoted = promote_binary_op_type(a_dtype, b_dtype)?;
988    let a = match a_dtype == promoted {
989        true => a,
990        false => cast_at(a, PrimType::try_from(promoted)?, loc)?,
991    };
992    let b = match b_dtype == promoted {
993        true => b,
994        false => cast_at(b, PrimType::try_from(promoted)?, loc)?,
995    };
996    Ok((a, b))
997}
998
999/// [`cast`] to a scalar type: a constant folded to `ty` keeping its location (see
1000/// [`fold_cast`]); anything else a [`Cast`].
1001fn cast_scalar(value: PrimExpr, ty: PrimType, loc: &Location) -> Result<PrimExpr> {
1002    match fold_cast(&value, &ty)? {
1003        Some(folded) => Ok(folded),
1004        None => Ok(Cast::new(ty, value, loc.clone())?.into()),
1005    }
1006}
1007
1008/// A constant cast to the scalar type `to`, as [`cast`] folds it: only when the result is the
1009/// same value in `to`, an integer it can represent or a float within its range, and when a float
1010/// type that rounds the result does so itself; `None` leaves a [`Cast`].
1011fn fold_cast(value: &PrimExpr, ty: &PrimType) -> Result<Option<PrimExpr>> {
1012    let integer = ty.matches_code(&INTEGER_OR_BOOL);
1013    let float32 = ty.matches_code(&[DLDataTypeCode::kDLFloat]) && ty.bits() == 32;
1014    let float64 = ty.matches_code(&[DLDataTypeCode::kDLFloat]) && ty.bits() == 64;
1015    let limit_16 = match (ty.dtype.code, ty.bits()) {
1016        (support::FLOAT, 16) => Some(support::MAX_FLOAT16),
1017        (support::BFLOAT, 16) => Some(support::MAX_BFLOAT16),
1018        _ => None,
1019    };
1020    let int = |value: BigInt, loc: &Location| -> Result<Option<PrimExpr>> {
1021        Ok(Some(IntImm::new(ty.clone(), value, loc.clone())?.into()))
1022    };
1023    let float = |value: f64, loc: &Location| -> Result<Option<PrimExpr>> {
1024        Ok(Some(FloatImm::new(ty.clone(), value, loc.clone())?.into()))
1025    };
1026    if let Some(imm) = value.downcast_ref::<IntImmObj>() {
1027        if integer {
1028            if const_fold::is_representable(&imm.value, ty) {
1029                return int(imm.value.clone(), &imm.loc);
1030            }
1031        } else if float32 {
1032            if let Some(small) = imm.value.to_i64() {
1033                return float(f64::from(small as f32), &imm.loc);
1034            }
1035        } else if float64 {
1036            let limit = BigInt::try_from(f64::MAX)?;
1037            if (-&limit..=limit).contains(&imm.value) {
1038                return float(imm.value.to_f64()?, &imm.loc);
1039            }
1040        } else if let Some(limit) = limit_16 {
1041            let source = imm.value.to_f64()?;
1042            // Keep the integer exact until the destination performs its rounding.
1043            if (-limit..=limit).contains(&source) && BigInt::try_from(source)? == imm.value {
1044                return float(source, &imm.loc);
1045            }
1046        }
1047    } else if let Some(imm) = value.downcast_ref::<FloatImmObj>() {
1048        let from = value.prim_ty();
1049        if imm.value.is_finite() && from.bits() == 16 {
1050            let bfloat = match from.dtype.code {
1051                support::FLOAT => Some(false),
1052                support::BFLOAT => Some(true),
1053                _ => None,
1054            };
1055            // Using the unrounded double would skip the rounding of the source type.
1056            if bfloat.is_some_and(|bfloat| !is_rounded_to_16_bits(imm.value, bfloat)) {
1057                return Ok(None);
1058            }
1059        }
1060        let source = match from.matches_code(&[DLDataTypeCode::kDLFloat]) && from.bits() == 32 {
1061            true => f64::from(imm.value as f32),
1062            false => imm.value,
1063        };
1064        if integer {
1065            // A cast to bool tests for nonzero rather than truncating a fraction.
1066            let fits_bool =
1067                !ty.matches_code(&[DLDataTypeCode::kDLBool]) || source == 0.0 || source == 1.0;
1068            if source.is_finite() && fits_bool {
1069                let result = BigInt::try_from(source)?;
1070                if const_fold::is_representable(&result, ty) {
1071                    return int(result, &imm.loc);
1072                }
1073            }
1074        } else if float32 {
1075            if const_fold::is_in_float32_range(source) {
1076                return float(f64::from(source as f32), &imm.loc);
1077            }
1078        } else if float64
1079            && ((from.matches_code(&[DLDataTypeCode::kDLFloat]) && matches!(from.bits(), 16 | 32))
1080                || is_bfloat16(from))
1081        {
1082            // Source rounding was checked above; widening preserves its value exactly.
1083            return float(source, &imm.loc);
1084        } else if let Some(limit) = limit_16
1085            && (!source.is_finite() || (-limit..=limit).contains(&source))
1086        {
1087            return float(source, &imm.loc);
1088        }
1089    }
1090    Ok(None)
1091}
1092
1093/// Whether the finite `value` of a float16 or bfloat16 `FloatImm` is a value of its type: a
1094/// `FloatImm` holds an unrounded double, which stands for the value the type rounds it to.
1095fn is_rounded_to_16_bits(value: f64, bfloat: bool) -> bool {
1096    let (digits, min_step) = if bfloat { (8, -133) } else { (11, -24) };
1097    let step = (frexp_exponent(value) - digits).max(min_step);
1098    let scaled = value * pow2(-step);
1099    scaled.trunc() == scaled
1100}
1101
1102/// The exponent of a finite `value`, `e` with `value = m * 2^e` and
1103/// `0.5 <= |m| < 1`, and 0 for zero.
1104fn frexp_exponent(value: f64) -> i32 {
1105    match ((value.to_bits() >> 52) & 0x7ff) as i32 {
1106        0 if value == 0.0 => 0,
1107        // A subnormal, scaled into the normal range.
1108        0 => frexp_exponent(value * pow2(64)) - 64,
1109        biased => biased - 1022,
1110    }
1111}
1112
1113/// `2^exponent` for an exponent of a normal double.
1114fn pow2(exponent: i32) -> f64 {
1115    f64::from_bits(((exponent + 1023) as u64) << 52)
1116}
1117
1118/// `value`, broadcast to the lanes of `other` when it is a scalar next to a vector.
1119fn broadcast_to_match_lanes(value: PrimExpr, other: &PrimType) -> Result<PrimExpr> {
1120    let ty = value.prim_ty();
1121    if ty.is_scalable_vector()
1122        || ty.is_fixed_length_vector()
1123        || (!other.is_scalable_vector() && !other.is_fixed_length_vector())
1124    {
1125        return Ok(value);
1126    }
1127    Ok(Broadcast::new(value, lanes_of(other)?, UNKNOWN_LOC)?.into())
1128}
1129
1130/// The type both operands of a binary operation take.
1131fn promote_binary_op_type(lhs: DLDataType, rhs: DLDataType) -> Result<DLDataType> {
1132    if lhs == rhs {
1133        return Ok(lhs);
1134    }
1135    let wider = || if lhs.bits < rhs.bits { rhs } else { lhs };
1136    let float = |dtype: DLDataType| dtype.code == support::FLOAT;
1137    let bfloat = |dtype: DLDataType| dtype.code == support::BFLOAT;
1138    let families: [fn(DLDataType) -> bool; 5] = [
1139        float,
1140        bfloat,
1141        |dtype| is_float8(dtype.code),
1142        |dtype| is_float6(dtype.code),
1143        |dtype| is_float4(dtype.code),
1144    ];
1145    if float(lhs) && float(rhs) {
1146        return Ok(wider());
1147    }
1148    // Each floating-point family takes precedence over every family after it.
1149    for family in families {
1150        match (family(lhs), family(rhs)) {
1151            (false, true) => return Ok(rhs),
1152            (true, false) => return Ok(lhs),
1153            _ => {}
1154        }
1155    }
1156    let integer = |dtype: DLDataType| matches!(dtype.code, support::INT | support::UINT);
1157    match (lhs.code, rhs.code) {
1158        (support::BOOL, _) if integer(rhs) => Ok(rhs),
1159        (_, support::BOOL) if integer(lhs) => Ok(lhs),
1160        (support::INT, support::INT) | (support::UINT, support::UINT) => Ok(wider()),
1161        (support::INT, support::UINT) | (support::UINT, support::INT) => match lhs.bits != rhs.bits
1162        {
1163            true => Ok(wider()),
1164            false => Ok(DLDataType { code: support::UINT, ..lhs }),
1165        },
1166        _ => {
1167            let (lhs, rhs) = (support::dtype_name(lhs), support::dtype_name(rhs));
1168            Err(tvm_ffi::format_err!(INTERNAL_ERROR, "Cannot match type {lhs} vs {rhs}"))
1169        }
1170    }
1171}
1172
1173// ---------------------------------------------------------------------------------------------
1174// Arithmetic
1175
1176/// The binary operators that match the operand types, fold constants and otherwise build the
1177/// raw node; each in a pair with its `_at` variant.
1178macro_rules! folded_binary {
1179    ($($(#[$doc:meta])* $name:ident / $at:ident: $fold:expr => $node:ident),+ $(,)?) => {
1180        $(
1181            $(#[$doc])*
1182            pub fn $name(a: impl Operand, b: impl Operand) -> Result<PrimExpr> {
1183                $at(a, b, UNKNOWN_LOC)
1184            }
1185
1186            #[doc = concat!("Build [`", stringify!($name), "`] at the location `loc`.")]
1187            pub fn $at(
1188                a: impl Operand,
1189                b: impl Operand,
1190                loc: impl IntoArg<Location>,
1191            ) -> Result<PrimExpr> {
1192                let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1193                let (a, b) = match_types_at(a, b, &loc)?;
1194                match $fold(&a, &b)? {
1195                    Some(folded) => Ok(folded),
1196                    None => Ok($node::new(a, b, loc)?.into()),
1197                }
1198            }
1199        )+
1200    };
1201}
1202
1203folded_binary!(
1204    /// Build `a + b`.
1205    ///
1206    /// Like every operator function, it matches the operand types, folds constants and builds at
1207    /// the unknown location; its `_at` variant takes the location. Every operator function
1208    /// returns a `TypeError` for an operand that is not a primitive expression, and the
1209    /// trigonometric and hyperbolic ones also for an operand that is not a float.
1210    ///
1211    /// # Errors
1212    ///
1213    /// Returns a `TypeError` if an operand is not a primitive expression, or an `InternalError` if
1214    /// the operand types cannot be matched.
1215    ///
1216    /// # Examples
1217    ///
1218    /// ```
1219    /// use tvm_tirx::ir::prim::op::{add, floordiv, mul};
1220    /// use tvm_tirx::ir::{PrimType, PrimVar, UNKNOWN_LOC};
1221    /// use tvm_tirx::script::script;
1222    /// use tvm_tirx::tvm_ffi::ObjectRefCore;
1223    ///
1224    /// let i = PrimVar::new("i", PrimType::int(32), UNKNOWN_LOC);
1225    /// assert_eq!(script(&floordiv(&i, 16)?)?, "i // 16");
1226    /// assert_eq!(script(&mul(4, 16)?)?, "64");
1227    /// assert!(add(&i, 0)?.same_as(&i));
1228    /// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
1229    /// ```
1230    add / add_at: const_fold::add => Add,
1231    /// Build `a - b`.
1232    sub / sub_at: const_fold::sub => Sub,
1233    /// Build `a * b`.
1234    mul / mul_at: const_fold::mul => Mul,
1235    /// Build `a / b`; integer division rounds towards zero.
1236    ///
1237    /// # Errors
1238    ///
1239    /// Returns an `InternalError` if `b` is a constant zero.
1240    div / div_at: const_fold::div => Div,
1241    /// Build the remainder of [`truncdiv`], with the sign of `a`.
1242    ///
1243    /// # Errors
1244    ///
1245    /// Returns an `InternalError` if a folded divisor is zero.
1246    truncmod / truncmod_at: const_fold::truncmod => Mod,
1247    /// Build the boolean `a > b`.
1248    gt / gt_at: fold_gt => GT,
1249    /// Build the boolean `a >= b`.
1250    ge / ge_at: fold_ge => GE,
1251    /// Build the boolean `a < b`.
1252    lt / lt_at: fold_lt => LT,
1253    /// Build the boolean `a <= b`.
1254    le / le_at: fold_le => LE,
1255    /// Build the boolean `a != b`.
1256    ne / ne_at: fold_ne => NE,
1257);
1258
1259unlocated! {
1260    /// Build the boolean `a == b`.
1261    eq(a: impl Operand, b: impl Operand) => eq_at;
1262    /// Build `-a`, folding a constant.
1263    neg(a: impl IntoExpr<PrimExpr>) => neg_at;
1264    /// Build `a / b`, rounding towards zero, of two integers.
1265    ///
1266    /// # Errors
1267    ///
1268    /// Returns an `InternalError` if an operand is not an integer or `b` is a constant zero.
1269    truncdiv(a: impl Operand, b: impl Operand) => truncdiv_at;
1270    /// Build `a / b`, rounding down, of two integers.
1271    ///
1272    /// # Errors
1273    ///
1274    /// Returns an `InternalError` if an operand is not an integer or `b` is a constant zero.
1275    floordiv(a: impl Operand, b: impl Operand) => floordiv_at;
1276    /// Build the remainder of [`floordiv`], with the sign of `b`.
1277    ///
1278    /// # Errors
1279    ///
1280    /// Returns an `InternalError` if an operand is not an integer or a folded divisor is zero.
1281    floormod(a: impl Operand, b: impl Operand) => floormod_at;
1282    /// Build `a / b` over non-negative indices, which is [`floordiv`].
1283    indexdiv(a: impl Operand, b: impl Operand) => indexdiv_at;
1284    /// Build `a % b` over non-negative indices, which is [`floormod`].
1285    indexmod(a: impl Operand, b: impl Operand) => indexmod_at;
1286    /// Build `a / b`, rounding up, of two integers: `floordiv(a + b - 1, b)`.
1287    ///
1288    /// # Errors
1289    ///
1290    /// Returns an `InternalError` if an operand is not an integer or `b` is a constant zero.
1291    ceildiv(a: impl Operand, b: impl Operand) => ceildiv_at;
1292    /// Build the smaller of `a` and `b`; a symbolic infinity on either side decides it.
1293    min(a: impl Operand, b: impl Operand) => min_at;
1294    /// Build the larger of `a` and `b`; a symbolic infinity on either side decides it.
1295    max(a: impl Operand, b: impl Operand) => max_at;
1296}
1297
1298/// Build [`eq`] at the location `loc`.
1299pub fn eq_at(a: impl Operand, b: impl Operand, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1300    let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1301    let (a, b) = match_types_at(a, b, &loc)?;
1302    if let Some(folded) = const_fold::compare(&a, &b, |x, y| x == y, |x, y| x == y)? {
1303        return Ok(folded);
1304    }
1305    if is_vscale_call(&a)? && is_vscale_call(&b)? {
1306        return Ok(IntImm::bool(true).into());
1307    }
1308    Ok(EQ::new(a, b, loc)?.into())
1309}
1310
1311/// Build [`neg`] at the location `loc`.
1312pub fn neg_at(a: impl IntoExpr<PrimExpr>, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1313    let (a, loc) = (a.into_owned_expr()?, loc.into_owned());
1314    let ty = a.prim_ty().clone();
1315    if let Some(imm) = a.downcast_ref::<IntImmObj>() {
1316        let value = -imm.value.clone();
1317        if const_fold::is_representable(&value, &ty) {
1318            return Ok(IntImm::new(ty, value, loc)?.into());
1319        }
1320    }
1321    if let Some(imm) = a.downcast_ref::<FloatImmObj>() {
1322        return Ok(FloatImm::new(ty, -imm.value, loc)?.into());
1323    }
1324    sub(make_const_at(ty, 0, loc)?, a)
1325}
1326
1327/// Build [`truncdiv`] at the location `loc`.
1328pub fn truncdiv_at(
1329    a: impl Operand,
1330    b: impl Operand,
1331    loc: impl IntoArg<Location>,
1332) -> Result<PrimExpr> {
1333    let (a, b) = operands(a, b)?;
1334    check_integers(&a, &b)?;
1335    div_at(a, b, loc)
1336}
1337
1338/// Build [`floordiv`] at the location `loc`.
1339pub fn floordiv_at(
1340    a: impl Operand,
1341    b: impl Operand,
1342    loc: impl IntoArg<Location>,
1343) -> Result<PrimExpr> {
1344    let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1345    check_integers(&a, &b)?;
1346    let (a, b) = match_types_at(a, b, &loc)?;
1347    match const_fold::floordiv(&a, &b)? {
1348        Some(folded) => Ok(folded),
1349        None => Ok(FloorDiv::new(a, b, loc)?.into()),
1350    }
1351}
1352
1353/// Build [`floormod`] at the location `loc`.
1354pub fn floormod_at(
1355    a: impl Operand,
1356    b: impl Operand,
1357    loc: impl IntoArg<Location>,
1358) -> Result<PrimExpr> {
1359    let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1360    check_integers(&a, &b)?;
1361    let (a, b) = match_types_at(a, b, &loc)?;
1362    match const_fold::floormod(&a, &b)? {
1363        Some(folded) => Ok(folded),
1364        None => Ok(FloorMod::new(a, b, loc)?.into()),
1365    }
1366}
1367
1368/// Build [`indexdiv`] at the location `loc`.
1369pub fn indexdiv_at(
1370    a: impl Operand,
1371    b: impl Operand,
1372    loc: impl IntoArg<Location>,
1373) -> Result<PrimExpr> {
1374    floordiv_at(a, b, loc)
1375}
1376
1377/// Build [`indexmod`] at the location `loc`.
1378pub fn indexmod_at(
1379    a: impl Operand,
1380    b: impl Operand,
1381    loc: impl IntoArg<Location>,
1382) -> Result<PrimExpr> {
1383    floormod_at(a, b, loc)
1384}
1385
1386/// Build [`ceildiv`] at the location `loc`.
1387pub fn ceildiv_at(
1388    a: impl Operand,
1389    b: impl Operand,
1390    loc: impl IntoArg<Location>,
1391) -> Result<PrimExpr> {
1392    let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1393    check_integers(&a, &b)?;
1394    let (a, b) = match_types_at(a, b, &loc)?;
1395    let sum = add(a, b.clone())?;
1396    let one = make_const(sum.prim_ty().clone(), 1)?;
1397    let numerator = sub(sum, one)?;
1398    match const_fold::floordiv(&numerator, &b)? {
1399        Some(folded) => Ok(folded),
1400        None => Ok(FloorDiv::new(numerator, b, loc)?.into()),
1401    }
1402}
1403
1404/// Build [`min`] at the location `loc`.
1405pub fn min_at(a: impl Operand, b: impl Operand, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1406    let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1407    let (pos_inf, neg_inf) = symbolic_infinities();
1408    if a.same_as(&pos_inf) {
1409        return Ok(b);
1410    }
1411    if a.same_as(&neg_inf) {
1412        return Ok(a);
1413    }
1414    if b.same_as(&pos_inf) {
1415        return Ok(a);
1416    }
1417    if b.same_as(&neg_inf) {
1418        return Ok(b);
1419    }
1420    let (a, b) = match_types_at(a, b, &loc)?;
1421    match const_fold::min(&a, &b)? {
1422        Some(folded) => Ok(folded),
1423        None => Ok(Min::new(a, b, loc)?.into()),
1424    }
1425}
1426
1427/// Build [`max`] at the location `loc`.
1428pub fn max_at(a: impl Operand, b: impl Operand, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1429    let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1430    let (pos_inf, neg_inf) = symbolic_infinities();
1431    if a.same_as(&pos_inf) {
1432        return Ok(a);
1433    }
1434    if a.same_as(&neg_inf) {
1435        return Ok(b);
1436    }
1437    if b.same_as(&pos_inf) {
1438        return Ok(b);
1439    }
1440    if b.same_as(&neg_inf) {
1441        return Ok(a);
1442    }
1443    let (a, b) = match_types_at(a, b, &loc)?;
1444    match const_fold::max(&a, &b)? {
1445        Some(folded) => Ok(folded),
1446        None => Ok(Max::new(a, b, loc)?.into()),
1447    }
1448}
1449
1450fn fold_gt(a: &PrimExpr, b: &PrimExpr) -> const_fold::Folded {
1451    const_fold::compare(a, b, |x, y| x > y, |x, y| x > y)
1452}
1453
1454fn fold_ge(a: &PrimExpr, b: &PrimExpr) -> const_fold::Folded {
1455    const_fold::compare(a, b, |x, y| x >= y, |x, y| x >= y)
1456}
1457
1458fn fold_lt(a: &PrimExpr, b: &PrimExpr) -> const_fold::Folded {
1459    const_fold::compare(a, b, |x, y| x < y, |x, y| x < y)
1460}
1461
1462fn fold_le(a: &PrimExpr, b: &PrimExpr) -> const_fold::Folded {
1463    const_fold::compare(a, b, |x, y| x <= y, |x, y| x <= y)
1464}
1465
1466fn fold_ne(a: &PrimExpr, b: &PrimExpr) -> const_fold::Folded {
1467    const_fold::compare(a, b, |x, y| x != y, |x, y| x != y)
1468}
1469
1470/// `SymbolicLimits::pos_inf_` and `neg_inf_`, the opaque infinities of integer analysis, which
1471/// [`min`] and [`max`] recognize by identity; fetched once per thread.
1472fn symbolic_infinities() -> (PrimExpr, PrimExpr) {
1473    use std::cell::OnceCell;
1474    thread_local! {
1475        static INFINITIES: OnceCell<(PrimExpr, PrimExpr)> = const { OnceCell::new() };
1476    }
1477    support::shared(&INFINITIES, || Ok((sym::pos_inf()?, sym::neg_inf()?)))
1478}
1479
1480// ---------------------------------------------------------------------------------------------
1481// Logic
1482
1483unlocated! {
1484    /// Build the boolean `a && b`; a constant side folds.
1485    ///
1486    /// # Errors
1487    ///
1488    /// Returns an `InternalError` if an operand is not a boolean.
1489    logical_and(a: impl IntoExpr<PrimExpr>, b: impl IntoExpr<PrimExpr>) => logical_and_at;
1490    /// Build the boolean `a || b`; a constant side folds.
1491    ///
1492    /// # Errors
1493    ///
1494    /// Returns an `InternalError` if an operand is not a boolean.
1495    logical_or(a: impl IntoExpr<PrimExpr>, b: impl IntoExpr<PrimExpr>) => logical_or_at;
1496    /// Build the boolean `!a`; a constant folds.
1497    ///
1498    /// # Errors
1499    ///
1500    /// Returns an `InternalError` if `a` is not a boolean.
1501    logical_not(a: impl IntoExpr<PrimExpr>) => logical_not_at;
1502    /// Build the conjunction of `conds` (Python `tvm_tirx.ir.prim.op.all`).
1503    ///
1504    /// # Errors
1505    ///
1506    /// Returns a `ValueError` if `conds` is empty.
1507    all(conds: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>) => all_at;
1508    /// Build the disjunction of `conds` (Python `tvm_tirx.ir.prim.op.any`).
1509    ///
1510    /// # Errors
1511    ///
1512    /// Returns a `ValueError` if `conds` is empty.
1513    any(conds: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>) => any_at;
1514    /// Build `true_value` where `cond` holds and `false_value` elsewhere, evaluating only the
1515    /// chosen one.
1516    ///
1517    /// # Errors
1518    ///
1519    /// Returns an `InternalError` if `cond` is not a boolean or the values cannot be matched.
1520    if_then_else(
1521        cond: impl IntoExpr<PrimExpr>,
1522        true_value: impl IntoExpr<PrimExpr>,
1523        false_value: impl IntoExpr<PrimExpr>
1524    ) => if_then_else_at;
1525}
1526
1527/// Build [`logical_and`] at the location `loc`.
1528pub fn logical_and_at(
1529    a: impl IntoExpr<PrimExpr>,
1530    b: impl IntoExpr<PrimExpr>,
1531    loc: impl IntoArg<Location>,
1532) -> Result<PrimExpr> {
1533    let (a, b) = (a.into_owned_expr()?, b.into_owned_expr()?);
1534    check_operands(&a, &b, "&&", "logical AND", "boolean", (&BOOLEAN, BOOL_CODES))?;
1535    match const_fold::and(&a, &b)? {
1536        Some(folded) => Ok(folded),
1537        None => Ok(And::new(a, b, loc)?.into()),
1538    }
1539}
1540
1541/// Build [`logical_or`] at the location `loc`.
1542pub fn logical_or_at(
1543    a: impl IntoExpr<PrimExpr>,
1544    b: impl IntoExpr<PrimExpr>,
1545    loc: impl IntoArg<Location>,
1546) -> Result<PrimExpr> {
1547    let (a, b) = (a.into_owned_expr()?, b.into_owned_expr()?);
1548    check_operands(&a, &b, "||", "logical OR", "boolean", (&BOOLEAN, BOOL_CODES))?;
1549    match const_fold::or(&a, &b)? {
1550        Some(folded) => Ok(folded),
1551        None => Ok(Or::new(a, b, loc)?.into()),
1552    }
1553}
1554
1555/// Build [`logical_not`] at the location `loc`.
1556pub fn logical_not_at(a: impl IntoExpr<PrimExpr>, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1557    let a = a.into_owned_expr()?;
1558    check_code(&a, "a", &BOOLEAN, BOOL_CODES, || {
1559        format!(
1560            "Expected boolean argument for ! operator (logical NOT), but received {} of type {}",
1561            a, a.ty
1562        )
1563    })?;
1564    match const_fold::not(&a)? {
1565        Some(folded) => Ok(folded),
1566        None => Ok(Not::new(a, loc)?.into()),
1567    }
1568}
1569
1570/// Build [`all`] at the location `loc`.
1571pub fn all_at(
1572    conds: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>,
1573    loc: impl IntoArg<Location>,
1574) -> Result<PrimExpr> {
1575    fold_conditions(conds, loc.into_owned(), "all", logical_and_at)
1576}
1577
1578/// Build [`any`] at the location `loc`.
1579pub fn any_at(
1580    conds: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>,
1581    loc: impl IntoArg<Location>,
1582) -> Result<PrimExpr> {
1583    fold_conditions(conds, loc.into_owned(), "any", logical_or_at)
1584}
1585
1586/// Build [`if_then_else`] at the location `loc`.
1587pub fn if_then_else_at(
1588    cond: impl IntoExpr<PrimExpr>,
1589    true_value: impl IntoExpr<PrimExpr>,
1590    false_value: impl IntoExpr<PrimExpr>,
1591    loc: impl IntoArg<Location>,
1592) -> Result<PrimExpr> {
1593    let (cond, loc) = (cond.into_owned_expr()?, loc.into_owned());
1594    if !cond.prim_ty().matches_code(&[DLDataTypeCode::kDLBool]) {
1595        let condition = "cond.ty().MatchesCode(DLDataTypeCode::kDLBool)";
1596        let message = "if_then_else only accept the condition to be boolean type.";
1597        return Err(support::check_failed(INTERNAL_ERROR, condition, message));
1598    }
1599    let (true_value, false_value) = match_types_at(true_value, false_value, &loc)?;
1600    if let Some(imm) = cond.downcast_ref::<IntImmObj>() {
1601        return Ok(if imm.value.is_zero() { false_value } else { true_value });
1602    }
1603    let ty = true_value.ty.clone();
1604    call(Some(&ty), "prim.if_then_else", vec![cond, true_value, false_value], loc)
1605}
1606
1607fn fold_conditions(
1608    conds: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>,
1609    loc: Location,
1610    name: &str,
1611    op: fn(PrimExpr, PrimExpr, Location) -> Result<PrimExpr>,
1612) -> Result<PrimExpr> {
1613    let mut conds = conds.into_iter().map(IntoExpr::into_owned_expr);
1614    let Some(first) = conds.next() else {
1615        tvm_ffi::bail!(VALUE_ERROR, "{name} must take at least 1 argument");
1616    };
1617    conds.try_fold(first?, |acc, cond| op(acc, cond?, loc.clone()))
1618}
1619
1620// ---------------------------------------------------------------------------------------------
1621// Bitwise operators
1622
1623unlocated! {
1624    /// Build `a << b` of two integers.
1625    ///
1626    /// # Errors
1627    ///
1628    /// Returns an `InternalError` if an operand is not an integer, or a constant shift amount is
1629    /// negative or not less than the width.
1630    shift_left(a: impl Operand, b: impl Operand) => shift_left_at;
1631    /// Build `a >> b` of two integers, sign-extending.
1632    ///
1633    /// # Errors
1634    ///
1635    /// Returns an `InternalError` if an operand is not an integer, or a constant shift amount is
1636    /// negative or not less than the width.
1637    shift_right(a: impl Operand, b: impl Operand) => shift_right_at;
1638    /// Build the node `~a` of an integer or boolean, which neither promotes nor folds.
1639    ///
1640    /// # Errors
1641    ///
1642    /// Returns an `InternalError` if `a` is not an integer or boolean.
1643    bitwise_not(a: impl IntoExpr<PrimExpr>) => bitwise_not_at;
1644}
1645
1646/// Build [`shift_left`] at the location `loc`.
1647pub fn shift_left_at(
1648    a: impl Operand,
1649    b: impl Operand,
1650    loc: impl IntoArg<Location>,
1651) -> Result<PrimExpr> {
1652    let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1653    check_operands(&a, &b, "<<", "left shift", "integer", (&INTEGER, INTEGER_CODES))?;
1654    let (a, b) = match_types_at(a, b, &loc)?;
1655    let ty = a.prim_ty().clone();
1656    let shift = |x: &BigInt, y: &BigInt| {
1657        let value = x.try_shl(y.clone())?;
1658        Ok(const_fold::is_representable(&value, &ty).then_some(value))
1659    };
1660    match fold_shift(&a, &b, shift, &loc)? {
1661        Some(folded) => Ok(folded),
1662        None => Ok(LShift::new(a, b, loc)?.into()),
1663    }
1664}
1665
1666/// Build [`shift_right`] at the location `loc`.
1667pub fn shift_right_at(
1668    a: impl Operand,
1669    b: impl Operand,
1670    loc: impl IntoArg<Location>,
1671) -> Result<PrimExpr> {
1672    let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1673    check_operands(&a, &b, ">>", "right shift", "integer", (&INTEGER, INTEGER_CODES))?;
1674    let (a, b) = match_types_at(a, b, &loc)?;
1675    match fold_shift(&a, &b, |x, y| x.try_shr(y.clone()).map(Some), &loc)? {
1676        Some(folded) => Ok(folded),
1677        None => Ok(RShift::new(a, b, loc)?.into()),
1678    }
1679}
1680
1681/// The bitwise operators of integers or booleans, which fold two constants of index types.
1682macro_rules! bitwise {
1683    ($($(#[$doc:meta])* $name:ident / $at:ident: $symbol:literal, $what:literal, $op:tt => $node:ident),+ $(,)?) => {
1684        $(
1685            $(#[$doc])*
1686            pub fn $name(a: impl Operand, b: impl Operand) -> Result<PrimExpr> {
1687                $at(a, b, UNKNOWN_LOC)
1688            }
1689
1690            #[doc = concat!("Build [`", stringify!($name), "`] at the location `loc`.")]
1691            pub fn $at(
1692                a: impl Operand,
1693                b: impl Operand,
1694                loc: impl IntoArg<Location>,
1695            ) -> Result<PrimExpr> {
1696                let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1697                let accepted = (&INTEGER_OR_BOOL[..], INTEGER_OR_BOOL_CODES);
1698                check_operands(&a, &b, $symbol, $what, "integer", accepted)?;
1699                let (a, b) = match_types_at(a, b, &loc)?;
1700                let ty = a.prim_ty();
1701                let index = const_fold::is_index_type(ty) && const_fold::is_index_type(b.prim_ty());
1702                if let (true, Some(x), Some(y)) =
1703                    (index, const_fold::int(&a), const_fold::int(&b))
1704                {
1705                    return Ok(IntImm::new(ty.clone(), x $op y, loc)?.into());
1706                }
1707                Ok($node::new(a, b, loc)?.into())
1708            }
1709        )+
1710    };
1711}
1712
1713bitwise!(
1714    /// Build `a & b` of two integers or booleans.
1715    ///
1716    /// # Errors
1717    ///
1718    /// Returns an `InternalError` if an operand is not an integer or boolean.
1719    bitwise_and / bitwise_and_at: "&", "bitwise AND", & => BitwiseAnd,
1720    /// Build `a | b` of two integers or booleans.
1721    ///
1722    /// # Errors
1723    ///
1724    /// Returns an `InternalError` if an operand is not an integer or boolean.
1725    bitwise_or / bitwise_or_at: "|", "bitwise OR", | => BitwiseOr,
1726    /// Build `a ^ b` of two integers or booleans.
1727    ///
1728    /// # Errors
1729    ///
1730    /// Returns an `InternalError` if an operand is not an integer or boolean.
1731    bitwise_xor / bitwise_xor_at: "^", "bitwise XOR", ^ => BitwiseXor,
1732);
1733
1734/// Build [`bitwise_not`] at the location `loc`.
1735pub fn bitwise_not_at(a: impl IntoExpr<PrimExpr>, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1736    let a = a.into_owned_expr()?;
1737    check_code(&a, "a", &INTEGER_OR_BOOL, INTEGER_OR_BOOL_CODES, || {
1738        format!(
1739            "Expected integer or boolean argument for ~ operator (bitwise NOT), but received {} \
1740             of type {}",
1741            a, a.ty
1742        )
1743    })?;
1744    Ok(BitwiseNot::new(a, loc)?.into())
1745}
1746
1747/// The folding of a shift of index types: a constant amount is checked against the width, two
1748/// constants fold to the value `shift` gives them, if any, and a shift by zero is the operand
1749/// itself (`TVM_PRIM_INDEX_CONST_PROPAGATION`).
1750fn fold_shift(
1751    a: &PrimExpr,
1752    b: &PrimExpr,
1753    shift: impl FnOnce(&BigInt, &BigInt) -> Result<Option<BigInt>>,
1754    loc: &Location,
1755) -> const_fold::Folded {
1756    let ty = a.prim_ty();
1757    if !const_fold::is_index_type(ty) || !const_fold::is_index_type(b.prim_ty()) {
1758        return Ok(None);
1759    }
1760    let (pa, pb) = (const_fold::int(a), const_fold::int(b));
1761    if let Some(y) = pb
1762        && (y.is_negative() || *y >= BigInt::from(i64::from(ty.bits())))
1763    {
1764        let condition = "pb->value >= 0 && pb->value < result_ty.bits()";
1765        let message = format!(
1766            "Shift amount must be non-negative and less than {} for type {}",
1767            ty.bits(),
1768            ty
1769        );
1770        return Err(support::check_failed(INTERNAL_ERROR, condition, &message));
1771    }
1772    if let (Some(x), Some(y)) = (pa, pb)
1773        && let Some(value) = shift(x, y)?
1774    {
1775        return Ok(Some(IntImm::new(ty.clone(), value, loc.clone())?.into()));
1776    }
1777    if pb.is_some_and(BigInt::is_zero) {
1778        return Ok(Some(a.clone()));
1779    }
1780    Ok(None)
1781}
1782
1783// ---------------------------------------------------------------------------------------------
1784// Math functions
1785
1786/// The unary math functions, each in a pair with its `_at` variant, implemented by a function
1787/// of the expression and the location.
1788macro_rules! unary {
1789    ($($(#[$doc:meta])* $name:ident / $at:ident => $imp:expr;)+) => {
1790        $(
1791            $(#[$doc])*
1792            pub fn $name(x: impl IntoExpr<PrimExpr>) -> Result<PrimExpr> {
1793                $at(x, UNKNOWN_LOC)
1794            }
1795
1796            #[doc = concat!("Build [`", stringify!($name), "`] at the location `loc`.")]
1797            pub fn $at(
1798                x: impl IntoExpr<PrimExpr>,
1799                loc: impl IntoArg<Location>,
1800            ) -> Result<PrimExpr> {
1801                $imp(x.into_owned_expr()?, loc.into_owned())
1802            }
1803        )+
1804    };
1805}
1806
1807unary! {
1808    /// Round `x` up.
1809    ceil / ceil_at => |x, loc| rounding(x, "prim.ceil", f64::ceil, loc);
1810    /// Round `x` down.
1811    floor / floor_at => |x, loc| rounding(x, "prim.floor", f64::floor, loc);
1812    /// Round `x` to the nearest integer; a constant folds a tie to even.
1813    round / round_at => |x, loc| rounding(x, "prim.round", f64::round_ties_even, loc);
1814    /// Round `x` to the nearest integer under the current rounding mode, a tie to even.
1815    nearbyint / nearbyint_at => |x, loc| rounding(x, "prim.nearbyint", f64::round_ties_even, loc);
1816    /// Round `x` towards zero.
1817    trunc / trunc_at => |x, loc| rounding(x, "prim.trunc", f64::trunc, loc);
1818    /// Build the absolute value of `x`; a constant folds.
1819    ///
1820    /// # Errors
1821    ///
1822    /// Returns an `InternalError` if `x` is not an integer or a float, such as a boolean.
1823    abs / abs_at => absolute;
1824    /// Build whether `x` is NaN.
1825    isnan / isnan_at => |x, loc| call(None, "prim.isnan", vec![x], loc);
1826    /// Build whether `x` is infinite.
1827    ///
1828    /// # Errors
1829    ///
1830    /// Returns an `InternalError` if `x` is not an integer or a float.
1831    isinf / isinf_at => infinite;
1832    /// Build whether `x` is finite.
1833    ///
1834    /// # Errors
1835    ///
1836    /// Returns an `InternalError` if `x` is not an integer or a float.
1837    isfinite / isfinite_at => finite;
1838    /// Mark `cond` as likely to hold; an integer constant is itself.
1839    likely / likely_at => likely_hint;
1840    /// Build a statement that `cond` holds, for simplifications.
1841    assume / assume_at => |cond, loc| {
1842        let ty: Type = PrimType::bool().into();
1843        call(Some(&ty), "prim.assume", vec![cond], loc)
1844    };
1845    /// Build the number of leading zero bits of `x`.
1846    clz / clz_at => |x: PrimExpr, loc| {
1847        let ty = x.ty.clone();
1848        call(Some(&ty), "prim.clz", vec![x], loc)
1849    };
1850}
1851
1852unlocated! {
1853    /// Create the largest value of the scalar type `ty`.
1854    ///
1855    /// # Errors
1856    ///
1857    /// Returns an `InternalError` if `ty` is a vector or has no largest value.
1858    max_value(ty: impl IntoArg<PrimType>) => max_value_at;
1859    /// Create the smallest value of the scalar type `ty`.
1860    ///
1861    /// # Errors
1862    ///
1863    /// Returns an `InternalError` if `ty` is a vector or has no smallest value.
1864    min_value(ty: impl IntoArg<PrimType>) => min_value_at;
1865    /// Create the positive infinity of the scalar `float16`, `float32` or `float64` type `ty`.
1866    ///
1867    /// # Errors
1868    ///
1869    /// Returns an `InternalError` if `ty` is a vector or not one of those types.
1870    infinity(ty: impl IntoArg<PrimType>) => infinity_at;
1871    /// Build the `int32` call `vscale()`, the factor of the lanes of a scalable vector
1872    /// (`prim.vscale`).
1873    vscale() => vscale_at;
1874}
1875
1876/// Build [`max_value`] at the location `loc`.
1877pub fn max_value_at(ty: impl IntoArg<PrimType>, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1878    let (ty, loc) = (ty.into_arg(), loc.into_arg());
1879    let (ty, loc): (&PrimType, &Location) = (ty.borrow(), loc.borrow());
1880    check_scalar(ty)?;
1881    let (code, bits) = (ty.dtype.code, ty.bits());
1882    let int = |value: BigInt| Ok(IntImm::new(ty, value, loc)?.into());
1883    let float = |value: f64| Ok(FloatImm::new(ty, value, loc)?.into());
1884    match code {
1885        support::INT if bits == 64 => int(BigInt::from(i64::MAX)),
1886        support::INT if bits < 64 => int(BigInt::from((1i64 << (bits - 1)) - 1)),
1887        support::UINT if bits == 64 => int(BigInt::from(u64::MAX)),
1888        support::UINT if bits < 64 => int(BigInt::from((1u64 << bits) - 1)),
1889        support::FLOAT if bits == 64 => float(f64::MAX),
1890        support::FLOAT if bits == 32 => float(f64::from(f32::MAX)),
1891        support::FLOAT if bits == 16 => float(support::MAX_FLOAT16),
1892        support::BFLOAT => float(support::MAX_BFLOAT16),
1893        _ if is_float4(code) => float(6.0),
1894        _ => match small_float_bound(code) {
1895            Some((max, _)) => float(max),
1896            None => {
1897                Err(tvm_ffi::format_err!(INTERNAL_ERROR, "Cannot decide max_value for type{ty}"))
1898            }
1899        },
1900    }
1901}
1902
1903/// Build [`min_value`] at the location `loc`.
1904pub fn min_value_at(ty: impl IntoArg<PrimType>, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1905    let (ty, loc) = (ty.into_arg(), loc.into_arg());
1906    let (ty, loc): (&PrimType, &Location) = (ty.borrow(), loc.borrow());
1907    check_scalar(ty)?;
1908    let (code, bits) = (ty.dtype.code, ty.bits());
1909    let int = |value: BigInt| Ok(IntImm::new(ty, value, loc)?.into());
1910    let float = |value: f64| Ok(FloatImm::new(ty, value, loc)?.into());
1911    match code {
1912        support::INT if bits == 64 => int(BigInt::from(i64::MIN)),
1913        support::INT if bits < 64 => int(BigInt::from(-(1i64 << (bits - 1)))),
1914        support::UINT => int(BigInt::from(0i64)),
1915        support::FLOAT if bits == 64 => float(f64::MIN),
1916        support::FLOAT if bits == 32 => float(f64::from(f32::MIN)),
1917        support::FLOAT if bits == 16 => float(-support::MAX_FLOAT16),
1918        support::BFLOAT => float(-support::MAX_BFLOAT16),
1919        _ if is_float4(code) => float(-6.0),
1920        _ => match small_float_bound(code) {
1921            Some((_, true)) => float(0.0),
1922            Some((max, false)) => float(-max),
1923            None => {
1924                Err(tvm_ffi::format_err!(INTERNAL_ERROR, "Cannot decide min_value for type{ty}"))
1925            }
1926        },
1927    }
1928}
1929
1930/// Build [`infinity`] at the location `loc`.
1931pub fn infinity_at(ty: impl IntoArg<PrimType>, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1932    let (ty, loc) = (ty.into_owned(), loc.into_owned());
1933    check_scalar(&ty)?;
1934    match (ty.dtype.code, ty.bits()) {
1935        (support::FLOAT, 64) => Ok(FloatImm::new(ty, f64::INFINITY, loc)?.into()),
1936        (support::FLOAT, 32 | 16) => Ok(FloatImm::new(ty, f64::from(f32::INFINITY), loc)?.into()),
1937        _ => Err(tvm_ffi::format_err!(INTERNAL_ERROR, "Cannot decide infinity for type {ty}")),
1938    }
1939}
1940
1941/// Build [`vscale`] at the location `loc`.
1942pub fn vscale_at(loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1943    let ty: Type = PrimType::int(32).into();
1944    call(Some(&ty), "prim.vscale", vec![], loc.into_owned())
1945}
1946
1947unlocated! {
1948    /// Build `x` to the power `y`, of two matched floats.
1949    ///
1950    /// # Errors
1951    ///
1952    /// Returns an `InternalError` if the operands are not floats or cannot be matched.
1953    pow(x: impl IntoExpr<PrimExpr>, y: impl IntoExpr<PrimExpr>) => pow_at;
1954    /// Build the floating-point remainder of `x / y`, of two matched floats.
1955    ///
1956    /// # Errors
1957    ///
1958    /// Returns an `InternalError` if the operands are not floats or cannot be matched.
1959    fmod(x: impl IntoExpr<PrimExpr>, y: impl IntoExpr<PrimExpr>) => fmod_at;
1960    /// Build `x * y + z` in one rounding.
1961    fma(
1962        x: impl IntoExpr<PrimExpr>,
1963        y: impl IntoExpr<PrimExpr>,
1964        z: impl IntoExpr<PrimExpr>
1965    ) => fma_at;
1966}
1967
1968/// Build [`pow`] at the location `loc`.
1969pub fn pow_at(
1970    x: impl IntoExpr<PrimExpr>,
1971    y: impl IntoExpr<PrimExpr>,
1972    loc: impl IntoArg<Location>,
1973) -> Result<PrimExpr> {
1974    float_binary(x.into_owned_expr()?, y.into_owned_expr()?, "prim.pow", "power", loc.into_owned())
1975}
1976
1977/// Build [`fmod`] at the location `loc`.
1978pub fn fmod_at(
1979    x: impl IntoExpr<PrimExpr>,
1980    y: impl IntoExpr<PrimExpr>,
1981    loc: impl IntoArg<Location>,
1982) -> Result<PrimExpr> {
1983    float_binary(x.into_owned_expr()?, y.into_owned_expr()?, "prim.fmod", "fmod", loc.into_owned())
1984}
1985
1986/// Build [`fma`] at the location `loc`.
1987pub fn fma_at(
1988    x: impl IntoExpr<PrimExpr>,
1989    y: impl IntoExpr<PrimExpr>,
1990    z: impl IntoExpr<PrimExpr>,
1991    loc: impl IntoArg<Location>,
1992) -> Result<PrimExpr> {
1993    let x = x.into_owned_expr()?;
1994    let ty = x.ty.clone();
1995    call(
1996        Some(&ty),
1997        "prim.fma",
1998        vec![x, y.into_owned_expr()?, z.into_owned_expr()?],
1999        loc.into_owned(),
2000    )
2001}
2002
2003/// `floor`, `ceil`, `round`, `nearbyint` and `trunc`: an integer or a boolean is itself, a float
2004/// constant is folded with `fold`, keeping its location, and anything else is a call.
2005fn rounding(
2006    x: PrimExpr,
2007    op: &'static str,
2008    fold: fn(f64) -> f64,
2009    loc: Location,
2010) -> Result<PrimExpr> {
2011    let ty = x.prim_ty();
2012    if ty.matches_code(&INTEGER_OR_BOOL) {
2013        return Ok(x);
2014    }
2015    if let Some(imm) = x.downcast_ref::<FloatImmObj>() {
2016        return Ok(FloatImm::new(ty.clone(), fold(imm.value), imm.loc.clone())?.into());
2017    }
2018    let ty = x.ty.clone();
2019    call(Some(&ty), op, vec![x], loc)
2020}
2021
2022fn absolute(x: PrimExpr, loc: Location) -> Result<PrimExpr> {
2023    match x.prim_ty().dtype.code {
2024        support::INT => integer_abs(x, loc),
2025        support::FLOAT | support::BFLOAT => match x.downcast_ref::<FloatImmObj>() {
2026            Some(imm) => {
2027                Ok(FloatImm::new(x.prim_ty().clone(), imm.value.abs(), imm.loc.clone())?.into())
2028            }
2029            None => {
2030                let ty = x.ty.clone();
2031                call(Some(&ty), "prim.fabs", vec![x], loc)
2032            }
2033        },
2034        support::UINT => Ok(x),
2035        _ => Err(tvm_ffi::format_err!(
2036            INTERNAL_ERROR,
2037            "Data type {} not supported for absolute op. Skipping absolute op...",
2038            x.ty
2039        )),
2040    }
2041}
2042
2043/// The absolute value of a signed integer: a constant folds when its absolute value is a
2044/// value of its type; anything else is `select(x >= 0, x, -x)`.
2045fn integer_abs(x: PrimExpr, loc: Location) -> Result<PrimExpr> {
2046    let ty = x.prim_ty();
2047    if let Some(imm) = x.downcast_ref::<IntImmObj>() {
2048        let value = match imm.value.is_negative() {
2049            true => -imm.value.clone(),
2050            false => imm.value.clone(),
2051        };
2052        if const_fold::is_representable(&value, ty) {
2053            return Ok(IntImm::new(ty.clone(), value, imm.loc.clone())?.into());
2054        }
2055    }
2056    let zero = make_const(ty.clone(), 0)?;
2057    let nonnegative = ge(x.clone(), zero)?;
2058    let negated = neg(x.clone())?;
2059    Ok(Select::new(nonnegative, x, negated, loc)?.into())
2060}
2061
2062fn infinite(x: PrimExpr, loc: Location) -> Result<PrimExpr> {
2063    let ty = x.prim_ty().clone();
2064    let result = PrimType::bool().with_lanes(support::lanes(&ty)? as u16)?;
2065    match ty.dtype.code {
2066        support::INT | support::UINT => make_const_at(result, false, loc),
2067        support::FLOAT => {
2068            let infinity = infinity_at(ty, loc.clone())?;
2069            let at_infinity = eq(abs_at(x.clone(), loc.clone())?, infinity)?;
2070            let not_nan = logical_not(isnan_at(x, loc)?)?;
2071            logical_and(at_infinity, not_nan)
2072        }
2073        _ => Err(tvm_ffi::format_err!(
2074            INTERNAL_ERROR,
2075            "Data type {} not supported for finiteness ops. Skipping it...",
2076            x.ty
2077        )),
2078    }
2079}
2080
2081fn finite(x: PrimExpr, loc: Location) -> Result<PrimExpr> {
2082    let not_infinite = logical_not(isinf_at(x.clone(), loc.clone())?)?;
2083    let not_nan = logical_not(isnan_at(x, loc)?)?;
2084    logical_and(not_infinite, not_nan)
2085}
2086
2087fn likely_hint(cond: PrimExpr, loc: Location) -> Result<PrimExpr> {
2088    if cond.downcast_ref::<IntImmObj>().is_some() {
2089        return Ok(cond);
2090    }
2091    let ty = cond.ty.clone();
2092    call(Some(&ty), "prim.likely", vec![cond], loc)
2093}
2094
2095/// The check `TVM_FFI_ICHECK_EQ(dtype.lanes(), 1)` of the limits.
2096fn check_scalar(ty: &PrimType) -> Result<()> {
2097    let lanes = support::lanes(ty)?;
2098    match lanes == 1 {
2099        true => Ok(()),
2100        false => Err(support::compare_failed(INTERNAL_ERROR, "dtype.lanes() == 1", lanes, 1, "")),
2101    }
2102}
2103
2104/// A function of two matched floats, called with the type of the first (`pow` and `fmod`).
2105fn float_binary(
2106    x: PrimExpr,
2107    y: PrimExpr,
2108    op: &'static str,
2109    what: &str,
2110    loc: Location,
2111) -> Result<PrimExpr> {
2112    let (x, y) = match_types_at(x, y, &loc)?;
2113    if !x.prim_ty().matches_code(&[DLDataTypeCode::kDLFloat]) {
2114        let condition = "x.ty().MatchesCode(DLDataTypeCode::kDLFloat)";
2115        let message = format!("{what} only applies to float");
2116        return Err(support::check_failed(INTERNAL_ERROR, condition, &message));
2117    }
2118    let ty = x.ty.clone();
2119    call(Some(&ty), op, vec![x, y], loc)
2120}
2121
2122// ---------------------------------------------------------------------------------------------
2123// Intrinsics
2124
2125/// The unary intrinsics; `float_only` marks `TVM_DECLARE_FLOAT_INTRIN_UNARY`.
2126macro_rules! unary_intrinsics {
2127    ($($(#[$doc:meta])* $name:ident / $at:ident => $op:literal, $float_only:literal;)+) => {
2128        unary! {
2129            $(
2130                $(#[$doc])*
2131                $name / $at => |x, loc| unary_intrinsic($op, x, $float_only, loc);
2132            )+
2133        }
2134    };
2135}
2136
2137unary_intrinsics! {
2138    /// Build `e` to the power `x`.
2139    exp / exp_at => "prim.exp", false;
2140    /// Build `2` to the power `x`.
2141    exp2 / exp2_at => "prim.exp2", false;
2142    /// Build `10` to the power `x`.
2143    exp10 / exp10_at => "prim.exp10", false;
2144    /// Build the error function of `x`.
2145    erf / erf_at => "prim.erf", false;
2146    /// Build the sigmoid of `x`.
2147    sigmoid / sigmoid_at => "prim.sigmoid", false;
2148    /// Build the square root of `x`.
2149    sqrt / sqrt_at => "prim.sqrt", false;
2150    /// Build the reciprocal square root of `x`.
2151    rsqrt / rsqrt_at => "prim.rsqrt", false;
2152    /// Build the natural logarithm of `x`.
2153    log / log_at => "prim.log", false;
2154    /// Build the base-2 logarithm of `x`.
2155    log2 / log2_at => "prim.log2", false;
2156    /// Build the base-10 logarithm of `x`.
2157    log10 / log10_at => "prim.log10", false;
2158    /// Build `log(1 + x)`.
2159    log1p / log1p_at => "prim.log1p", false;
2160    /// Build the number of set bits of `x`.
2161    popcount / popcount_at => "prim.popcount", false;
2162    /// Build the hyperbolic tangent of the float `x`.
2163    tanh / tanh_at => "prim.tanh", true;
2164    /// Build the tangent of the float `x`.
2165    tan / tan_at => "prim.tan", true;
2166    /// Build the cosine of the float `x`.
2167    cos / cos_at => "prim.cos", true;
2168    /// Build the hyperbolic cosine of the float `x`.
2169    cosh / cosh_at => "prim.cosh", true;
2170    /// Build the sine of the float `x`.
2171    sin / sin_at => "prim.sin", true;
2172    /// Build the hyperbolic sine of the float `x`.
2173    sinh / sinh_at => "prim.sinh", true;
2174    /// Build the arc sine of the float `x`.
2175    asin / asin_at => "prim.asin", true;
2176    /// Build the arc cosine of the float `x`.
2177    acos / acos_at => "prim.acos", true;
2178    /// Build the arc tangent of the float `x`.
2179    atan / atan_at => "prim.atan", true;
2180    /// Build the inverse hyperbolic cosine of the float `x`.
2181    acosh / acosh_at => "prim.acosh", true;
2182    /// Build the inverse hyperbolic sine of the float `x`.
2183    asinh / asinh_at => "prim.asinh", true;
2184    /// Build the inverse hyperbolic tangent of the float `x`.
2185    atanh / atanh_at => "prim.atanh", true;
2186}
2187
2188/// The binary intrinsics, calls typed as their first argument, whose arguments are not matched
2189/// (`TVM_DECLARE_INTRIN_BINARY`).
2190macro_rules! binary_intrinsics {
2191    ($($(#[$doc:meta])* $name:ident / $at:ident => $op:literal;)+) => {
2192        $(
2193            $(#[$doc])*
2194            pub fn $name(
2195                x: impl IntoExpr<PrimExpr>,
2196                y: impl IntoExpr<PrimExpr>,
2197            ) -> Result<PrimExpr> {
2198                $at(x, y, UNKNOWN_LOC)
2199            }
2200
2201            #[doc = concat!("Build [`", stringify!($name), "`] at the location `loc`.")]
2202            pub fn $at(
2203                x: impl IntoExpr<PrimExpr>,
2204                y: impl IntoExpr<PrimExpr>,
2205                loc: impl IntoArg<Location>,
2206            ) -> Result<PrimExpr> {
2207                let x = x.into_owned_expr()?;
2208                let ty = x.ty.clone();
2209                call(Some(&ty), $op, vec![x, y.into_owned_expr()?], loc.into_owned())
2210            }
2211        )+
2212    };
2213}
2214
2215binary_intrinsics! {
2216    /// Build the arc tangent of `x / y`, by the signs of both.
2217    atan2 / atan2_at => "prim.atan2";
2218    /// Build the next representable value after `x` towards `y`.
2219    nextafter / nextafter_at => "prim.nextafter";
2220    /// Build `x` with the sign of `y`.
2221    copysign / copysign_at => "prim.copysign";
2222    /// Build `sqrt(x * x + y * y)`.
2223    hypot / hypot_at => "prim.hypot";
2224    /// Build `x * 2 ^ y`.
2225    ldexp / ldexp_at => "prim.ldexp";
2226}
2227
2228/// A unary intrinsic `op`, a call typed as its argument. A bfloat16 argument is computed in
2229/// float32 and cast back; with `float_only`, any argument but a float or a bfloat16 is a
2230/// `TypeError`.
2231fn unary_intrinsic(
2232    op: &'static str,
2233    x: PrimExpr,
2234    float_only: bool,
2235    loc: Location,
2236) -> Result<PrimExpr> {
2237    let ty = x.prim_ty().clone();
2238    if float_only && !ty.matches_code(&[DLDataTypeCode::kDLFloat]) && !is_bfloat16(&ty) {
2239        let condition = "dtype.code() == DLDataTypeCode::kDLFloat || \
2240                         dtype.MatchesElementType(DLDataTypeCode::kDLBfloat, 16)";
2241        let message = format!("{op} only supports floating-point inputs, but got {}", x.ty);
2242        return Err(support::check_failed(TYPE_ERROR, condition, &message));
2243    }
2244    if !is_bfloat16(&ty) {
2245        let ty = x.ty.clone();
2246        return call(Some(&ty), op, vec![x], loc);
2247    }
2248    let float32 = ty.with_code(DLDataTypeCode::kDLFloat)?.with_bits(32)?;
2249    let x_float32: PrimExpr = Cast::new(float32.clone(), x, loc.clone())?.into();
2250    let result = call(Some(&float32.into()), op, vec![x_float32], loc.clone())?;
2251    Ok(Cast::new(ty, result, loc)?.into())
2252}
2253
2254// ---------------------------------------------------------------------------------------------
2255// Data type queries and operand checks the operators share
2256
2257/// The `float4` type code.
2258const FLOAT4: DLDataTypeCode = DLDataTypeCode::kDLFloat4_e2m1fn;
2259
2260/// Whether `code` is a float8 type code.
2261fn is_float8(code: u8) -> bool {
2262    support::float8_bound(code).is_some()
2263}
2264
2265/// Whether `code` is a float6 type code.
2266fn is_float6(code: u8) -> bool {
2267    support::float6_bound(code).is_some()
2268}
2269
2270/// The largest finite value of a float8 or float6 type, and whether the type is unsigned, its
2271/// minimum then 0.
2272fn small_float_bound(code: u8) -> Option<(f64, bool)> {
2273    support::float8_bound(code).or_else(|| support::float6_bound(code).map(|max| (max, false)))
2274}
2275
2276fn is_float4(code: u8) -> bool {
2277    FLOAT4 as u8 == code
2278}
2279
2280/// Whether `ty` has the element type bfloat16.
2281fn is_bfloat16(ty: &PrimType) -> bool {
2282    ty.matches_code(&[DLDataTypeCode::kDLBfloat]) && ty.bits() == 16
2283}
2284
2285/// The lanes of a vector type as an expression: the count, or `factor * vscale()` for a scalable
2286/// vector.
2287fn lanes_of(ty: &PrimType) -> Result<PrimExpr> {
2288    match ty.vscale_factor() {
2289        Some(factor) => {
2290            let factor = IntImm::int32(i32::from(factor));
2291            Ok(Mul::new(factor, vscale()?, UNKNOWN_LOC)?.into())
2292        }
2293        None => Ok(IntImm::int32(support::lanes(ty)?).into()),
2294    }
2295}
2296
2297/// `Call(ty, Op::Get(op), args, {}, {}, loc)`; without `ty` the constructor infers the type.
2298fn call(
2299    ty: Option<&Type>,
2300    op: &'static str,
2301    args: Vec<PrimExpr>,
2302    loc: Location,
2303) -> Result<PrimExpr> {
2304    let op = support::cached_op(op)?;
2305    PrimExpr::try_from(Expr::from(Call::new(ty, op, args, None, Vec::<Type>::new(), loc)?))
2306}
2307
2308/// Whether `expr` is a call of `prim.vscale`.
2309fn is_vscale_call(expr: &PrimExpr) -> Result<bool> {
2310    let Some(call) = expr.downcast_ref::<CallObj>() else { return Ok(false) };
2311    Ok(call.op.same_as(&support::cached_op("prim.vscale")?))
2312}
2313
2314/// The `TVM_FFI_ICHECK` an operation makes of an operand's type code: `codes` spells
2315/// the accepted codes as the error prints them, `message` what it reports.
2316fn check_code(
2317    operand: &PrimExpr,
2318    side: &str,
2319    accepted: &[DLDataTypeCode],
2320    codes: &str,
2321    message: impl FnOnce() -> String,
2322) -> Result<()> {
2323    if operand.prim_ty().matches_code(accepted) {
2324        return Ok(());
2325    }
2326    let condition = format!("{side}.ty().MatchesCode({codes})");
2327    Err(support::check_failed(INTERNAL_ERROR, &condition, &message()))
2328}
2329
2330const INTEGER: [DLDataTypeCode; 2] = [DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt];
2331const INTEGER_CODES: &str = "DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt";
2332const INTEGER_OR_BOOL: [DLDataTypeCode; 3] =
2333    [DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt, DLDataTypeCode::kDLBool];
2334const INTEGER_OR_BOOL_CODES: &str =
2335    "DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt, DLDataTypeCode::kDLBool";
2336const BOOLEAN: [DLDataTypeCode; 1] = [DLDataTypeCode::kDLBool];
2337const BOOL_CODES: &str = "DLDataTypeCode::kDLBool";
2338
2339/// `TVM_FFI_ICHECK(x.ty().MatchesCode(kDLInt, kDLUInt)) << x` of the integer divisions, on both
2340/// operands.
2341fn check_integers(a: &PrimExpr, b: &PrimExpr) -> Result<()> {
2342    check_code(a, "a", &INTEGER, INTEGER_CODES, || a.to_string())?;
2343    check_code(b, "b", &INTEGER, INTEGER_CODES, || b.to_string())
2344}
2345
2346/// The operand checks of an operator `symbol` (`what` names it) that takes `kind` arguments:
2347/// integers, integers or booleans, or booleans.
2348fn check_operands(
2349    a: &PrimExpr,
2350    b: &PrimExpr,
2351    symbol: &str,
2352    what: &str,
2353    kind: &str,
2354    (accepted, codes): (&[DLDataTypeCode], &str),
2355) -> Result<()> {
2356    for (operand, side, which) in [(a, "a", "LHS"), (b, "b", "RHS")] {
2357        check_code(operand, side, accepted, codes, || {
2358            format!(
2359                "Expected {kind} argument as {which} of {symbol} operator ({what}), but received \
2360                 {} of type {}",
2361                operand, operand.ty
2362            )
2363        })?;
2364    }
2365    Ok(())
2366}