1#![allow(clippy::too_many_arguments)]
21
22use crate::ir::attrs::DictAttrs;
82use crate::ir::expr::Call;
83use crate::ir::expr::CallObj;
84use crate::ir::expr::Expr;
85use crate::ir::expr::IntImm;
86use crate::ir::expr::IntImmObj;
87use crate::ir::expr::IntoExpr;
88use crate::ir::expr::PrimExpr;
89use crate::ir::expr::PrimVar;
90use crate::ir::expr::StringImm;
91use crate::ir::expr::Var;
92use crate::ir::location::Location;
93use crate::ir::location::UNKNOWN_LOC;
94use crate::ir::op::Op;
95use crate::ir::r#type::MissingType;
96use crate::ir::r#type::MissingTypeObj;
97use crate::ir::r#type::PrimType;
98use crate::ir::support;
99use std::ops::Deref;
100use std::sync::LazyLock;
101use tvm_ffi::Any;
102use tvm_ffi::AnyView;
103use tvm_ffi::Array;
104use tvm_ffi::BigInt;
105use tvm_ffi::DLDataTypeCode;
106use tvm_ffi::Error;
107use tvm_ffi::IntoArg;
108use tvm_ffi::Map;
109use tvm_ffi::Object;
110use tvm_ffi::ObjectArc;
111use tvm_ffi::ObjectRefCore;
112use tvm_ffi::Result;
113use tvm_ffi::String;
114use tvm_ffi::VALUE_ERROR;
115use tvm_ffi::reflection::NativeFunction;
116use tvm_ffi::reflection::TypeAttrColumn;
117#[allow(missing_docs)]
151#[repr(C)]
152#[derive(tvm_ffi::derive::ObjectRef, Clone)]
153pub struct Stmt {
154 data_: ObjectArc<StmtObj>,
155}
156
157#[allow(missing_docs)]
160#[repr(C)]
161#[derive(tvm_ffi::derive::Object)]
162#[object(type_key = "ir.Stmt", immutable, rs_parent)]
163pub struct StmtObj {
164 base_: Object,
165 pub loc: Location,
166}
167
168const _: () = {
169 assert!(::core::mem::size_of::<StmtObj>() == 32);
170 assert!(::core::mem::align_of::<StmtObj>() == 8);
171};
172
173#[allow(missing_docs)]
174impl StmtObj {
175 pub fn new(loc: Location) -> Self {
176 let base_ = Object::new();
177 Self { base_, loc }
178 }
179}
180#[allow(missing_docs)]
186#[repr(C)]
187#[derive(tvm_ffi::derive::ObjectRef, Clone)]
188pub struct Bind {
189 data_: ObjectArc<BindObj>,
190}
191
192#[allow(missing_docs)]
195#[repr(C)]
196#[derive(tvm_ffi::derive::Object)]
197#[object(type_key = "ir.Bind", final, immutable)]
198pub struct BindObj {
199 base_: StmtObj,
200 pub var: Var,
201 pub value: Expr,
202}
203
204const _: () = {
205 assert!(::core::mem::size_of::<BindObj>() == 48);
206 assert!(::core::mem::align_of::<BindObj>() == 8);
207};
208
209impl Deref for BindObj {
210 type Target = StmtObj;
211 fn deref(&self) -> &StmtObj {
212 &self.base_
213 }
214}
215
216#[allow(missing_docs)]
217impl BindObj {
218 pub(crate) fn new(loc: Location, var: Var, value: Expr) -> Self {
219 let base_ = StmtObj::new(loc);
220 Self { base_, var, value }
221 }
222}
223
224#[allow(missing_docs)]
225impl Bind {
226 pub fn from_fields(
228 loc: impl IntoArg<Location>,
229 var: impl IntoArg<Var>,
230 value: impl IntoArg<Expr>,
231 ) -> Self {
232 let obj = BindObj::new(loc.into_owned(), var.into_owned(), value.into_owned());
233 Self { data_: ObjectArc::new(obj) }
234 }
235}
236
237tvm_ffi::impl_object_ref_upcast!(Bind => Stmt);
238impl Bind {
241 pub fn new(
249 var: impl IntoArg<Var>,
250 value: impl IntoExpr,
251 loc: impl IntoArg<Location>,
252 ) -> Result<Self> {
253 let (var, value) = (var.into_owned(), value.into_owned_expr()?);
254 if !tvm_ffi::structural_equal(&value.ty, &var.ty)? {
255 let condition = "ffi::StructuralEqual()(value->ty, var->ty)";
256 return Err(support::check_failed(tvm_ffi::INTERNAL_ERROR, condition, ""));
257 }
258 Ok(Self::from_fields(loc.into_owned(), var, value))
259 }
260}
261
262#[allow(missing_docs)]
266#[repr(C)]
267#[derive(tvm_ffi::derive::ObjectRef, Clone)]
268pub struct AssertStmt {
269 data_: ObjectArc<AssertStmtObj>,
270}
271
272#[allow(missing_docs)]
275#[repr(C)]
276#[derive(tvm_ffi::derive::Object)]
277#[object(type_key = "ir.AssertStmt", final, immutable)]
278pub struct AssertStmtObj {
279 base_: StmtObj,
280 pub condition: PrimExpr,
281 pub error_kind: StringImm,
282 pub message_parts: Array<StringImm>,
283}
284
285const _: () = {
286 assert!(::core::mem::size_of::<AssertStmtObj>() == 56);
287 assert!(::core::mem::align_of::<AssertStmtObj>() == 8);
288};
289
290impl Deref for AssertStmtObj {
291 type Target = StmtObj;
292 fn deref(&self) -> &StmtObj {
293 &self.base_
294 }
295}
296
297#[allow(missing_docs)]
298impl AssertStmtObj {
299 pub(crate) fn new(
300 loc: Location,
301 condition: PrimExpr,
302 error_kind: StringImm,
303 message_parts: Array<StringImm>,
304 ) -> Self {
305 let base_ = StmtObj::new(loc);
306 Self { base_, condition, error_kind, message_parts }
307 }
308}
309
310#[allow(missing_docs)]
311impl AssertStmt {
312 pub fn from_fields(
314 loc: impl IntoArg<Location>,
315 condition: impl IntoArg<PrimExpr>,
316 error_kind: impl IntoArg<StringImm>,
317 message_parts: impl Into<Array<StringImm>>,
318 ) -> Self {
319 let obj = AssertStmtObj::new(
320 loc.into_owned(),
321 condition.into_owned(),
322 error_kind.into_owned(),
323 message_parts.into(),
324 );
325 Self { data_: ObjectArc::new(obj) }
326 }
327}
328
329tvm_ffi::impl_object_ref_upcast!(AssertStmt => Stmt);
330impl AssertStmt {
333 pub fn new(
340 condition: impl IntoExpr<PrimExpr>,
341 error_kind: impl IntoArg<StringImm>,
342 message_parts: impl IntoIterator<Item = impl IntoArg<StringImm>>,
343 loc: impl IntoArg<Location>,
344 ) -> Result<Self> {
345 let (condition, error_kind) = (condition.into_owned_expr()?, error_kind.into_owned());
346 let message_parts =
347 message_parts.into_iter().map(IntoArg::into_owned).collect::<Array<StringImm>>();
348 let condition_ty = condition.prim_ty();
349 if !condition_ty.matches_code(&[DLDataTypeCode::kDLBool]) {
350 let message = format!(
351 "AssertStmt should have boolean condition, but received {} with dtype {}",
352 condition, condition_ty
353 );
354 let check = "condition_ty.MatchesCode(DLDataTypeCode::kDLBool)";
355 return Err(support::check_failed(tvm_ffi::INTERNAL_ERROR, check, &message));
356 }
357 Ok(Self::from_fields(loc.into_owned(), condition, error_kind, message_parts))
358 }
359}
360
361#[allow(missing_docs)]
368#[repr(C)]
369#[derive(tvm_ffi::derive::ObjectRef, Clone)]
370pub struct For {
371 data_: ObjectArc<ForObj>,
372}
373
374#[allow(missing_docs)]
375#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
376#[repr(transparent)]
377pub struct ForKind(i32);
378
379#[allow(missing_docs)]
380#[allow(non_upper_case_globals)]
381impl ForKind {
382 pub const Default: Self = Self(0);
383 pub const Parallel: Self = Self(1);
384 pub const Vectorized: Self = Self(2);
385 pub const Unrolled: Self = Self(3);
386 pub const fn from_raw(value: i32) -> Self {
387 Self(value)
388 }
389 pub const fn as_raw(self) -> i32 {
390 self.0
391 }
392}
393
394impl TryFrom<i64> for ForKind {
395 type Error = Error;
396 fn try_from(value: i64) -> Result<Self> {
397 i32::try_from(value).map(Self).map_err(|_| {
398 Error::new(VALUE_ERROR, &format!("ForKind value {value} does not fit i32"))
399 })
400 }
401}
402
403#[allow(missing_docs)]
406#[repr(C)]
407#[derive(tvm_ffi::derive::Object)]
408#[object(type_key = "ir.For", final, immutable)]
409pub struct ForObj {
410 base_: StmtObj,
411 pub var: PrimVar,
412 pub begin: PrimExpr,
413 pub end: PrimExpr,
414 pub step: PrimExpr,
415 pub kind: ForKind,
416 pub body: SeqStmt,
417 pub annotations: Map<String, Any>,
418}
419
420const _: () = {
421 assert!(::core::mem::size_of::<ForObj>() == 88);
422 assert!(::core::mem::align_of::<ForObj>() == 8);
423};
424
425impl Deref for ForObj {
426 type Target = StmtObj;
427 fn deref(&self) -> &StmtObj {
428 &self.base_
429 }
430}
431
432#[allow(missing_docs)]
433impl ForObj {
434 pub(crate) fn new(
435 loc: Location,
436 var: PrimVar,
437 begin: PrimExpr,
438 end: PrimExpr,
439 step: PrimExpr,
440 kind: ForKind,
441 body: SeqStmt,
442 annotations: Map<String, Any>,
443 ) -> Self {
444 let base_ = StmtObj::new(loc);
445 Self { base_, var, begin, end, step, kind, body, annotations }
446 }
447}
448
449#[allow(missing_docs)]
450impl For {
451 pub fn from_fields(
453 loc: impl IntoArg<Location>,
454 var: impl IntoArg<PrimVar>,
455 begin: impl IntoArg<PrimExpr>,
456 end: impl IntoArg<PrimExpr>,
457 step: impl IntoArg<PrimExpr>,
458 kind: impl Into<ForKind>,
459 body: impl IntoArg<SeqStmt>,
460 annotations: impl Into<Map<String, Any>>,
461 ) -> Self {
462 let obj = ForObj::new(
463 loc.into_owned(),
464 var.into_owned(),
465 begin.into_owned(),
466 end.into_owned(),
467 step.into_owned(),
468 kind.into(),
469 body.into_owned(),
470 annotations.into(),
471 );
472 Self { data_: ObjectArc::new(obj) }
473 }
474}
475
476tvm_ffi::impl_object_ref_upcast!(For => Stmt);
477impl Default for ForKind {
480 fn default() -> Self {
482 Self::Default
483 }
484}
485
486impl For {
487 #[allow(clippy::too_many_arguments)]
497 pub fn new(
498 var: impl IntoArg<PrimVar>,
499 begin: impl IntoExpr<PrimExpr>,
500 end: impl IntoExpr<PrimExpr>,
501 step: impl IntoExpr<PrimExpr>,
502 kind: ForKind,
503 body: impl IntoArg<Stmt>,
504 annotations: impl Into<Option<Map<String, Any>>>,
505 loc: impl IntoArg<Location>,
506 ) -> Result<Self> {
507 let (var, begin, end, step) = (
508 var.into_owned(),
509 begin.into_owned_expr()?,
510 end.into_owned_expr()?,
511 step.into_owned_expr()?,
512 );
513 let var_expr: PrimExpr = var.clone().into();
514 let var_ty = var.prim_ty().clone();
515 let body = into_body(body.into_owned())?;
516 let annotations = annotations.into().unwrap_or_else(Map::new);
517 for (expr, field) in [(&var_expr, "var"), (&begin, "begin"), (&end, "end"), (&step, "step")]
518 {
519 let ty = expr.prim_ty();
520 if !ty.is_scalar()
521 || !ty.matches_code(&[DLDataTypeCode::kDLUInt, DLDataTypeCode::kDLInt])
522 {
523 let message = format!(
524 "TIR For nodes require a scalar integer as the {field}, but received {} with \
525 dtype {}",
526 expr, ty
527 );
528 let condition = "dtype.IsScalar() && (dtype.MatchesCode(DLDataTypeCode::kDLUInt, \
529 DLDataTypeCode::kDLInt))";
530 return Err(support::check_failed(tvm_ffi::INTERNAL_ERROR, condition, &message));
531 }
532 }
533 let promote = |expr: PrimExpr| -> Result<PrimExpr> {
535 let ty = expr.prim_ty().clone();
536 if ty.dtype == var_ty.dtype {
537 return Ok(expr);
538 }
539 if let Some(imm) = expr.downcast_ref::<IntImmObj>() {
540 if !int_imm_value_fits(&imm.value, &var_ty)? {
541 let message = format!(
542 "Literal value {} is not representable in the loop variable's dtype ({})",
543 imm.value, var_ty
544 );
545 let condition = "IntImmValueFits(a->value, var_ty)";
546 return Err(support::check_failed(
547 tvm_ffi::INTERNAL_ERROR,
548 condition,
549 &message,
550 ));
551 }
552 return Ok(IntImm::new(var_ty.clone(), imm.value.clone(), UNKNOWN_LOC)?.into());
553 }
554 if ty.bits() > var_ty.bits() {
555 let message = format!(
556 " Loop variable's dtype ({}) is narrower than that of `begin` or `end` ({})",
557 var_ty, ty
558 );
559 let condition = "e_ty.bits() <= var_ty.bits()";
560 return Err(support::check_failed(tvm_ffi::INTERNAL_ERROR, condition, &message));
561 }
562 Ok(expr)
563 };
564 let same_type = |expr: &PrimExpr, condition: &str| -> Result<()> {
565 let ty = expr.prim_ty();
566 if ty.dtype == var_ty.dtype {
567 return Ok(());
568 }
569 let message = format!("{var_ty} vs {ty}");
570 Err(support::check_failed(tvm_ffi::INTERNAL_ERROR, condition, &message))
571 };
572 let (begin, end) = (promote(begin)?, promote(end)?);
573 same_type(&begin, "var.ty() == begin.ty()")?;
574 same_type(&end, "var.ty() == end.ty()")?;
575 let step = promote(step)?;
576 same_type(&step, "var.ty() == step.ty()")?;
577 Ok(Self::from_fields(loc.into_owned(), var, begin, end, step, kind, body, annotations))
578 }
579}
580
581#[allow(missing_docs)]
584#[repr(C)]
585#[derive(tvm_ffi::derive::ObjectRef, Clone)]
586pub struct While {
587 data_: ObjectArc<WhileObj>,
588}
589
590#[allow(missing_docs)]
593#[repr(C)]
594#[derive(tvm_ffi::derive::Object)]
595#[object(type_key = "ir.While", final, immutable)]
596pub struct WhileObj {
597 base_: StmtObj,
598 pub condition: PrimExpr,
599 pub body: SeqStmt,
600}
601
602const _: () = {
603 assert!(::core::mem::size_of::<WhileObj>() == 48);
604 assert!(::core::mem::align_of::<WhileObj>() == 8);
605};
606
607impl Deref for WhileObj {
608 type Target = StmtObj;
609 fn deref(&self) -> &StmtObj {
610 &self.base_
611 }
612}
613
614#[allow(missing_docs)]
615impl WhileObj {
616 pub(crate) fn new(loc: Location, condition: PrimExpr, body: SeqStmt) -> Self {
617 let base_ = StmtObj::new(loc);
618 Self { base_, condition, body }
619 }
620}
621
622#[allow(missing_docs)]
623impl While {
624 pub fn from_fields(
626 loc: impl IntoArg<Location>,
627 condition: impl IntoArg<PrimExpr>,
628 body: impl IntoArg<SeqStmt>,
629 ) -> Self {
630 let obj = WhileObj::new(loc.into_owned(), condition.into_owned(), body.into_owned());
631 Self { data_: ObjectArc::new(obj) }
632 }
633}
634
635tvm_ffi::impl_object_ref_upcast!(While => Stmt);
636impl While {
639 pub fn new(
646 condition: impl IntoExpr<PrimExpr>,
647 body: impl IntoArg<Stmt>,
648 loc: impl IntoArg<Location>,
649 ) -> Result<Self> {
650 let condition = condition.into_owned_expr()?;
651 let body = into_body(body.into_owned())?;
652 if !condition.prim_ty().is_scalar() {
653 let check = "condition.ty().IsScalar()";
654 return Err(support::check_failed(tvm_ffi::INTERNAL_ERROR, check, ""));
655 }
656 Ok(Self::from_fields(loc, condition, body))
657 }
658}
659
660#[allow(missing_docs)]
664#[repr(C)]
665#[derive(tvm_ffi::derive::ObjectRef, Clone)]
666pub struct TensorStore {
667 data_: ObjectArc<TensorStoreObj>,
668}
669
670#[allow(missing_docs)]
673#[repr(C)]
674#[derive(tvm_ffi::derive::Object)]
675#[object(type_key = "ir.TensorStore", final, immutable)]
676pub struct TensorStoreObj {
677 base_: StmtObj,
678 pub dest: Expr,
679 pub indices: Array<PrimExpr>,
680 pub value: PrimExpr,
681}
682
683const _: () = {
684 assert!(::core::mem::size_of::<TensorStoreObj>() == 56);
685 assert!(::core::mem::align_of::<TensorStoreObj>() == 8);
686};
687
688impl Deref for TensorStoreObj {
689 type Target = StmtObj;
690 fn deref(&self) -> &StmtObj {
691 &self.base_
692 }
693}
694
695#[allow(missing_docs)]
696impl TensorStoreObj {
697 pub(crate) fn new(
698 loc: Location,
699 dest: Expr,
700 indices: Array<PrimExpr>,
701 value: PrimExpr,
702 ) -> Self {
703 let base_ = StmtObj::new(loc);
704 Self { base_, dest, indices, value }
705 }
706}
707
708#[allow(missing_docs)]
709impl TensorStore {
710 pub fn from_fields(
712 loc: impl IntoArg<Location>,
713 dest: impl IntoArg<Expr>,
714 indices: impl Into<Array<PrimExpr>>,
715 value: impl IntoArg<PrimExpr>,
716 ) -> Self {
717 let obj = TensorStoreObj::new(
718 loc.into_owned(),
719 dest.into_owned(),
720 indices.into(),
721 value.into_owned(),
722 );
723 Self { data_: ObjectArc::new(obj) }
724 }
725}
726
727tvm_ffi::impl_object_ref_upcast!(TensorStore => Stmt);
728impl TensorStore {
731 pub fn new(
739 dest: impl IntoExpr,
740 indices: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>,
741 value: impl IntoExpr<PrimExpr>,
742 loc: impl IntoArg<Location>,
743 ) -> Result<Self> {
744 static VALIDATE: LazyLock<Option<TypeAttrColumn>> =
746 LazyLock::new(|| TypeAttrColumn::lookup("__tvm_tensor_store_validate__"));
747 let (dest, value) = (dest.into_owned_expr()?, value.into_owned_expr()?);
748 let indices = indices
749 .into_iter()
750 .map(IntoExpr::into_owned_expr)
751 .collect::<Result<Array<PrimExpr>>>()?;
752 let ty_index = AnyView::from(&dest.ty).type_index();
753 let Some(validate) = VALIDATE.and_then(|column| column.get(ty_index)) else {
754 let message = format!(
755 "Type {} does not support TensorStore",
756 tvm_ffi::reflection::type_key(ty_index).unwrap_or_default()
757 );
758 return Err(support::check_failed(
759 tvm_ffi::TYPE_ERROR,
760 "validate.has_value()",
761 &message,
762 ));
763 };
764 let validate: NativeFunction<(&Expr, &Array<PrimExpr>, &PrimExpr)> =
767 unsafe { NativeFunction::from_any(validate)? };
768 validate.call((&dest, &indices, &value))?;
769 Ok(Self::from_fields(loc.into_owned(), dest, indices, value))
770 }
771}
772
773#[allow(missing_docs)]
780#[repr(C)]
781#[derive(tvm_ffi::derive::ObjectRef, Clone)]
782pub struct RegionStmt {
783 data_: ObjectArc<RegionStmtObj>,
784}
785
786#[allow(missing_docs)]
789#[repr(C)]
790#[derive(tvm_ffi::derive::Object)]
791#[object(type_key = "ir.RegionStmt", final, immutable)]
792pub struct RegionStmtObj {
793 base_: StmtObj,
794 pub op: Op,
795 pub args: Array<Expr>,
796 pub body_params: Array<Var>,
797 pub attrs: DictAttrs,
798 pub body: SeqStmt,
799 pub result_vars: Array<Var>,
800}
801
802const _: () = {
803 assert!(::core::mem::size_of::<RegionStmtObj>() == 80);
804 assert!(::core::mem::align_of::<RegionStmtObj>() == 8);
805};
806
807impl Deref for RegionStmtObj {
808 type Target = StmtObj;
809 fn deref(&self) -> &StmtObj {
810 &self.base_
811 }
812}
813
814#[allow(missing_docs)]
815impl RegionStmtObj {
816 pub(crate) fn new(
817 loc: Location,
818 op: Op,
819 args: Array<Expr>,
820 body_params: Array<Var>,
821 attrs: DictAttrs,
822 body: SeqStmt,
823 result_vars: Array<Var>,
824 ) -> Self {
825 let base_ = StmtObj::new(loc);
826 Self { base_, op, args, body_params, attrs, body, result_vars }
827 }
828}
829
830#[allow(missing_docs)]
831impl RegionStmt {
832 pub fn from_fields(
834 loc: impl IntoArg<Location>,
835 op: impl IntoArg<Op>,
836 args: impl Into<Array<Expr>>,
837 body_params: impl Into<Array<Var>>,
838 attrs: impl IntoArg<DictAttrs>,
839 body: impl IntoArg<SeqStmt>,
840 result_vars: impl Into<Array<Var>>,
841 ) -> Self {
842 let obj = RegionStmtObj::new(
843 loc.into_owned(),
844 op.into_owned(),
845 args.into(),
846 body_params.into(),
847 attrs.into_owned(),
848 body.into_owned(),
849 result_vars.into(),
850 );
851 Self { data_: ObjectArc::new(obj) }
852 }
853}
854
855tvm_ffi::impl_object_ref_upcast!(RegionStmt => Stmt);
856impl RegionStmt {
859 pub fn new(
868 op: impl IntoArg<Op>,
869 args: impl IntoIterator<Item = impl IntoExpr>,
870 body_params: impl IntoIterator<Item = impl IntoArg<Var>>,
871 attrs: impl IntoArg<DictAttrs>,
872 body: impl IntoArg<Stmt>,
873 result_vars: impl IntoIterator<Item = impl IntoArg<Var>>,
874 loc: impl IntoArg<Location>,
875 ) -> Result<Self> {
876 let (op, attrs, body) =
877 (op.into_owned(), attrs.into_owned(), into_body(body.into_owned())?);
878 let args =
879 args.into_iter().map(IntoExpr::into_owned_expr).collect::<Result<Array<Expr>>>()?;
880 let body_params = body_params.into_iter().map(IntoArg::into_owned).collect::<Array<Var>>();
881 let result_vars = result_vars.into_iter().map(IntoArg::into_owned).collect::<Array<Var>>();
882 let name = op.name.as_str().to_string();
883 let expected = region_body_params(&op, &args, &attrs)?;
884 if body_params.len() != expected.len() {
885 let condition = "body_params.size() == expected_params.size()";
886 let message = format!("{name} expects {} body parameters", expected.len());
887 let (given, wanted) = (body_params.len(), expected.len());
888 return Err(support::compare_failed(
889 tvm_ffi::VALUE_ERROR,
890 condition,
891 given,
892 wanted,
893 &message,
894 ));
895 }
896 for (i, (param, expected)) in body_params.iter().zip(expected.iter()).enumerate() {
897 if !tvm_ffi::structural_equal(¶m.ty, &expected.ty)? {
898 let condition =
899 "ffi::StructuralEqual()(body_params[i]->ty, expected_params[i]->ty)";
900 let message =
901 format!("{name} body parameter {i} has a type inconsistent with its contract");
902 return Err(support::check_failed(tvm_ffi::VALUE_ERROR, condition, &message));
903 }
904 }
905 let mut definitions = std::collections::HashSet::new();
906 for var in body_params.iter().chain(result_vars.iter()) {
907 if !definitions.insert(object_address(var)) {
908 let condition = "definitions.insert(var.get()).second";
909 let message = "RegionStmt parameters and results must be distinct definitions";
910 return Err(support::check_failed(tvm_ffi::VALUE_ERROR, condition, message));
911 }
912 }
913 let region =
914 Self::from_fields(loc.into_owned(), op, args, body_params, attrs, body, result_vars);
915 let validate =
917 unsafe { support::op_hook::<(&RegionStmtObj,), ()>(®ion.op, "FRegionValidate")? };
918 if let Some(validate) = validate {
919 validate.call((&*region,))?;
920 }
921 Ok(region)
922 }
923}
924
925#[allow(missing_docs)]
930#[repr(C)]
931#[derive(tvm_ffi::derive::ObjectRef, Clone)]
932pub struct SeqStmt {
933 data_: ObjectArc<SeqStmtObj>,
934}
935
936#[allow(missing_docs)]
939#[repr(C)]
940#[derive(tvm_ffi::derive::Object)]
941#[object(type_key = "ir.SeqStmt", final, immutable)]
942pub struct SeqStmtObj {
943 base_: StmtObj,
944 pub seq: Array<Stmt>,
945}
946
947const _: () = {
948 assert!(::core::mem::size_of::<SeqStmtObj>() == 40);
949 assert!(::core::mem::align_of::<SeqStmtObj>() == 8);
950};
951
952impl Deref for SeqStmtObj {
953 type Target = StmtObj;
954 fn deref(&self) -> &StmtObj {
955 &self.base_
956 }
957}
958
959#[allow(missing_docs)]
960impl SeqStmtObj {
961 pub(crate) fn new(loc: Location, seq: Array<Stmt>) -> Self {
962 let base_ = StmtObj::new(loc);
963 Self { base_, seq }
964 }
965}
966
967#[allow(missing_docs)]
968impl SeqStmt {
969 pub fn from_fields(loc: impl IntoArg<Location>, seq: impl Into<Array<Stmt>>) -> Self {
971 let obj = SeqStmtObj::new(loc.into_owned(), seq.into());
972 Self { data_: ObjectArc::new(obj) }
973 }
974}
975
976tvm_ffi::impl_object_ref_upcast!(SeqStmt => Stmt);
977impl SeqStmt {
980 pub fn new(
983 seq: impl IntoIterator<Item = impl IntoArg<Stmt>>,
984 loc: impl IntoArg<Location>,
985 ) -> Self {
986 let seq = seq.into_iter().map(IntoArg::into_owned).collect::<Array<Stmt>>();
987 Self::from_fields(loc.into_owned(), flatten(seq))
988 }
989}
990
991#[allow(missing_docs)]
995#[repr(C)]
996#[derive(tvm_ffi::derive::ObjectRef, Clone)]
997pub struct If {
998 data_: ObjectArc<IfObj>,
999}
1000
1001#[allow(missing_docs)]
1004#[repr(C)]
1005#[derive(tvm_ffi::derive::Object)]
1006#[object(type_key = "ir.If", final, immutable)]
1007pub struct IfObj {
1008 base_: StmtObj,
1009 pub condition: PrimExpr,
1010 pub then_case: SeqStmt,
1011 pub else_case: Option<SeqStmt>,
1012}
1013
1014const _: () = {
1015 assert!(::core::mem::size_of::<IfObj>() == 56);
1016 assert!(::core::mem::align_of::<IfObj>() == 8);
1017};
1018
1019impl Deref for IfObj {
1020 type Target = StmtObj;
1021 fn deref(&self) -> &StmtObj {
1022 &self.base_
1023 }
1024}
1025
1026#[allow(missing_docs)]
1027impl IfObj {
1028 pub(crate) fn new(
1029 loc: Location,
1030 condition: PrimExpr,
1031 then_case: SeqStmt,
1032 else_case: Option<SeqStmt>,
1033 ) -> Self {
1034 let base_ = StmtObj::new(loc);
1035 Self { base_, condition, then_case, else_case }
1036 }
1037}
1038
1039#[allow(missing_docs)]
1040impl If {
1041 pub fn from_fields(
1043 loc: impl IntoArg<Location>,
1044 condition: impl IntoArg<PrimExpr>,
1045 then_case: impl IntoArg<SeqStmt>,
1046 else_case: impl Into<Option<SeqStmt>>,
1047 ) -> Self {
1048 let obj = IfObj::new(
1049 loc.into_owned(),
1050 condition.into_owned(),
1051 then_case.into_owned(),
1052 else_case.into(),
1053 );
1054 Self { data_: ObjectArc::new(obj) }
1055 }
1056}
1057
1058tvm_ffi::impl_object_ref_upcast!(If => Stmt);
1059impl If {
1062 pub fn new(
1064 condition: impl IntoExpr<PrimExpr>,
1065 then_case: impl IntoArg<Stmt>,
1066 else_case: Option<&Stmt>,
1067 loc: impl IntoArg<Location>,
1068 ) -> Result<Self> {
1069 let condition = condition.into_owned_expr()?;
1070 let then_case = into_body(then_case.into_owned())?;
1071 let else_case = else_case.map(|stmt| into_body(stmt.clone())).transpose()?;
1072 Ok(Self::from_fields(loc.into_owned(), condition, then_case, else_case))
1073 }
1074}
1075
1076#[allow(missing_docs)]
1080#[repr(C)]
1081#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1082pub struct Evaluate {
1083 data_: ObjectArc<EvaluateObj>,
1084}
1085
1086#[allow(missing_docs)]
1089#[repr(C)]
1090#[derive(tvm_ffi::derive::Object)]
1091#[object(type_key = "ir.Evaluate", final, immutable)]
1092pub struct EvaluateObj {
1093 base_: StmtObj,
1094 pub value: Expr,
1095}
1096
1097const _: () = {
1098 assert!(::core::mem::size_of::<EvaluateObj>() == 40);
1099 assert!(::core::mem::align_of::<EvaluateObj>() == 8);
1100};
1101
1102impl Deref for EvaluateObj {
1103 type Target = StmtObj;
1104 fn deref(&self) -> &StmtObj {
1105 &self.base_
1106 }
1107}
1108
1109#[allow(missing_docs)]
1110impl EvaluateObj {
1111 pub(crate) fn new(loc: Location, value: Expr) -> Self {
1112 let base_ = StmtObj::new(loc);
1113 Self { base_, value }
1114 }
1115}
1116
1117#[allow(missing_docs)]
1118impl Evaluate {
1119 pub fn from_fields(loc: impl IntoArg<Location>, value: impl IntoArg<Expr>) -> Self {
1121 let obj = EvaluateObj::new(loc.into_owned(), value.into_owned());
1122 Self { data_: ObjectArc::new(obj) }
1123 }
1124}
1125
1126tvm_ffi::impl_object_ref_upcast!(Evaluate => Stmt);
1127impl Evaluate {
1130 pub fn new(value: impl IntoArg<Expr>, loc: impl IntoArg<Location>) -> Self {
1132 Self::from_fields(loc.into_owned(), value.into_owned())
1133 }
1134}
1135
1136#[allow(missing_docs)]
1139#[repr(C)]
1140#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1141pub struct Break {
1142 data_: ObjectArc<BreakObj>,
1143}
1144
1145#[allow(missing_docs)]
1148#[repr(C)]
1149#[derive(tvm_ffi::derive::Object)]
1150#[object(type_key = "ir.Break", final, immutable)]
1151pub struct BreakObj {
1152 base_: StmtObj,
1153}
1154
1155const _: () = {
1156 assert!(::core::mem::size_of::<BreakObj>() == 32);
1157 assert!(::core::mem::align_of::<BreakObj>() == 8);
1158};
1159
1160impl Deref for BreakObj {
1161 type Target = StmtObj;
1162 fn deref(&self) -> &StmtObj {
1163 &self.base_
1164 }
1165}
1166
1167#[allow(missing_docs)]
1168impl BreakObj {
1169 pub(crate) fn new(loc: Location) -> Self {
1170 let base_ = StmtObj::new(loc);
1171 Self { base_ }
1172 }
1173}
1174
1175#[allow(missing_docs)]
1176impl Break {
1177 pub fn new(loc: impl IntoArg<Location>) -> Self {
1179 let obj = BreakObj::new(loc.into_owned());
1180 Self { data_: ObjectArc::new(obj) }
1181 }
1182}
1183
1184tvm_ffi::impl_object_ref_upcast!(Break => Stmt);
1185#[allow(missing_docs)]
1192#[repr(C)]
1193#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1194pub struct Return {
1195 data_: ObjectArc<ReturnObj>,
1196}
1197
1198#[allow(missing_docs)]
1201#[repr(C)]
1202#[derive(tvm_ffi::derive::Object)]
1203#[object(type_key = "ir.Return", final, immutable)]
1204pub struct ReturnObj {
1205 base_: StmtObj,
1206 pub value: Expr,
1207}
1208
1209const _: () = {
1210 assert!(::core::mem::size_of::<ReturnObj>() == 40);
1211 assert!(::core::mem::align_of::<ReturnObj>() == 8);
1212};
1213
1214impl Deref for ReturnObj {
1215 type Target = StmtObj;
1216 fn deref(&self) -> &StmtObj {
1217 &self.base_
1218 }
1219}
1220
1221#[allow(missing_docs)]
1222impl ReturnObj {
1223 pub(crate) fn new(loc: Location, value: Expr) -> Self {
1224 let base_ = StmtObj::new(loc);
1225 Self { base_, value }
1226 }
1227}
1228
1229#[allow(missing_docs)]
1230impl Return {
1231 pub fn from_fields(loc: impl IntoArg<Location>, value: impl IntoArg<Expr>) -> Self {
1233 let obj = ReturnObj::new(loc.into_owned(), value.into_owned());
1234 Self { data_: ObjectArc::new(obj) }
1235 }
1236}
1237
1238tvm_ffi::impl_object_ref_upcast!(Return => Stmt);
1239impl Return {
1242 pub fn new(value: impl IntoArg<Expr>, loc: impl IntoArg<Location>) -> Self {
1244 Self::from_fields(loc.into_owned(), value.into_owned())
1245 }
1246}
1247
1248#[allow(missing_docs)]
1251#[repr(C)]
1252#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1253pub struct Continue {
1254 data_: ObjectArc<ContinueObj>,
1255}
1256
1257#[allow(missing_docs)]
1260#[repr(C)]
1261#[derive(tvm_ffi::derive::Object)]
1262#[object(type_key = "ir.Continue", final, immutable)]
1263pub struct ContinueObj {
1264 base_: StmtObj,
1265}
1266
1267const _: () = {
1268 assert!(::core::mem::size_of::<ContinueObj>() == 32);
1269 assert!(::core::mem::align_of::<ContinueObj>() == 8);
1270};
1271
1272impl Deref for ContinueObj {
1273 type Target = StmtObj;
1274 fn deref(&self) -> &StmtObj {
1275 &self.base_
1276 }
1277}
1278
1279#[allow(missing_docs)]
1280impl ContinueObj {
1281 pub(crate) fn new(loc: Location) -> Self {
1282 let base_ = StmtObj::new(loc);
1283 Self { base_ }
1284 }
1285}
1286
1287#[allow(missing_docs)]
1288impl Continue {
1289 pub fn new(loc: impl IntoArg<Location>) -> Self {
1291 let obj = ContinueObj::new(loc.into_owned());
1292 Self { data_: ObjectArc::new(obj) }
1293 }
1294}
1295
1296tvm_ffi::impl_object_ref_upcast!(Continue => Stmt);
1297fn int_imm_value_fits(value: &BigInt, ty: &PrimType) -> Result<bool> {
1306 let bits = u32::from(ty.bits());
1307 if ty.matches_code(&[DLDataTypeCode::kDLUInt]) {
1308 let limit = BigInt::from(1i64).try_shl(bits as i64)?;
1309 return Ok(!value.is_negative() && *value < limit);
1310 }
1311 let limit = BigInt::from(1i64).try_shl(bits as i64 - 1)?;
1312 Ok(*value >= -limit.clone() && *value < limit)
1313}
1314
1315fn region_body_params(op: &Op, args: &Array<Expr>, attrs: &DictAttrs) -> Result<Array<Var>> {
1318 let name = op.name.as_str();
1319 let get_body_params =
1321 unsafe { support::op_hook::<(&CallObj,), Array<Var>>(op, "FRegionGetBodyParams")? };
1322 let Some(get_body_params) = get_body_params else {
1323 let message = format!(
1324 "{name} does not support region construction: FRegionGetBodyParams is required"
1325 );
1326 return Err(support::check_failed(tvm_ffi::VALUE_ERROR, "IsRegionOp(op)", &message));
1327 };
1328 let signature = Call::from_fields(
1329 UNKNOWN_LOC,
1330 MissingType::new(),
1331 op.clone(),
1332 args.clone(),
1333 Some(attrs.clone().into()),
1334 Array::from_vec(vec![]),
1335 );
1336 signature.validate()?;
1337 let params = get_body_params.call((&*signature,))?;
1338 let mut definitions = std::collections::HashSet::new();
1339 for param in params.iter() {
1340 if param.ty.downcast_ref::<MissingTypeObj>().is_some() {
1341 let condition = "!param->ty.as<MissingType>().has_value()";
1342 let message = format!("FRegionGetBodyParams for {name} must return typed variables");
1343 return Err(support::check_failed(tvm_ffi::VALUE_ERROR, condition, &message));
1344 }
1345 if !definitions.insert(object_address(param)) {
1346 let condition = "definitions.insert(param.get()).second";
1347 let message =
1348 format!("FRegionGetBodyParams for {name} must return distinct definitions");
1349 return Err(support::check_failed(tvm_ffi::VALUE_ERROR, condition, &message));
1350 }
1351 }
1352 Ok(params)
1353}
1354
1355fn object_address<T: ObjectRefCore>(value: &T) -> usize {
1357 ObjectArc::as_ptr(ObjectRefCore::data(value)) as usize
1359}
1360
1361fn flatten(seq: Array<Stmt>) -> Array<Stmt> {
1363 let nested_or_no_op =
1364 |stmt: &Stmt| stmt.downcast_ref::<SeqStmtObj>().is_some() || is_no_op(stmt);
1365 if !seq.iter().any(nested_or_no_op) {
1366 return seq;
1367 }
1368 fn append(stmt: Stmt, flattened: &mut Vec<Stmt>) {
1369 match stmt.downcast_ref::<SeqStmtObj>() {
1370 Some(nested) => nested.seq.iter().for_each(|child| append(child.clone(), flattened)),
1371 None if is_no_op(&stmt) => {}
1372 None => flattened.push(stmt),
1373 }
1374 }
1375 let mut flattened = Vec::new();
1376 seq.iter().for_each(|stmt| append(stmt.clone(), &mut flattened));
1377 Array::from_vec(flattened)
1378}
1379
1380fn is_no_op(stmt: &Stmt) -> bool {
1382 stmt.downcast_ref::<EvaluateObj>()
1383 .and_then(|evaluate| evaluate.value.downcast_ref::<IntImmObj>())
1384 .is_some_and(|imm| imm.value == BigInt::from(0i64))
1385}
1386
1387fn into_body(stmt: Stmt) -> Result<SeqStmt> {
1390 if stmt.downcast_ref::<SeqStmtObj>().is_some() {
1391 return Ok(stmt.downcast().expect("a SeqStmt"));
1392 }
1393 let loc = stmt.loc.clone();
1394 Ok(SeqStmt::from_fields(loc, flatten(Array::from_vec(vec![stmt]))))
1395}