1use crate::ir::attrs::Attrs;
55use crate::ir::attrs::AttrsObj;
56use crate::ir::expr::Call;
57use crate::ir::expr::Expr;
58use crate::ir::expr::FloatImm;
59use crate::ir::expr::IntoExpr;
60use crate::ir::expr::PrimExpr;
61use crate::ir::expr::StringImmObj;
62use crate::ir::location::Location;
63use crate::ir::location::UNKNOWN_LOC;
64use crate::ir::prim::op::ExprResult;
65use crate::ir::prim::op::PrimOps;
66use crate::ir::prim::op::add;
67use crate::ir::prim::op::exp;
68use crate::ir::prim::op::log;
69use crate::ir::prim::op::match_types_at;
70use crate::ir::r#type::PrimType;
71use crate::ir::r#type::PtrTypeObj;
72use crate::ir::r#type::Type;
73use crate::ir::support;
74use std::borrow::Borrow;
75use std::ops::Deref;
76use tvm_ffi::Array;
77use tvm_ffi::DLDataTypeCode;
78use tvm_ffi::INTERNAL_ERROR;
79use tvm_ffi::IntoArg;
80use tvm_ffi::Map;
81use tvm_ffi::ObjectArc;
82use tvm_ffi::ObjectRefCore;
83use tvm_ffi::Result;
84use tvm_ffi::String;
85use tvm_ffi::TYPE_ERROR;
86#[allow(missing_docs)]
97#[repr(C)]
98#[derive(tvm_ffi::derive::ObjectRef, Clone)]
99pub struct CallFFIKernelAttr {
100 data_: ObjectArc<CallFFIKernelAttrObj>,
101}
102
103#[allow(missing_docs)]
106#[repr(C)]
107#[derive(tvm_ffi::derive::Object)]
108#[object(type_key = "tirx.CallFFIKernelAttr", final, immutable)]
109pub struct CallFFIKernelAttrObj {
110 base_: AttrsObj,
111 pub launch_params: Array<String>,
112 pub launch_fields: Array<String>,
113 pub num_kernel_args: i64,
114 pub kernel_attrs: Map<String, i64>,
115}
116
117const _: () = {
118 assert!(::core::mem::size_of::<CallFFIKernelAttrObj>() == 56);
119 assert!(::core::mem::align_of::<CallFFIKernelAttrObj>() == 8);
120};
121
122impl Deref for CallFFIKernelAttrObj {
123 type Target = AttrsObj;
124 fn deref(&self) -> &AttrsObj {
125 &self.base_
126 }
127}
128
129#[allow(missing_docs)]
130impl CallFFIKernelAttrObj {
131 pub(crate) fn new(
132 launch_params: Array<String>,
133 launch_fields: Array<String>,
134 num_kernel_args: i64,
135 kernel_attrs: Map<String, i64>,
136 ) -> Self {
137 let base_ = AttrsObj::new();
138 Self { base_, launch_params, launch_fields, num_kernel_args, kernel_attrs }
139 }
140}
141
142#[allow(missing_docs)]
143impl CallFFIKernelAttr {
144 pub fn new(
146 launch_params: impl Into<Array<String>>,
147 launch_fields: impl Into<Array<String>>,
148 num_kernel_args: i64,
149 kernel_attrs: impl Into<Map<String, i64>>,
150 ) -> Self {
151 let obj = CallFFIKernelAttrObj::new(
152 launch_params.into(),
153 launch_fields.into(),
154 num_kernel_args,
155 kernel_attrs.into(),
156 );
157 Self { data_: ObjectArc::new(obj) }
158 }
159}
160
161tvm_ffi::impl_object_ref_upcast!(CallFFIKernelAttr => Attrs);
162pub fn logaddexp(a: impl IntoExpr<PrimExpr>, b: impl IntoExpr<PrimExpr>) -> Result<PrimExpr> {
173 logaddexp_at(a, b, UNKNOWN_LOC)
174}
175
176pub fn logaddexp_at(
178 a: impl IntoExpr<PrimExpr>,
179 b: impl IntoExpr<PrimExpr>,
180 loc: impl IntoArg<Location>,
181) -> Result<PrimExpr> {
182 let (a, b) = (a.into_owned_expr()?, b.into_owned_expr()?);
183 for (operand, side) in [(&a, "a"), (&b, "b")] {
184 if !operand.prim_ty().matches_code(&[DLDataTypeCode::kDLFloat]) {
185 let condition = format!("{side}.ty().MatchesCode(DLDataTypeCode::kDLFloat)");
186 let message = operand.to_string();
187 return Err(support::check_failed(INTERNAL_ERROR, &condition, &message));
188 }
189 }
190 let (a, b) = match_types_at(a, b, loc)?;
191 log(add(exp(a)?, exp(b)?)?)
192}
193
194pub fn reinterpret(ty: impl IntoArg<Type>, value: impl IntoExpr) -> Result<Expr> {
215 reinterpret_at(ty, value, UNKNOWN_LOC)
216}
217
218pub fn reinterpret_at(
220 ty: impl IntoArg<Type>,
221 value: impl IntoExpr,
222 loc: impl IntoArg<Location>,
223) -> Result<Expr> {
224 let (ty, value) = (ty.into_arg(), value.into_owned_expr()?);
225 let ty: &Type = ty.borrow();
226 let target_is_pointer = ty.downcast_ref::<PtrTypeObj>().is_some();
227 let source_is_pointer = value.ty.downcast_ref::<PtrTypeObj>().is_some();
228 let type_error = |condition: &str, message: std::string::String| {
229 Err(support::check_failed(TYPE_ERROR, condition, &message))
230 };
231 if value.downcast_ref::<StringImmObj>().is_some() {
232 if !target_is_pointer {
233 let message = format!("String reinterpret requires a pointer target, but got {ty}");
234 return type_error("target_ty.as<PtrTypeObj>()", message);
235 }
236 } else if let Some(target) = ty.downcast_ref::<PrimType>() {
237 if let Some(source) = value.ty.downcast_ref::<PrimType>() {
238 if source.dtype == target.dtype {
239 return Ok(value);
240 }
241 if !target.is_scalable_vector() && !source.is_scalable_vector() {
242 let bits =
243 |ty: &PrimType| ty.lanes().map(|lanes| u32::from(ty.bits()) * u32::from(lanes));
244 let float4 = [DLDataTypeCode::kDLFloat4_e2m1fn];
245 let same_size = bits(source) == bits(target)
246 || ((source.matches_code(&float4) || target.matches_code(&float4))
247 && source.storage_bytes() == target.storage_bytes());
248 if !same_size {
249 let condition = "value_bits == target_bits || \
250 ((value_dtype.MatchesCode(DLDataTypeCode::kDLFloat4_e2m1fn) || \
251 target_prim.MatchesCode(DLDataTypeCode::kDLFloat4_e2m1fn)) && \
252 value_dtype.StorageBytes() == target_prim.StorageBytes())";
253 let message = format!("Reinterpret requires size match {} vs {}", ty, value.ty);
254 return Err(support::check_failed(INTERNAL_ERROR, condition, &message));
255 }
256 }
257 } else {
258 if !source_is_pointer {
259 let message =
260 format!("Reinterpret source must be PrimType or PtrType, but got {}", value.ty);
261 return type_error("value->ty.as<PtrTypeObj>()", message);
262 }
263 if !is_scalar_int64(target) {
264 let condition = "target_dtype.value().IsScalar() && target_dtype.value().bits() == 64 && \
265 target_dtype.value().MatchesCode(DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt)";
266 let message = format!(
267 "Pointer reinterpret requires a scalar 64-bit integer target, but got {ty}"
268 );
269 return type_error(condition, message);
270 }
271 }
272 } else {
273 if !target_is_pointer {
274 let message = format!("Reinterpret target must be PrimType or PtrType, but got {ty}");
275 return type_error("target_ty.as<PtrTypeObj>()", message);
276 }
277 if let Some(source) = value.ty.downcast_ref::<PrimType>() {
278 if !is_scalar_int64(source) {
279 let condition = "source_dtype.value().IsScalar() && source_dtype.value().bits() == 64 && \
280 source_dtype.value().MatchesCode(DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt)";
281 let message = format!(
282 "Pointer reinterpret requires a scalar 64-bit integer source, but got {}",
283 value.ty
284 );
285 return type_error(condition, message);
286 }
287 } else if !source_is_pointer {
288 let message =
289 format!("Reinterpret source must be PrimType or PtrType, but got {}", value.ty);
290 return type_error("value->ty.as<PtrTypeObj>()", message);
291 }
292 }
293 let op = support::cached_op("tirx.reinterpret")?;
294 Ok(Call::new(Some(ty), op, vec![value], None, Vec::<Type>::new(), loc)?.into())
295}
296
297pub fn fast_erf_float_expr(arg: impl IntoExpr<PrimExpr>, bits: u8) -> Result<PrimExpr> {
300 let ty = PrimType::float(bits);
301 let constant =
303 |value: f32| -> ExprResult { FloatImm::new(&ty, f64::from(value), UNKNOWN_LOC).into() };
304 #[allow(clippy::excessive_precision)]
306 let alpha: [f32; 7] = [
307 -1.60960333262415e-02,
308 -2.95459980854025e-03,
309 -7.34990630326855e-04,
310 -5.69250639462346e-05,
311 -2.10102402082508e-06,
312 2.77068142495902e-08,
313 -2.72614225801306e-10,
314 ];
315 #[allow(clippy::excessive_precision)]
317 let beta: [f32; 5] = [
318 -1.42647390514189e-02,
319 -7.37332916720468e-03,
320 -1.68282697438203e-03,
321 -2.13374055278905e-04,
322 -1.45660718464996e-05,
323 ];
324 let x = arg.into_owned_expr()?.min(constant(4.0)).max(constant(-4.0));
325 let x2 = &x * &x;
326 let mut p = &x2 * constant(alpha[6]) + constant(alpha[5]);
328 for coefficient in alpha[..5].iter().rev() {
329 p = &x2 * p + constant(*coefficient);
330 }
331 p = &x * p;
332 let mut q = &x2 * constant(beta[4]) + constant(beta[3]);
333 for coefficient in beta[..3].iter().rev() {
334 q = &x2 * q + constant(*coefficient);
335 }
336 p.div(q).try_into()
337}
338
339pub fn gpu_thread_return() -> Result<PrimExpr> {
341 gpu_thread_return_at(UNKNOWN_LOC)
342}
343
344pub fn gpu_thread_return_at(loc: impl IntoArg<Location>) -> Result<PrimExpr> {
346 tvm_ffi::cached_global_func!("tirx.gpu_thread_return")
347 .call_tuple((loc.into_arg().borrow(),))?
348 .try_into()
349}
350
351fn is_scalar_int64(ty: &PrimType) -> bool {
353 ty.is_scalar()
354 && ty.bits() == 64
355 && ty.matches_code(&[DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt])
356}