tvm
Loading...
Searching...
No Matches
const_fold.h
Go to the documentation of this file.
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
24#ifndef TVM_IR_PRIM_CONST_FOLD_H_
25#define TVM_IR_PRIM_CONST_FOLD_H_
26
27#include <tvm/ffi/optional.h>
28#include <tvm/ir/prim/expr.h>
29#include <tvm/runtime/logging.h>
30
31#include <algorithm>
32#include <cmath>
33#include <limits>
34
35namespace tvm {
36namespace prim {
37
48template <typename Op>
49inline ffi::Optional<PrimExpr> TryConstFold(PrimExpr a, PrimExpr b);
50
60template <typename Op>
61inline ffi::Optional<PrimExpr> TryConstFold(PrimExpr a);
62
63namespace detail {
64
74inline bool IsIndexType(DLDataType type) {
75 return type.code == static_cast<uint8_t>(DLDataTypeCode::kDLInt) &&
76 (type.bits == 32 || type.bits == 64) && type.lanes == 1;
77}
78
79inline bool IsIndexTypedExpr(const ExprObj* expr) {
80 TVM_FFI_DCHECK(expr != nullptr);
81 TVM_FFI_DCHECK(!expr->ExprObj::ty.as<MissingType>().has_value());
82 const auto* prim_ty = expr->ExprObj::ty.as<PrimTypeObj>();
83 TVM_FFI_DCHECK(prim_ty != nullptr);
84 return IsIndexType(prim_ty->dtype);
85}
86
87inline bool IsIndexTypedExpr(const PrimExpr& expr) { return IsIndexTypedExpr(expr.get()); }
88
90inline bool IsRepresentable(const ffi::BigInt& value, const PrimType& dtype) {
91 if (!dtype.IsScalar() || dtype.bits() <= 0) return false;
92 if (auto small = value.as<int64_t>()) {
93 if (dtype.MatchesCode(DLDataTypeCode::kDLUInt)) {
94 return *small >= 0 &&
95 (dtype.bits() >= 63 || static_cast<uint64_t>(*small) < (uint64_t{1} << dtype.bits()));
96 }
97 if (dtype.MatchesCode(DLDataTypeCode::kDLBool) ||
98 (dtype.MatchesCode(DLDataTypeCode::kDLInt) && dtype.bits() == 1)) {
99 return *small == 0 || *small == 1;
100 }
101 if (dtype.MatchesCode(DLDataTypeCode::kDLInt)) {
102 if (dtype.bits() >= 64) return true;
103 int64_t limit = int64_t{1} << (dtype.bits() - 1);
104 return *small >= -limit && *small < limit;
105 }
106 return false;
107 }
108 if (dtype.MatchesCode(DLDataTypeCode::kDLUInt)) {
109 return value >= 0 && value < (ffi::BigInt(1) << dtype.bits());
110 }
111 if (dtype.MatchesCode(DLDataTypeCode::kDLInt) && dtype.bits() > 1) {
112 ffi::BigInt limit = ffi::BigInt(1) << (dtype.bits() - 1);
113 return value >= -limit && value < limit;
114 }
115 return false;
116}
117
119inline bool IsInFloat32Range(double value) {
120 return !std::isfinite(value) || (value >= std::numeric_limits<float>::lowest() &&
121 value <= std::numeric_limits<float>::max());
122}
123
124} // namespace detail
125
126#define TVM_PRIM_CONST_PROPAGATION(BODY) \
127 using tvm::FloatImmObj; \
128 const IntImmObj* pa = a.as<IntImmObj>(); \
129 const IntImmObj* pb = b.as<IntImmObj>(); \
130 const FloatImmObj* fa = a.as<FloatImmObj>(); \
131 const FloatImmObj* fb = b.as<FloatImmObj>(); \
132 BODY;
133
134#define TVM_PRIM_INDEX_CONST_PROPAGATION(BODY) \
135 const IntImmObj* pa = a.as<IntImmObj>(); \
136 const IntImmObj* pb = b.as<IntImmObj>(); \
137 if (::tvm::prim::detail::IsIndexTypedExpr(a) && ::tvm::prim::detail::IsIndexTypedExpr(b)) { \
138 BODY; \
139 }
140
141// specialization of constant folders.
142template <>
143inline ffi::Optional<PrimExpr> TryConstFold<prim::Add>(PrimExpr a, PrimExpr b) {
145 PrimType result_ty = a.ty();
146 if (pa && pb) {
147 ffi::BigInt res = pa->value + pb->value;
148 if (!detail::IsRepresentable(res, result_ty)) return std::nullopt;
149 return IntImm(result_ty, std::move(res));
150 }
151 if (pa && pa->value == 0) return b;
152 if (pb && pb->value == 0) return a;
153 if (fa && fb) {
154 if (result_ty.bits() == 32) {
155 float lhs = static_cast<float>(fa->value);
156 float rhs = static_cast<float>(fb->value);
157 // Check before rounding can turn a finite overflow into infinity.
158 if (!detail::IsInFloat32Range(static_cast<double>(lhs) + rhs)) return std::nullopt;
159 return FloatImm(result_ty, static_cast<float>(lhs + rhs));
160 } else if (result_ty.bits() == 64) {
161 return FloatImm(result_ty, fa->value + fb->value);
162 }
163 }
164 if (fa && fa->value == 0) return b;
165 if (fb && fb->value == 0) return a;
166 });
167 return std::nullopt;
168}
169
170template <>
171inline ffi::Optional<PrimExpr> TryConstFold<prim::Sub>(PrimExpr a, PrimExpr b) {
173 PrimType result_ty = a.ty();
174 if (pa && pb) {
175 ffi::BigInt res = pa->value - pb->value;
176 if (!detail::IsRepresentable(res, result_ty)) return std::nullopt;
177 return IntImm(result_ty, std::move(res));
178 }
179 if (pb && pb->value == 0) return a;
180 if (fa && fb) {
181 if (result_ty.bits() == 32) {
182 float lhs = static_cast<float>(fa->value);
183 float rhs = static_cast<float>(fb->value);
184 // Check before rounding can turn a finite overflow into infinity.
185 if (!detail::IsInFloat32Range(static_cast<double>(lhs) - rhs)) return std::nullopt;
186 return FloatImm(result_ty, static_cast<float>(lhs - rhs));
187 } else if (result_ty.bits() == 64) {
188 return FloatImm(result_ty, fa->value - fb->value);
189 }
190 }
191 if (fb && fb->value == 0) return a;
192 });
193 return std::nullopt;
194}
195
196template <>
197inline ffi::Optional<PrimExpr> TryConstFold<prim::Mul>(PrimExpr a, PrimExpr b) {
199 PrimType result_ty = a.ty();
200 if (pa && pb) {
201 ffi::BigInt res = pa->value * pb->value;
202 if (!detail::IsRepresentable(res, result_ty)) return std::nullopt;
203 return IntImm(result_ty, std::move(res));
204 }
205 if (pa) {
206 if (pa->value == 1) return b;
207 if (pa->value == 0) return a;
208 }
209 if (pb) {
210 if (pb->value == 1) return a;
211 if (pb->value == 0) return b;
212 }
213 if (fa && fb) {
214 if (result_ty.bits() == 32) {
215 float lhs = static_cast<float>(fa->value);
216 float rhs = static_cast<float>(fb->value);
217 // Check before rounding can turn a finite overflow into infinity.
218 if (!detail::IsInFloat32Range(static_cast<double>(lhs) * rhs)) return std::nullopt;
219 return FloatImm(result_ty, static_cast<float>(lhs * rhs));
220 } else if (result_ty.bits() == 64) {
221 return FloatImm(result_ty, fa->value * fb->value);
222 }
223 }
224 if (fa) {
225 if (fa->value == 1) return b;
226 if (fa->value == 0) return a;
227 }
228 if (fb) {
229 if (fb->value == 1) return a;
230 if (fb->value == 0) return b;
231 }
232 });
233 return std::nullopt;
234}
235
236template <>
237inline ffi::Optional<PrimExpr> TryConstFold<prim::Div>(PrimExpr a, PrimExpr b) {
239 PrimType result_ty = a.ty();
240 if (pa && pb) {
241 // due to division and mod can have different modes
242 // NOTE: this will assumes truc div.
243 TVM_FFI_ICHECK_NE(pb->value, 0) << "Divide by zero";
244 ffi::BigInt res = pa->value / pb->value;
245 if (!detail::IsRepresentable(res, result_ty)) return std::nullopt;
246 return IntImm(result_ty, std::move(res));
247 }
248 if (pa) {
249 if (pa->value == 0) return a;
250 }
251 if (pb) {
252 if (pb->value == 1) return a;
253 TVM_FFI_ICHECK_NE(pb->value, 0) << "Divide by zero";
254 }
255 if (fa && fb) {
256 TVM_FFI_ICHECK_NE(fb->value, 0) << "Divide by zero";
257 if (result_ty.bits() == 32) {
258 float lhs = static_cast<float>(fa->value);
259 float rhs = static_cast<float>(fb->value);
260 // Check before rounding can turn a finite overflow into infinity.
261 if (!detail::IsInFloat32Range(static_cast<double>(lhs) / rhs)) return std::nullopt;
262 return FloatImm(result_ty, static_cast<float>(lhs / rhs));
263 } else if (result_ty.bits() == 64) {
264 return FloatImm(result_ty, fa->value / fb->value);
265 }
266 }
267 if (fa && fa->value == 0) return a;
268 if (fb) {
269 if (fb->value == 1) return a;
270 TVM_FFI_ICHECK_NE(fb->value, 0) << "Divide by zero";
271 }
272 });
273 return std::nullopt;
274}
275
276template <>
277inline ffi::Optional<PrimExpr> TryConstFold<prim::Mod>(PrimExpr a, PrimExpr b) {
279 PrimType result_ty = a.ty();
280 if (pa && pb) {
281 TVM_FFI_ICHECK_NE(pb->value, 0) << "Divide by zero";
282 ffi::BigInt res = pa->value % pb->value;
283 if (!detail::IsRepresentable(res, result_ty)) return std::nullopt;
284 return IntImm(result_ty, std::move(res));
285 }
286 if (pa) {
287 if (pa->value == 0) return a;
288 }
289 if (pb) {
290 if (pb->value == 1) return IntImm(result_ty, 0);
291 TVM_FFI_ICHECK_NE(pb->value, 0) << "Divide by zero";
292 }
293 });
294 // Fold wide literals without enabling symbolic index rewrites for their type.
295 if (pa && pb && a.ty().bits() >= 64) {
296 TVM_FFI_ICHECK_NE(pb->value, 0) << "Divide by zero";
297 ffi::BigInt res = pa->value % pb->value;
298 if (!detail::IsRepresentable(res, a.ty())) return std::nullopt;
299 return IntImm(a.ty(), std::move(res));
300 }
301 return std::nullopt;
302}
303
304template <>
305inline ffi::Optional<PrimExpr> TryConstFold<prim::FloorDiv>(PrimExpr a, PrimExpr b) {
307 PrimType result_ty = a.ty();
308 if (pa && pb) {
309 TVM_FFI_ICHECK_NE(pb->value, 0) << "Divide by zero";
310 ffi::BigInt res = ffi::floordiv(pa->value, pb->value);
311 if (!detail::IsRepresentable(res, result_ty)) return std::nullopt;
312 return IntImm(result_ty, std::move(res));
313 }
314 if (pa) {
315 if (pa->value == 0) return a;
316 }
317 if (pb) {
318 if (pb->value == 1) return a;
319 TVM_FFI_ICHECK_NE(pb->value, 0) << "Divide by zero";
320 }
321 if (fa && fb && fb->value != 0) {
322 if (result_ty.bits() == 32) {
323 float lhs = static_cast<float>(fa->value);
324 float rhs = static_cast<float>(fb->value);
325 if (!detail::IsInFloat32Range(static_cast<double>(lhs) / rhs)) return std::nullopt;
326 float quotient = lhs / rhs;
327 return FloatImm(result_ty, std::floor(quotient));
328 } else if (result_ty.bits() == 64) {
329 return FloatImm(result_ty, std::floor(fa->value / fb->value));
330 } else {
331 return std::nullopt;
332 }
333 }
334 if (fa && fa->value == 0) return a;
335 if (fb) {
336 if (fb->value == 1) return a;
337 TVM_FFI_ICHECK_NE(fb->value, 0) << "Divide by zero";
338 }
339 });
340 return std::nullopt;
341}
342
343template <>
344inline ffi::Optional<PrimExpr> TryConstFold<prim::FloorMod>(PrimExpr a, PrimExpr b) {
346 PrimType result_ty = a.ty();
347 if (pa && pb) {
348 TVM_FFI_ICHECK_NE(pb->value, 0) << "Divide by zero";
349 ffi::BigInt res = ffi::floormod(pa->value, pb->value);
350 if (!detail::IsRepresentable(res, result_ty)) return std::nullopt;
351 return IntImm(result_ty, std::move(res));
352 }
353 if (pa) {
354 if (pa->value == 0) return a;
355 }
356 if (pb) {
357 if (pb->value == 1) return IntImm(result_ty, 0);
358 TVM_FFI_ICHECK_NE(pb->value, 0) << "Divide by zero";
359 }
360 });
361 // Fold wide literals without enabling symbolic index rewrites for their type.
362 if (pa && pb && (a.ty().bits() >= 64 || a.ty().MatchesCode(DLDataTypeCode::kDLUInt))) {
363 TVM_FFI_ICHECK_NE(pb->value, 0) << "Divide by zero";
364 ffi::BigInt res = ffi::floormod(pa->value, pb->value);
365 if (!detail::IsRepresentable(res, a.ty())) return std::nullopt;
366 return IntImm(a.ty(), std::move(res));
367 }
368 return std::nullopt;
369}
370
371template <>
372inline ffi::Optional<PrimExpr> TryConstFold<prim::Min>(PrimExpr a, PrimExpr b) {
374 PrimType result_ty = a.ty();
375 if (pa && pb) return IntImm(result_ty, std::min(pa->value, pb->value));
376 if (fa && fb) return std::isnan(fa->value) || fa->value < fb->value ? a : b;
377 });
378 if (a.same_as(b)) return a;
379 return std::nullopt;
380}
381
382template <>
383inline ffi::Optional<PrimExpr> TryConstFold<prim::Max>(PrimExpr a, PrimExpr b) {
385 PrimType result_ty = a.ty();
386 if (pa && pb) return IntImm(result_ty, std::max(pa->value, pb->value));
387 if (fa && fb) return std::isnan(fa->value) || fa->value > fb->value ? a : b;
388 });
389 if (a.same_as(b)) return a;
390 return std::nullopt;
391}
392
393template <>
394inline ffi::Optional<PrimExpr> TryConstFold<prim::GT>(PrimExpr a, PrimExpr b) {
396 if (pa && pb) return IntImm::Bool(pa->value > pb->value);
397 if (fa && fb) return IntImm::Bool(fa->value > fb->value);
398 });
399 return std::nullopt;
400}
401
402template <>
403inline ffi::Optional<PrimExpr> TryConstFold<prim::GE>(PrimExpr a, PrimExpr b) {
405 if (pa && pb) return IntImm::Bool(pa->value >= pb->value);
406 if (fa && fb) return IntImm::Bool(fa->value >= fb->value);
407 });
408 return std::nullopt;
409}
410
411template <>
412inline ffi::Optional<PrimExpr> TryConstFold<prim::LT>(PrimExpr a, PrimExpr b) {
414 if (pa && pb) return IntImm::Bool(pa->value < pb->value);
415 if (fa && fb) return IntImm::Bool(fa->value < fb->value);
416 });
417 return std::nullopt;
418}
419
420template <>
421inline ffi::Optional<PrimExpr> TryConstFold<prim::LE>(PrimExpr a, PrimExpr b) {
423 if (pa && pb) return IntImm::Bool(pa->value <= pb->value);
424 if (fa && fb) return IntImm::Bool(fa->value <= fb->value);
425 });
426 return std::nullopt;
427}
428
429template <>
430inline ffi::Optional<PrimExpr> TryConstFold<prim::EQ>(PrimExpr a, PrimExpr b) {
432 if (pa && pb) return IntImm::Bool(pa->value == pb->value);
433 if (fa && fb) return IntImm::Bool(fa->value == fb->value);
434 });
435 return std::nullopt;
436}
437
438template <>
439inline ffi::Optional<PrimExpr> TryConstFold<prim::NE>(PrimExpr a, PrimExpr b) {
441 if (pa && pb) return IntImm::Bool(pa->value != pb->value);
442 if (fa && fb) return IntImm::Bool(fa->value != fb->value);
443 });
444 return std::nullopt;
445}
446
447template <>
448inline ffi::Optional<PrimExpr> TryConstFold<prim::And>(PrimExpr a, PrimExpr b) {
449 const IntImmObj* pa = a.as<IntImmObj>();
450 const IntImmObj* pb = b.as<IntImmObj>();
451 if (pa && pa->value) return b;
452 if (pa && !pa->value) return a;
453 if (pb && pb->value) return a;
454 if (pb && !pb->value) return b;
455 return std::nullopt;
456}
457
458template <>
459inline ffi::Optional<PrimExpr> TryConstFold<prim::Or>(PrimExpr a, PrimExpr b) {
460 const IntImmObj* pa = a.as<IntImmObj>();
461 const IntImmObj* pb = b.as<IntImmObj>();
462 if (pa && pa->value) return a;
463 if (pa && !pa->value) return b;
464 if (pb && pb->value) return b;
465 if (pb && !pb->value) return a;
466 return std::nullopt;
467}
468
469template <>
470inline ffi::Optional<PrimExpr> TryConstFold<prim::Not>(PrimExpr a) {
471 const IntImmObj* pa = a.as<IntImmObj>();
472 if (pa) {
473 return IntImm::Bool(!(pa->value));
474 }
475 return std::nullopt;
476}
477
478} // namespace prim
479} // namespace tvm
480#endif // TVM_IR_PRIM_CONST_FOLD_H_
TIR expressions.
Base type of all the expressions.
Definition expr.h:66
static IntImm Bool(bool value, Location loc=UnknownLoc())
Construct a scalar boolean constant.
Definition expr.h:351
Managed reference to the MissingTypeObj singleton.
Definition type.h:126
Typed reference/view over any Expr whose ExprObj::ty is PrimType.
Definition expr.h:187
Primitive data types used in the low-level IR.
Definition type.h:164
Definition type.h:182
TVM_FFI_INLINE int32_t bits() const
Definition type.h:224
TVM_FFI_INLINE bool IsScalar() const
Whether this type is a scalar, excluding fixed and scalable vectors.
Definition type.h:259
TVM_FFI_INLINE bool MatchesCode(Codes... codes) const
Check whether the dtype code matches any of the provided DLPack codes.
Definition type.h:253
#define TVM_PRIM_CONST_PROPAGATION(BODY)
Definition const_fold.h:126
#define TVM_PRIM_INDEX_CONST_PROPAGATION(BODY)
Definition const_fold.h:134
bool IsIndexTypedExpr(const ExprObj *expr)
Definition const_fold.h:79
bool IsIndexType(DLDataType type)
Check whether type is used to represent index.
Definition const_fold.h:74
bool IsInFloat32Range(double value)
Check float32 range, allowing rounding and supported special values.
Definition const_fold.h:119
bool IsRepresentable(const ffi::BigInt &value, const PrimType &dtype)
Whether an exact integer is a valid literal of the given scalar type.
Definition const_fold.h:90
ffi::Optional< PrimExpr > TryConstFold< prim::Sub >(PrimExpr a, PrimExpr b)
Definition const_fold.h:171
ffi::Optional< PrimExpr > TryConstFold< prim::Not >(PrimExpr a)
Definition const_fold.h:470
ffi::Optional< PrimExpr > TryConstFold< prim::EQ >(PrimExpr a, PrimExpr b)
Definition const_fold.h:430
ffi::Optional< PrimExpr > TryConstFold< prim::Max >(PrimExpr a, PrimExpr b)
Definition const_fold.h:383
ffi::Optional< PrimExpr > TryConstFold< prim::GT >(PrimExpr a, PrimExpr b)
Definition const_fold.h:394
ffi::Optional< PrimExpr > TryConstFold< prim::LT >(PrimExpr a, PrimExpr b)
Definition const_fold.h:412
ffi::Optional< PrimExpr > TryConstFold(PrimExpr a, PrimExpr b)
Try to run binary compute with constant folding.
ffi::Optional< PrimExpr > TryConstFold< prim::LE >(PrimExpr a, PrimExpr b)
Definition const_fold.h:421
ffi::Optional< PrimExpr > TryConstFold< prim::Add >(PrimExpr a, PrimExpr b)
Definition const_fold.h:143
ffi::Optional< PrimExpr > TryConstFold< prim::Mul >(PrimExpr a, PrimExpr b)
Definition const_fold.h:197
ffi::Optional< PrimExpr > TryConstFold< prim::NE >(PrimExpr a, PrimExpr b)
Definition const_fold.h:439
ffi::Optional< PrimExpr > TryConstFold< prim::And >(PrimExpr a, PrimExpr b)
Definition const_fold.h:448
ffi::Optional< PrimExpr > TryConstFold< prim::Min >(PrimExpr a, PrimExpr b)
Definition const_fold.h:372
ffi::Optional< PrimExpr > TryConstFold< prim::Mod >(PrimExpr a, PrimExpr b)
Definition const_fold.h:277
ffi::Optional< PrimExpr > TryConstFold< prim::FloorMod >(PrimExpr a, PrimExpr b)
Definition const_fold.h:344
ffi::Optional< PrimExpr > TryConstFold< prim::Div >(PrimExpr a, PrimExpr b)
Definition const_fold.h:237
ffi::Optional< PrimExpr > TryConstFold< prim::GE >(PrimExpr a, PrimExpr b)
Definition const_fold.h:403
ffi::Optional< PrimExpr > TryConstFold< prim::Or >(PrimExpr a, PrimExpr b)
Definition const_fold.h:459
ffi::Optional< PrimExpr > TryConstFold< prim::FloorDiv >(PrimExpr a, PrimExpr b)
Definition const_fold.h:305
tvm::IntImmObj IntImmObj
Definition expr.h:49
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition analysis.h:41