1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
|
//===- IndexOps.cpp - Index operation definitions --------------------------==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/Index/IR/IndexOps.h"
#include "mlir/Dialect/Index/IR/IndexAttrs.h"
#include "mlir/Dialect/Index/IR/IndexDialect.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/OpImplementation.h"
#include "llvm/ADT/SmallString.h"
#include <optional>
using namespace mlir;
using namespace mlir::index;
//===----------------------------------------------------------------------===//
// IndexDialect
//===----------------------------------------------------------------------===//
void IndexDialect::registerOperations() {
addOperations<
#define GET_OP_LIST
#include "mlir/Dialect/Index/IR/IndexOps.cpp.inc"
>();
}
Operation *IndexDialect::materializeConstant(OpBuilder &b, Attribute value,
Type type, Location loc) {
// Materialize bool constants as `i1`.
if (auto boolValue = dyn_cast<BoolAttr>(value)) {
if (!type.isSignlessInteger(1))
return nullptr;
return b.create<BoolConstantOp>(loc, type, boolValue);
}
// Materialize integer attributes as `index`.
if (auto indexValue = dyn_cast<IntegerAttr>(value)) {
if (!llvm::isa<IndexType>(indexValue.getType()) ||
!llvm::isa<IndexType>(type))
return nullptr;
assert(indexValue.getValue().getBitWidth() ==
IndexType::kInternalStorageBitWidth);
return b.create<ConstantOp>(loc, indexValue);
}
return nullptr;
}
//===----------------------------------------------------------------------===//
// Fold Utilities
//===----------------------------------------------------------------------===//
/// Fold an index operation irrespective of the target bitwidth. The
/// operation must satisfy the property:
///
/// ```
/// trunc(f(a, b)) = f(trunc(a), trunc(b))
/// ```
///
/// For all values of `a` and `b`. The function accepts a lambda that computes
/// the integer result, which in turn must satisfy the above property.
static OpFoldResult foldBinaryOpUnchecked(
ArrayRef<Attribute> operands,
function_ref<std::optional<APInt>(const APInt &, const APInt &)>
calculate) {
assert(operands.size() == 2 && "binary operation expected 2 operands");
auto lhs = dyn_cast_if_present<IntegerAttr>(operands[0]);
auto rhs = dyn_cast_if_present<IntegerAttr>(operands[1]);
if (!lhs || !rhs)
return {};
std::optional<APInt> result = calculate(lhs.getValue(), rhs.getValue());
if (!result)
return {};
assert(result->trunc(32) ==
calculate(lhs.getValue().trunc(32), rhs.getValue().trunc(32)));
return IntegerAttr::get(IndexType::get(lhs.getContext()), *result);
}
/// Fold an index operation only if the truncated 64-bit result matches the
/// 32-bit result for operations that don't satisfy the above property. These
/// are operations where the upper bits of the operands can affect the lower
/// bits of the results.
///
/// The function accepts a lambda that computes the integer result in both
/// 64-bit and 32-bit. If either call returns `std::nullopt`, the operation is
/// not folded.
static OpFoldResult foldBinaryOpChecked(
ArrayRef<Attribute> operands,
function_ref<std::optional<APInt>(const APInt &, const APInt &lhs)>
calculate) {
assert(operands.size() == 2 && "binary operation expected 2 operands");
auto lhs = dyn_cast_if_present<IntegerAttr>(operands[0]);
auto rhs = dyn_cast_if_present<IntegerAttr>(operands[1]);
// Only fold index operands.
if (!lhs || !rhs)
return {};
// Compute the 64-bit result and the 32-bit result.
std::optional<APInt> result64 = calculate(lhs.getValue(), rhs.getValue());
if (!result64)
return {};
std::optional<APInt> result32 =
calculate(lhs.getValue().trunc(32), rhs.getValue().trunc(32));
if (!result32)
return {};
// Compare the truncated 64-bit result to the 32-bit result.
if (result64->trunc(32) != *result32)
return {};
// The operation can be folded for these particular operands.
return IntegerAttr::get(IndexType::get(lhs.getContext()), *result64);
}
//===----------------------------------------------------------------------===//
// AddOp
//===----------------------------------------------------------------------===//
OpFoldResult AddOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpUnchecked(
adaptor.getOperands(),
[](const APInt &lhs, const APInt &rhs) { return lhs + rhs; });
}
//===----------------------------------------------------------------------===//
// SubOp
//===----------------------------------------------------------------------===//
OpFoldResult SubOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpUnchecked(
adaptor.getOperands(),
[](const APInt &lhs, const APInt &rhs) { return lhs - rhs; });
}
//===----------------------------------------------------------------------===//
// MulOp
//===----------------------------------------------------------------------===//
OpFoldResult MulOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpUnchecked(
adaptor.getOperands(),
[](const APInt &lhs, const APInt &rhs) { return lhs * rhs; });
}
//===----------------------------------------------------------------------===//
// DivSOp
//===----------------------------------------------------------------------===//
OpFoldResult DivSOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpChecked(
adaptor.getOperands(),
[](const APInt &lhs, const APInt &rhs) -> std::optional<APInt> {
// Don't fold division by zero.
if (rhs.isZero())
return std::nullopt;
return lhs.sdiv(rhs);
});
}
//===----------------------------------------------------------------------===//
// DivUOp
//===----------------------------------------------------------------------===//
OpFoldResult DivUOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpChecked(
adaptor.getOperands(),
[](const APInt &lhs, const APInt &rhs) -> std::optional<APInt> {
// Don't fold division by zero.
if (rhs.isZero())
return std::nullopt;
return lhs.udiv(rhs);
});
}
//===----------------------------------------------------------------------===//
// CeilDivSOp
//===----------------------------------------------------------------------===//
/// Compute `ceildivs(n, m)` as `x = m > 0 ? -1 : 1` and then
/// `n*m > 0 ? (n+x)/m + 1 : -(-n/m)`.
static std::optional<APInt> calculateCeilDivS(const APInt &n, const APInt &m) {
// Don't fold division by zero.
if (m.isZero())
return std::nullopt;
// Short-circuit the zero case.
if (n.isZero())
return n;
bool mGtZ = m.sgt(0);
if (n.sgt(0) != mGtZ) {
// If the operands have different signs, compute the negative result. Signed
// division overflow is not possible, since if `m == -1`, `n` can be at most
// `INT_MAX`, and `-INT_MAX != INT_MIN` in two's complement.
return -(-n).sdiv(m);
}
// Otherwise, compute the positive result. Signed division overflow is not
// possible since if `m == -1`, `x` will be `1`.
int64_t x = mGtZ ? -1 : 1;
return (n + x).sdiv(m) + 1;
}
OpFoldResult CeilDivSOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpChecked(adaptor.getOperands(), calculateCeilDivS);
}
//===----------------------------------------------------------------------===//
// CeilDivUOp
//===----------------------------------------------------------------------===//
OpFoldResult CeilDivUOp::fold(FoldAdaptor adaptor) {
// Compute `ceildivu(n, m)` as `n == 0 ? 0 : (n-1)/m + 1`.
return foldBinaryOpChecked(
adaptor.getOperands(),
[](const APInt &n, const APInt &m) -> std::optional<APInt> {
// Don't fold division by zero.
if (m.isZero())
return std::nullopt;
// Short-circuit the zero case.
if (n.isZero())
return n;
return (n - 1).udiv(m) + 1;
});
}
//===----------------------------------------------------------------------===//
// FloorDivSOp
//===----------------------------------------------------------------------===//
/// Compute `floordivs(n, m)` as `x = m < 0 ? 1 : -1` and then
/// `n*m < 0 ? -1 - (x-n)/m : n/m`.
static std::optional<APInt> calculateFloorDivS(const APInt &n, const APInt &m) {
// Don't fold division by zero.
if (m.isZero())
return std::nullopt;
// Short-circuit the zero case.
if (n.isZero())
return n;
bool mLtZ = m.slt(0);
if (n.slt(0) == mLtZ) {
// If the operands have the same sign, compute the positive result.
return n.sdiv(m);
}
// If the operands have different signs, compute the negative result. Signed
// division overflow is not possible since if `m == -1`, `x` will be 1 and
// `n` can be at most `INT_MAX`.
int64_t x = mLtZ ? 1 : -1;
return -1 - (x - n).sdiv(m);
}
OpFoldResult FloorDivSOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpChecked(adaptor.getOperands(), calculateFloorDivS);
}
//===----------------------------------------------------------------------===//
// RemSOp
//===----------------------------------------------------------------------===//
OpFoldResult RemSOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpChecked(
adaptor.getOperands(),
[](const APInt &lhs, const APInt &rhs) { return lhs.srem(rhs); });
}
//===----------------------------------------------------------------------===//
// RemUOp
//===----------------------------------------------------------------------===//
OpFoldResult RemUOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpChecked(
adaptor.getOperands(),
[](const APInt &lhs, const APInt &rhs) { return lhs.urem(rhs); });
}
//===----------------------------------------------------------------------===//
// MaxSOp
//===----------------------------------------------------------------------===//
OpFoldResult MaxSOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpChecked(adaptor.getOperands(),
[](const APInt &lhs, const APInt &rhs) {
return lhs.sgt(rhs) ? lhs : rhs;
});
}
//===----------------------------------------------------------------------===//
// MaxUOp
//===----------------------------------------------------------------------===//
OpFoldResult MaxUOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpChecked(adaptor.getOperands(),
[](const APInt &lhs, const APInt &rhs) {
return lhs.ugt(rhs) ? lhs : rhs;
});
}
//===----------------------------------------------------------------------===//
// MinSOp
//===----------------------------------------------------------------------===//
OpFoldResult MinSOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpChecked(adaptor.getOperands(), [](const APInt &lhs, const APInt &rhs) {
return lhs.slt(rhs) ? lhs : rhs;
});
}
//===----------------------------------------------------------------------===//
// MinUOp
//===----------------------------------------------------------------------===//
OpFoldResult MinUOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpChecked(adaptor.getOperands(), [](const APInt &lhs, const APInt &rhs) {
return lhs.ult(rhs) ? lhs : rhs;
});
}
//===----------------------------------------------------------------------===//
// ShlOp
//===----------------------------------------------------------------------===//
OpFoldResult ShlOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpUnchecked(
adaptor.getOperands(),
[](const APInt &lhs, const APInt &rhs) -> std::optional<APInt> {
// We cannot fold if the RHS is greater than or equal to 32 because
// this would be UB in 32-bit systems but not on 64-bit systems. RHS is
// already treated as unsigned.
if (rhs.uge(32))
return {};
return lhs << rhs;
});
}
//===----------------------------------------------------------------------===//
// ShrSOp
//===----------------------------------------------------------------------===//
OpFoldResult ShrSOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpChecked(
adaptor.getOperands(),
[](const APInt &lhs, const APInt &rhs) -> std::optional<APInt> {
// Don't fold if RHS is greater than or equal to 32.
if (rhs.uge(32))
return {};
return lhs.ashr(rhs);
});
}
//===----------------------------------------------------------------------===//
// ShrUOp
//===----------------------------------------------------------------------===//
OpFoldResult ShrUOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpChecked(
adaptor.getOperands(),
[](const APInt &lhs, const APInt &rhs) -> std::optional<APInt> {
// Don't fold if RHS is greater than or equal to 32.
if (rhs.uge(32))
return {};
return lhs.lshr(rhs);
});
}
//===----------------------------------------------------------------------===//
// AndOp
//===----------------------------------------------------------------------===//
OpFoldResult AndOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpUnchecked(
adaptor.getOperands(),
[](const APInt &lhs, const APInt &rhs) { return lhs & rhs; });
}
//===----------------------------------------------------------------------===//
// OrOp
//===----------------------------------------------------------------------===//
OpFoldResult OrOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpUnchecked(
adaptor.getOperands(),
[](const APInt &lhs, const APInt &rhs) { return lhs | rhs; });
}
//===----------------------------------------------------------------------===//
// XOrOp
//===----------------------------------------------------------------------===//
OpFoldResult XOrOp::fold(FoldAdaptor adaptor) {
return foldBinaryOpUnchecked(
adaptor.getOperands(),
[](const APInt &lhs, const APInt &rhs) { return lhs ^ rhs; });
}
//===----------------------------------------------------------------------===//
// CastSOp
//===----------------------------------------------------------------------===//
bool CastSOp::areCastCompatible(TypeRange lhsTypes, TypeRange rhsTypes) {
return llvm::isa<IndexType>(lhsTypes.front()) !=
llvm::isa<IndexType>(rhsTypes.front());
}
//===----------------------------------------------------------------------===//
// CastUOp
//===----------------------------------------------------------------------===//
bool CastUOp::areCastCompatible(TypeRange lhsTypes, TypeRange rhsTypes) {
return llvm::isa<IndexType>(lhsTypes.front()) !=
llvm::isa<IndexType>(rhsTypes.front());
}
//===----------------------------------------------------------------------===//
// CmpOp
//===----------------------------------------------------------------------===//
/// Compare two integers according to the comparison predicate.
bool compareIndices(const APInt &lhs, const APInt &rhs,
IndexCmpPredicate pred) {
switch (pred) {
case IndexCmpPredicate::EQ:
return lhs.eq(rhs);
case IndexCmpPredicate::NE:
return lhs.ne(rhs);
case IndexCmpPredicate::SGE:
return lhs.sge(rhs);
case IndexCmpPredicate::SGT:
return lhs.sgt(rhs);
case IndexCmpPredicate::SLE:
return lhs.sle(rhs);
case IndexCmpPredicate::SLT:
return lhs.slt(rhs);
case IndexCmpPredicate::UGE:
return lhs.uge(rhs);
case IndexCmpPredicate::UGT:
return lhs.ugt(rhs);
case IndexCmpPredicate::ULE:
return lhs.ule(rhs);
case IndexCmpPredicate::ULT:
return lhs.ult(rhs);
}
llvm_unreachable("unhandled IndexCmpPredicate predicate");
}
OpFoldResult CmpOp::fold(FoldAdaptor adaptor) {
auto lhs = dyn_cast_if_present<IntegerAttr>(adaptor.getLhs());
auto rhs = dyn_cast_if_present<IntegerAttr>(adaptor.getRhs());
if (!lhs || !rhs)
return {};
// Perform the comparison in 64-bit and 32-bit.
bool result64 = compareIndices(lhs.getValue(), rhs.getValue(), getPred());
bool result32 = compareIndices(lhs.getValue().trunc(32),
rhs.getValue().trunc(32), getPred());
if (result64 != result32)
return {};
return BoolAttr::get(getContext(), result64);
}
//===----------------------------------------------------------------------===//
// ConstantOp
//===----------------------------------------------------------------------===//
void ConstantOp::getAsmResultNames(
function_ref<void(Value, StringRef)> setNameFn) {
SmallString<32> specialNameBuffer;
llvm::raw_svector_ostream specialName(specialNameBuffer);
specialName << "idx" << getValueAttr().getValue();
setNameFn(getResult(), specialName.str());
}
OpFoldResult ConstantOp::fold(FoldAdaptor adaptor) { return getValueAttr(); }
void ConstantOp::build(OpBuilder &b, OperationState &state, int64_t value) {
build(b, state, b.getIndexType(), b.getIndexAttr(value));
}
//===----------------------------------------------------------------------===//
// BoolConstantOp
//===----------------------------------------------------------------------===//
OpFoldResult BoolConstantOp::fold(FoldAdaptor adaptor) {
return getValueAttr();
}
void BoolConstantOp::getAsmResultNames(
function_ref<void(Value, StringRef)> setNameFn) {
setNameFn(getResult(), getValue() ? "true" : "false");
}
//===----------------------------------------------------------------------===//
// ODS-Generated Definitions
//===----------------------------------------------------------------------===//
#define GET_OP_CLASSES
#include "mlir/Dialect/Index/IR/IndexOps.cpp.inc"
|