1use 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#[allow(missing_docs)]
111#[repr(C)]
112#[derive(tvm_ffi::derive::ObjectRef, Clone)]
113pub struct Ramp {
114 data_: ObjectArc<RampObj>,
115}
116
117#[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 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);
179impl Ramp {
182 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 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#[allow(missing_docs)]
231#[repr(C)]
232#[derive(tvm_ffi::derive::ObjectRef, Clone)]
233pub struct Broadcast {
234 data_: ObjectArc<BroadcastObj>,
235}
236
237#[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 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);
290impl Broadcast {
293 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#[allow(missing_docs)]
317#[repr(C)]
318#[derive(tvm_ffi::derive::ObjectRef, Clone)]
319pub struct Shuffle {
320 data_: ObjectArc<ShuffleObj>,
321}
322
323#[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 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);
377impl Shuffle {
380 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
442fn 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
482pub(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
498fn 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}