Skip to main content

tvm_tirx/ir/prim/
vector_expr.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20//! Vector expressions. A vector is built from scalars by a [`Ramp`] (`lanes` values from `base`
21//! by `stride`) or a [`Broadcast`] (one value repeated), and rearranged by a [`Shuffle`]; its lane
22//! count is a constant or, for a scalable vector, `vscale() * factor`.
23
24// tvm-ffi-stubgen(file): mod(missing_docs = allow)
25// `custom_new` reserves `new` for a hand-written constructor (operand checks and the derived vector
26// type); the generated `from_fields` allocates the fields as given.
27// tvm-ffi-stubgen(object): prim.Ramp(custom_new, upcast = PrimExpr)
28// tvm-ffi-stubgen(object): prim.Broadcast(custom_new, upcast = PrimExpr)
29// tvm-ffi-stubgen(object): prim.Shuffle(custom_new, upcast = PrimExpr)
30// Every node is typed by a `PrimType` and holds `PrimExpr` operands: its allocator takes a
31// `PrimType`, and it converts into a `PrimExpr` without a check.
32// tvm-ffi-stubgen(field): prim.Ramp.ty(type = PrimType)
33// tvm-ffi-stubgen(field): prim.Ramp.base(type = PrimExpr)
34// tvm-ffi-stubgen(field): prim.Ramp.stride(type = PrimExpr)
35// tvm-ffi-stubgen(field): prim.Ramp.lanes(type = PrimExpr)
36// tvm-ffi-stubgen(field): prim.Broadcast.ty(type = PrimType)
37// tvm-ffi-stubgen(field): prim.Broadcast.value(type = PrimExpr)
38// tvm-ffi-stubgen(field): prim.Broadcast.lanes(type = PrimExpr)
39// tvm-ffi-stubgen(field): prim.Shuffle.ty(type = PrimType)
40// tvm-ffi-stubgen(field): prim.Shuffle.vectors(type = Array<PrimExpr>)
41// tvm-ffi-stubgen(field): prim.Shuffle.indices(type = Array<PrimExpr>)
42// Names the hand-written wrappers use: the import section keeps them even when no generated block
43// does.
44// tvm-ffi-stubgen(import): tvm_ffi::DLDataTypeCode
45// tvm-ffi-stubgen(import): tvm_ffi::ObjectRefCore
46// tvm-ffi-stubgen(import): tvm_ffi::Result
47// tvm-ffi-stubgen(import): crate::ir::expr::Call
48// tvm-ffi-stubgen(import): crate::ir::expr::CallObj
49// tvm-ffi-stubgen(import): crate::ir::expr::IntImm
50// tvm-ffi-stubgen(import): crate::ir::expr::IntImmObj
51// tvm-ffi-stubgen(import): crate::ir::location::UNKNOWN_LOC
52// tvm-ffi-stubgen(import): crate::ir::prim::expr::Mul
53// tvm-ffi-stubgen(import): crate::ir::prim::expr::MulObj
54// tvm-ffi-stubgen(import): crate::ir::r#type::PrimType
55// tvm-ffi-stubgen(import): crate::ir::expr::PrimExpr
56// tvm-ffi-stubgen(import): tvm_ffi::Array
57// tvm-ffi-stubgen(import): crate::ir::r#type::Type
58// tvm-ffi-stubgen(import): crate::ir::support
59// tvm-ffi-stubgen(import): crate::ir::prim::op::cast
60// tvm-ffi-stubgen(import): crate::ir::dtype::with_lanes
61// tvm-ffi-stubgen(import): crate::ir::expr::IntoExpr
62// tvm-ffi-stubgen(import): tvm_ffi::IntoArg
63
64// tvm-ffi-stubgen(begin): import-section
65use crate::ir::dtype::with_lanes;
66use crate::ir::expr::Call;
67use crate::ir::expr::CallObj;
68use crate::ir::expr::Expr;
69use crate::ir::expr::ExprObj;
70use crate::ir::expr::IntImm;
71use crate::ir::expr::IntImmObj;
72use crate::ir::expr::IntoExpr;
73use crate::ir::expr::PrimExpr;
74use crate::ir::location::Location;
75use crate::ir::location::UNKNOWN_LOC;
76use crate::ir::prim::expr::Mul;
77use crate::ir::prim::expr::MulObj;
78use crate::ir::prim::op::cast;
79use crate::ir::r#type::PrimType;
80use crate::ir::r#type::Type;
81use crate::ir::support;
82use std::ops::Deref;
83use tvm_ffi::Array;
84use tvm_ffi::DLDataTypeCode;
85use tvm_ffi::IntoArg;
86use tvm_ffi::ObjectArc;
87use tvm_ffi::ObjectRefCore;
88use tvm_ffi::Result;
89// tvm-ffi-stubgen(end)
90
91/// The vector of `lanes` values `base`, `base + stride`, ..., such as the indices of a vector
92/// load; `base` and `stride` are scalar `int32`, `int64`, `uint32` or `uint64`.
93///
94/// # Examples
95///
96/// ```
97/// use tvm_tirx::ir::prim::{Broadcast, Ramp};
98/// use tvm_tirx::ir::{PrimExpr, PrimType, PrimVar, UNKNOWN_LOC};
99/// use tvm_tirx::script::script;
100///
101/// let i = PrimVar::new("i", PrimType::int(32), UNKNOWN_LOC);
102/// let index = Ramp::new(&i * 4, 1, 4, UNKNOWN_LOC)?;
103/// assert_eq!(script(&index)?, "T.Ramp(i * 4, 1, 4)");
104///
105/// let shifted = PrimExpr::try_from(&index + Broadcast::new(&i, 4, UNKNOWN_LOC)?)?;
106/// assert_eq!(script(&shifted)?, "T.Ramp(i * 4, 1, 4) + T.Broadcast(i, 4)");
107/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
108/// ```
109// tvm-ffi-stubgen(begin): object/prim.Ramp
110#[allow(missing_docs)]
111#[repr(C)]
112#[derive(tvm_ffi::derive::ObjectRef, Clone)]
113pub struct Ramp {
114    data_: ObjectArc<RampObj>,
115}
116
117/// The object behind [`Ramp`].
118// Complete: reflected fields fill [40, 64) exactly.
119#[allow(missing_docs)]
120#[repr(C)]
121#[derive(tvm_ffi::derive::Object)]
122#[object(type_key = "prim.Ramp", final, immutable)]
123pub struct RampObj {
124    base_: ExprObj,
125    pub base: PrimExpr,
126    pub stride: PrimExpr,
127    pub lanes: PrimExpr,
128}
129
130const _: () = {
131    assert!(::core::mem::size_of::<RampObj>() == 64);
132    assert!(::core::mem::align_of::<RampObj>() == 8);
133};
134
135impl Deref for RampObj {
136    type Target = ExprObj;
137    fn deref(&self) -> &ExprObj {
138        &self.base_
139    }
140}
141
142#[allow(missing_docs)]
143impl RampObj {
144    pub(crate) fn new(
145        loc: Location,
146        ty: PrimType,
147        base: PrimExpr,
148        stride: PrimExpr,
149        lanes: PrimExpr,
150    ) -> Self {
151        let base_ = ExprObj::new(loc, ty.into());
152        Self { base_, base, stride, lanes }
153    }
154}
155
156#[allow(missing_docs)]
157impl Ramp {
158    /// Create a `Ramp` from its field values.
159    pub fn from_fields(
160        loc: impl IntoArg<Location>,
161        ty: impl IntoArg<PrimType>,
162        base: impl IntoArg<PrimExpr>,
163        stride: impl IntoArg<PrimExpr>,
164        lanes: impl IntoArg<PrimExpr>,
165    ) -> Self {
166        let obj = RampObj::new(
167            loc.into_owned(),
168            ty.into_owned(),
169            base.into_owned(),
170            stride.into_owned(),
171            lanes.into_owned(),
172        );
173        Self { data_: ObjectArc::new(obj) }
174    }
175}
176
177tvm_ffi::impl_object_ref_upcast!(Ramp => Expr);
178tvm_ffi::impl_object_ref_upcast!(unsafe Ramp => PrimExpr);
179// tvm-ffi-stubgen(end)
180
181impl Ramp {
182    /// Create the vector of `lanes` values from `base` by `stride`, with `stride` cast to the type
183    /// of `base`.
184    ///
185    /// # Errors
186    ///
187    /// Returns a `TypeError` if `base` or `stride` is not a scalar `int32`, `int64`, `uint32` or
188    /// `uint64`, or an `InternalError` if `lanes` is neither a constant greater than 1 nor
189    /// `vscale() * factor`.
190    pub fn new(
191        base: impl IntoExpr<PrimExpr>,
192        stride: impl IntoExpr<PrimExpr>,
193        lanes: impl IntoExpr<PrimExpr>,
194        loc: impl IntoArg<Location>,
195    ) -> Result<Self> {
196        let (base, stride, lanes) =
197            (base.into_owned_expr()?, stride.into_owned_expr()?, lanes.into_owned_expr()?);
198        let (base_ty, stride_ty) = (base.prim_ty().clone(), stride.prim_ty().clone());
199        // Only 32-bit and 64-bit integers step through the lanes of a ramp.
200        let index = |ty: &PrimType| {
201            ty.is_scalar()
202                && ty.matches_code(&[DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt])
203                && matches!(ty.bits(), 32 | 64)
204        };
205        for (field, ty) in [("base", &base_ty), ("stride", &stride_ty)] {
206            if !index(ty) {
207                let condition = format!(
208                    "{field}_ty.IsScalar() && \
209                     {field}_ty.MatchesCode(DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt) && \
210                     ({field}_ty.bits() == 32 || {field}_ty.bits() == 64)"
211                );
212                let message = format!(
213                    "Ramp {field} must be scalar int32, int64, uint32, or uint64, but got {}",
214                    ty
215                );
216                return Err(support::check_failed(tvm_ffi::TYPE_ERROR, &condition, &message));
217            }
218        }
219        let stride = match stride_ty.dtype == base_ty.dtype {
220            true => stride,
221            false => cast(stride, base_ty.clone())?,
222        };
223        let (ty, lanes) = vector_lanes(&base_ty, lanes)?;
224        Ok(Self::from_fields(loc.into_owned(), ty, base, stride, lanes))
225    }
226}
227
228/// The vector of `lanes` copies of the scalar `value`.
229// tvm-ffi-stubgen(begin): object/prim.Broadcast
230#[allow(missing_docs)]
231#[repr(C)]
232#[derive(tvm_ffi::derive::ObjectRef, Clone)]
233pub struct Broadcast {
234    data_: ObjectArc<BroadcastObj>,
235}
236
237/// The object behind [`Broadcast`].
238// Complete: reflected fields fill [40, 56) exactly.
239#[allow(missing_docs)]
240#[repr(C)]
241#[derive(tvm_ffi::derive::Object)]
242#[object(type_key = "prim.Broadcast", final, immutable)]
243pub struct BroadcastObj {
244    base_: ExprObj,
245    pub value: PrimExpr,
246    pub lanes: PrimExpr,
247}
248
249const _: () = {
250    assert!(::core::mem::size_of::<BroadcastObj>() == 56);
251    assert!(::core::mem::align_of::<BroadcastObj>() == 8);
252};
253
254impl Deref for BroadcastObj {
255    type Target = ExprObj;
256    fn deref(&self) -> &ExprObj {
257        &self.base_
258    }
259}
260
261#[allow(missing_docs)]
262impl BroadcastObj {
263    pub(crate) fn new(loc: Location, ty: PrimType, value: PrimExpr, lanes: PrimExpr) -> Self {
264        let base_ = ExprObj::new(loc, ty.into());
265        Self { base_, value, lanes }
266    }
267}
268
269#[allow(missing_docs)]
270impl Broadcast {
271    /// Create a `Broadcast` from its field values.
272    pub fn from_fields(
273        loc: impl IntoArg<Location>,
274        ty: impl IntoArg<PrimType>,
275        value: impl IntoArg<PrimExpr>,
276        lanes: impl IntoArg<PrimExpr>,
277    ) -> Self {
278        let obj = BroadcastObj::new(
279            loc.into_owned(),
280            ty.into_owned(),
281            value.into_owned(),
282            lanes.into_owned(),
283        );
284        Self { data_: ObjectArc::new(obj) }
285    }
286}
287
288tvm_ffi::impl_object_ref_upcast!(Broadcast => Expr);
289tvm_ffi::impl_object_ref_upcast!(unsafe Broadcast => PrimExpr);
290// tvm-ffi-stubgen(end)
291
292impl Broadcast {
293    /// Create the vector of `lanes` copies of the scalar `value`.
294    ///
295    /// # Errors
296    ///
297    /// Returns an `InternalError` if `value` is a vector, or `lanes` is neither a constant greater
298    /// than 1 nor `vscale() * factor`.
299    pub fn new(
300        value: impl IntoExpr<PrimExpr>,
301        lanes: impl IntoExpr<PrimExpr>,
302        loc: impl IntoArg<Location>,
303    ) -> Result<Self> {
304        let (value, lanes) = (value.into_owned_expr()?, lanes.into_owned_expr()?);
305        if !value.prim_ty().is_scalar() {
306            return Err(support::check_failed(tvm_ffi::INTERNAL_ERROR, "value_ty.IsScalar()", ""));
307        }
308        let (ty, lanes) = vector_lanes(value.prim_ty(), lanes)?;
309        Ok(Self::from_fields(loc.into_owned(), ty, value, lanes))
310    }
311}
312
313/// The vector of the lanes at `indices` of the concatenated `vectors`, which share an element
314/// type.
315// tvm-ffi-stubgen(begin): object/prim.Shuffle
316#[allow(missing_docs)]
317#[repr(C)]
318#[derive(tvm_ffi::derive::ObjectRef, Clone)]
319pub struct Shuffle {
320    data_: ObjectArc<ShuffleObj>,
321}
322
323/// The object behind [`Shuffle`].
324// Complete: reflected fields fill [40, 56) exactly.
325#[allow(missing_docs)]
326#[repr(C)]
327#[derive(tvm_ffi::derive::Object)]
328#[object(type_key = "prim.Shuffle", final, immutable)]
329pub struct ShuffleObj {
330    base_: ExprObj,
331    pub vectors: Array<PrimExpr>,
332    pub indices: Array<PrimExpr>,
333}
334
335const _: () = {
336    assert!(::core::mem::size_of::<ShuffleObj>() == 56);
337    assert!(::core::mem::align_of::<ShuffleObj>() == 8);
338};
339
340impl Deref for ShuffleObj {
341    type Target = ExprObj;
342    fn deref(&self) -> &ExprObj {
343        &self.base_
344    }
345}
346
347#[allow(missing_docs)]
348impl ShuffleObj {
349    pub(crate) fn new(
350        loc: Location,
351        ty: PrimType,
352        vectors: Array<PrimExpr>,
353        indices: Array<PrimExpr>,
354    ) -> Self {
355        let base_ = ExprObj::new(loc, ty.into());
356        Self { base_, vectors, indices }
357    }
358}
359
360#[allow(missing_docs)]
361impl Shuffle {
362    /// Create a `Shuffle` from its field values.
363    pub fn from_fields(
364        loc: impl IntoArg<Location>,
365        ty: impl IntoArg<PrimType>,
366        vectors: impl Into<Array<PrimExpr>>,
367        indices: impl Into<Array<PrimExpr>>,
368    ) -> Self {
369        let obj =
370            ShuffleObj::new(loc.into_owned(), ty.into_owned(), vectors.into(), indices.into());
371        Self { data_: ObjectArc::new(obj) }
372    }
373}
374
375tvm_ffi::impl_object_ref_upcast!(Shuffle => Expr);
376tvm_ffi::impl_object_ref_upcast!(unsafe Shuffle => PrimExpr);
377// tvm-ffi-stubgen(end)
378
379impl Shuffle {
380    /// Create the vector of the lanes at `indices` of the concatenated `vectors`.
381    ///
382    /// # Errors
383    ///
384    /// Returns an `InternalError` if `vectors` or `indices` is empty, the vectors have different
385    /// element types, or there are more indices than lanes.
386    pub fn new(
387        vectors: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>,
388        indices: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>,
389        loc: impl IntoArg<Location>,
390    ) -> Result<Self> {
391        let vectors = vectors
392            .into_iter()
393            .map(IntoExpr::into_owned_expr)
394            .collect::<Result<Array<PrimExpr>>>()?;
395        let indices = indices
396            .into_iter()
397            .map(IntoExpr::into_owned_expr)
398            .collect::<Result<Array<PrimExpr>>>()?;
399        let types = vectors.iter().map(|vector| vector.prim_ty().clone()).collect::<Vec<_>>();
400        let empty =
401            |condition: &str| support::compare_failed(tvm_ffi::INTERNAL_ERROR, condition, 0, 0, "");
402        let Some(first) = types.first() else { return Err(empty("vectors.size() != 0U")) };
403        if indices.is_empty() {
404            return Err(empty("indices.size() != 0U"));
405        }
406        let base_dtype = with_lanes(first.dtype, 1);
407        let mut total_lanes = 0;
408        for ty in &types {
409            if with_lanes(ty.dtype, 1) != base_dtype {
410                let condition = "val_ty.WithLanes(1)->dtype == base_type->dtype";
411                return Err(support::check_failed(tvm_ffi::INTERNAL_ERROR, condition, ""));
412            }
413            total_lanes += support::lanes(ty)?;
414        }
415        if indices.len() > total_lanes as usize {
416            let condition = "indices.size() <= static_cast<size_t>(total_lanes)";
417            let (count, total) = (indices.len(), total_lanes);
418            return Err(support::compare_failed(
419                tvm_ffi::INTERNAL_ERROR,
420                condition,
421                count,
422                total,
423                "",
424            ));
425        }
426        if indices.len() >= 32768 {
427            let condition = "indices.size() < 32768U";
428            let count = indices.len();
429            return Err(support::compare_failed(
430                tvm_ffi::INTERNAL_ERROR,
431                condition,
432                count,
433                32768,
434                "",
435            ));
436        }
437        let ty = PrimType::try_from(with_lanes(base_dtype, indices.len() as u16))?;
438        Ok(Self::from_fields(loc.into_owned(), ty, vectors, indices))
439    }
440}
441
442// ---------------------------------------------------------------------------------------------
443// Lanes the constructors share
444
445/// The vector type of `element` elements over `lanes`, and the lanes a `Ramp` or `Broadcast` keeps:
446/// a constant count as an `int32` constant, or a scalable count as `vscale * factor`.
447fn vector_lanes(element: &PrimType, lanes: PrimExpr) -> Result<(PrimType, PrimExpr)> {
448    if let Some(imm) = lanes.downcast_ref::<IntImmObj>() {
449        let Some(count) = imm.value.to_i64().and_then(|count| i32::try_from(count).ok()) else {
450            tvm_ffi::bail!(tvm_ffi::INTERNAL_ERROR, "lanes {} does not fit in i32", imm.value);
451        };
452        if count <= 1 {
453            return Err(support::compare_failed(
454                tvm_ffi::INTERNAL_ERROR,
455                "lanes > 1",
456                count,
457                1,
458                "",
459            ));
460        }
461        if count >= 32768 {
462            let condition = "lanes < 32768";
463            return Err(support::compare_failed(
464                tvm_ffi::INTERNAL_ERROR,
465                condition,
466                count,
467                32768,
468                "",
469            ));
470        }
471        let ty = PrimType::try_from(with_lanes(element.dtype, count as u16))?;
472        return Ok((ty, IntImm::int32(count).into()));
473    }
474    let Some(factor) = vscale_factor(&lanes)? else {
475        let message = format!("Invalid expression for scalable lanes {lanes}");
476        return Err(support::check_failed(tvm_ffi::INTERNAL_ERROR, "vscale_factor", &message));
477    };
478    let ty = PrimType::try_from(support::scalable_vector(element.dtype, factor)?)?;
479    Ok((ty, vscale_lanes(factor)?))
480}
481
482/// The lane count of a scalable vector of `factor` times `vscale` lanes, spelled
483/// `vscale() * factor`, both `int32`.
484pub(crate) fn vscale_lanes(factor: i32) -> Result<PrimExpr> {
485    let vscale = support::cached_op("prim.vscale")?;
486    let vscale: Expr = Call::new(
487        Some(&PrimType::int(32).into()),
488        vscale,
489        Vec::<Expr>::new(),
490        None,
491        Vec::<Type>::new(),
492        UNKNOWN_LOC,
493    )?
494    .into();
495    Ok(Mul::new(PrimExpr::try_from(vscale)?, IntImm::int32(factor), UNKNOWN_LOC)?.into())
496}
497
498/// `factor` when `lanes` is `factor * vscale` or `vscale * factor`.
499fn vscale_factor(lanes: &PrimExpr) -> Result<Option<i32>> {
500    let Some(mul) = lanes.downcast_ref::<MulObj>() else { return Ok(None) };
501    let vscale = support::cached_op("prim.vscale")?;
502    let is_vscale = |expr: &PrimExpr| {
503        expr.downcast_ref::<CallObj>().is_some_and(|call| call.op.same_as(&vscale))
504    };
505    let factor = |imm: &IntImmObj| imm.value.to_i64().and_then(|value| i32::try_from(value).ok());
506    if let Some(imm) = mul.a.downcast_ref::<IntImmObj>()
507        && is_vscale(&mul.b)
508    {
509        return Ok(factor(imm));
510    }
511    if let Some(imm) = mul.b.downcast_ref::<IntImmObj>()
512        && is_vscale(&mul.a)
513    {
514        return Ok(factor(imm));
515    }
516    Ok(None)
517}