1 | //===- MathExtras.h - Math functions relevant to MLIR -----------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file contains math functions relevant to MLIR. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef MLIR_SUPPORT_MATHEXTRAS_H_ |
14 | #define |
15 | |
16 | #include "mlir/Support/LLVM.h" |
17 | #include "llvm/ADT/APInt.h" |
18 | |
19 | namespace mlir { |
20 | |
21 | /// Returns the result of MLIR's ceildiv operation on constants. The RHS is |
22 | /// expected to be non-zero. |
23 | inline int64_t ceilDiv(int64_t lhs, int64_t rhs) { |
24 | assert(rhs != 0); |
25 | // C/C++'s integer division rounds towards 0. |
26 | int64_t x = (rhs > 0) ? -1 : 1; |
27 | return ((lhs != 0) && (lhs > 0) == (rhs > 0)) ? ((lhs + x) / rhs) + 1 |
28 | : -(-lhs / rhs); |
29 | } |
30 | |
31 | /// Returns the result of MLIR's floordiv operation on constants. The RHS is |
32 | /// expected to be non-zero. |
33 | inline int64_t floorDiv(int64_t lhs, int64_t rhs) { |
34 | assert(rhs != 0); |
35 | // C/C++'s integer division rounds towards 0. |
36 | int64_t x = (rhs < 0) ? 1 : -1; |
37 | return ((lhs != 0) && ((lhs < 0) != (rhs < 0))) ? -((-lhs + x) / rhs) - 1 |
38 | : lhs / rhs; |
39 | } |
40 | |
41 | /// Returns MLIR's mod operation on constants. MLIR's mod operation yields the |
42 | /// remainder of the Euclidean division of 'lhs' by 'rhs', and is therefore not |
43 | /// C's % operator. The RHS is always expected to be positive, and the result |
44 | /// is always non-negative. |
45 | inline int64_t mod(int64_t lhs, int64_t rhs) { |
46 | assert(rhs >= 1); |
47 | return lhs % rhs < 0 ? lhs % rhs + rhs : lhs % rhs; |
48 | } |
49 | } // namespace mlir |
50 | |
51 | #endif // MLIR_SUPPORT_MATHEXTRAS_H_ |
52 | |