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
|
//===----------- MultiBuffering.cpp ---------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements multi buffering transformation.
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Arith/Utils/Utils.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/MemRef/Transforms/Passes.h"
#include "mlir/Dialect/MemRef/Transforms/Transforms.h"
#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/Dominance.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/ValueRange.h"
#include "mlir/Interfaces/LoopLikeInterface.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Debug.h"
using namespace mlir;
#define DEBUG_TYPE "memref-transforms"
#define DBGS() (llvm::dbgs() << "[" DEBUG_TYPE "]: ")
#define DBGSNL() (llvm::dbgs() << "\n")
/// Return true if the op fully overwrite the given `buffer` value.
static bool overrideBuffer(Operation *op, Value buffer) {
auto copyOp = dyn_cast<memref::CopyOp>(op);
if (!copyOp)
return false;
return copyOp.getTarget() == buffer;
}
/// Replace the uses of `oldOp` with the given `val` and for subview uses
/// propagate the type change. Changing the memref type may require propagating
/// it through subview ops so we cannot just do a replaceAllUse but need to
/// propagate the type change and erase old subview ops.
static void replaceUsesAndPropagateType(RewriterBase &rewriter,
Operation *oldOp, Value val) {
SmallVector<Operation *> opsToDelete;
SmallVector<OpOperand *> operandsToReplace;
// Save the operand to replace / delete later (avoid iterator invalidation).
// TODO: can we use an early_inc iterator?
for (OpOperand &use : oldOp->getUses()) {
// Non-subview ops will be replaced by `val`.
auto subviewUse = dyn_cast<memref::SubViewOp>(use.getOwner());
if (!subviewUse) {
operandsToReplace.push_back(&use);
continue;
}
// `subview(old_op)` is replaced by a new `subview(val)`.
OpBuilder::InsertionGuard g(rewriter);
rewriter.setInsertionPoint(subviewUse);
Type newType = memref::SubViewOp::inferRankReducedResultType(
subviewUse.getType().getShape(), cast<MemRefType>(val.getType()),
subviewUse.getStaticOffsets(), subviewUse.getStaticSizes(),
subviewUse.getStaticStrides());
Value newSubview = rewriter.create<memref::SubViewOp>(
subviewUse->getLoc(), cast<MemRefType>(newType), val,
subviewUse.getMixedOffsets(), subviewUse.getMixedSizes(),
subviewUse.getMixedStrides());
// Ouch recursion ... is this really necessary?
replaceUsesAndPropagateType(rewriter, subviewUse, newSubview);
opsToDelete.push_back(use.getOwner());
}
// Perform late replacement.
// TODO: can we use an early_inc iterator?
for (OpOperand *operand : operandsToReplace) {
Operation *op = operand->getOwner();
rewriter.startRootUpdate(op);
operand->set(val);
rewriter.finalizeRootUpdate(op);
}
// Perform late op erasure.
// TODO: can we use an early_inc iterator?
for (Operation *op : opsToDelete)
rewriter.eraseOp(op);
}
// Transformation to do multi-buffering/array expansion to remove dependencies
// on the temporary allocation between consecutive loop iterations.
// Returns success if the transformation happened and failure otherwise.
// This is not a pattern as it requires propagating the new memref type to its
// uses and requires updating subview ops.
FailureOr<memref::AllocOp>
mlir::memref::multiBuffer(RewriterBase &rewriter, memref::AllocOp allocOp,
unsigned multiBufferingFactor,
bool skipOverrideAnalysis) {
LLVM_DEBUG(DBGS() << "Start multibuffering: " << allocOp << "\n");
DominanceInfo dom(allocOp->getParentOp());
LoopLikeOpInterface candidateLoop;
for (Operation *user : allocOp->getUsers()) {
auto parentLoop = user->getParentOfType<LoopLikeOpInterface>();
if (!parentLoop) {
if (isa<memref::DeallocOp>(user)) {
// Allow dealloc outside of any loop.
// TODO: The whole precondition function here is very brittle and will
// need to rethought an isolated into a cleaner analysis.
continue;
}
LLVM_DEBUG(DBGS() << "--no parent loop -> fail\n");
LLVM_DEBUG(DBGS() << "----due to user: " << *user << "\n");
return failure();
}
if (!skipOverrideAnalysis) {
/// Make sure there is no loop-carried dependency on the allocation.
if (!overrideBuffer(user, allocOp.getResult())) {
LLVM_DEBUG(DBGS() << "--Skip user: found loop-carried dependence\n");
continue;
}
// If this user doesn't dominate all the other users keep looking.
if (llvm::any_of(allocOp->getUsers(), [&](Operation *otherUser) {
return !dom.dominates(user, otherUser);
})) {
LLVM_DEBUG(
DBGS() << "--Skip user: does not dominate all other users\n");
continue;
}
} else {
if (llvm::any_of(allocOp->getUsers(), [&](Operation *otherUser) {
return !isa<memref::DeallocOp>(otherUser) &&
!parentLoop->isProperAncestor(otherUser);
})) {
LLVM_DEBUG(
DBGS()
<< "--Skip user: not all other users are in the parent loop\n");
continue;
}
}
candidateLoop = parentLoop;
break;
}
if (!candidateLoop) {
LLVM_DEBUG(DBGS() << "Skip alloc: no candidate loop\n");
return failure();
}
std::optional<Value> inductionVar = candidateLoop.getSingleInductionVar();
std::optional<OpFoldResult> lowerBound = candidateLoop.getSingleLowerBound();
std::optional<OpFoldResult> singleStep = candidateLoop.getSingleStep();
if (!inductionVar || !lowerBound || !singleStep) {
LLVM_DEBUG(DBGS() << "Skip alloc: no single iv, lb or step\n");
return failure();
}
if (!dom.dominates(allocOp.getOperation(), candidateLoop)) {
LLVM_DEBUG(DBGS() << "Skip alloc: does not dominate candidate loop\n");
return failure();
}
LLVM_DEBUG(DBGS() << "Start multibuffering loop: " << candidateLoop << "\n");
// 1. Construct the multi-buffered memref type.
ArrayRef<int64_t> originalShape = allocOp.getType().getShape();
SmallVector<int64_t, 4> multiBufferedShape{multiBufferingFactor};
llvm::append_range(multiBufferedShape, originalShape);
LLVM_DEBUG(DBGS() << "--original type: " << allocOp.getType() << "\n");
MemRefType mbMemRefType = MemRefType::Builder(allocOp.getType())
.setShape(multiBufferedShape)
.setLayout(MemRefLayoutAttrInterface());
LLVM_DEBUG(DBGS() << "--multi-buffered type: " << mbMemRefType << "\n");
// 2. Create the multi-buffered alloc.
Location loc = allocOp->getLoc();
OpBuilder::InsertionGuard g(rewriter);
rewriter.setInsertionPoint(allocOp);
auto mbAlloc = rewriter.create<memref::AllocOp>(
loc, mbMemRefType, ValueRange{}, allocOp->getAttrs());
LLVM_DEBUG(DBGS() << "--multi-buffered alloc: " << mbAlloc << "\n");
// 3. Within the loop, build the modular leading index (i.e. each loop
// iteration %iv accesses slice ((%iv - %lb) / %step) % %mb_factor).
rewriter.setInsertionPointToStart(&candidateLoop.getLoopBody().front());
Value ivVal = *inductionVar;
Value lbVal = getValueOrCreateConstantIndexOp(rewriter, loc, *lowerBound);
Value stepVal = getValueOrCreateConstantIndexOp(rewriter, loc, *singleStep);
AffineExpr iv, lb, step;
bindDims(rewriter.getContext(), iv, lb, step);
Value bufferIndex = affine::makeComposedAffineApply(
rewriter, loc, ((iv - lb).floorDiv(step)) % multiBufferingFactor,
{ivVal, lbVal, stepVal});
LLVM_DEBUG(DBGS() << "--multi-buffered indexing: " << bufferIndex << "\n");
// 4. Build the subview accessing the particular slice, taking modular
// rotation into account.
int64_t mbMemRefTypeRank = mbMemRefType.getRank();
IntegerAttr zero = rewriter.getIndexAttr(0);
IntegerAttr one = rewriter.getIndexAttr(1);
SmallVector<OpFoldResult> offsets(mbMemRefTypeRank, zero);
SmallVector<OpFoldResult> sizes(mbMemRefTypeRank, one);
SmallVector<OpFoldResult> strides(mbMemRefTypeRank, one);
// Offset is [bufferIndex, 0 ... 0 ].
offsets.front() = bufferIndex;
// Sizes is [1, original_size_0 ... original_size_n ].
for (int64_t i = 0, e = originalShape.size(); i != e; ++i)
sizes[1 + i] = rewriter.getIndexAttr(originalShape[i]);
// Strides is [1, 1 ... 1 ].
auto dstMemref =
cast<MemRefType>(memref::SubViewOp::inferRankReducedResultType(
originalShape, mbMemRefType, offsets, sizes, strides));
Value subview = rewriter.create<memref::SubViewOp>(loc, dstMemref, mbAlloc,
offsets, sizes, strides);
LLVM_DEBUG(DBGS() << "--multi-buffered slice: " << subview << "\n");
// 5. Due to the recursive nature of replaceUsesAndPropagateType , we need to
// handle dealloc uses separately..
for (OpOperand &use : llvm::make_early_inc_range(allocOp->getUses())) {
auto deallocOp = dyn_cast<memref::DeallocOp>(use.getOwner());
if (!deallocOp)
continue;
OpBuilder::InsertionGuard g(rewriter);
rewriter.setInsertionPoint(deallocOp);
auto newDeallocOp =
rewriter.create<memref::DeallocOp>(deallocOp->getLoc(), mbAlloc);
(void)newDeallocOp;
LLVM_DEBUG(DBGS() << "----Created dealloc: " << newDeallocOp << "\n");
rewriter.eraseOp(deallocOp);
}
// 6. RAUW with the particular slice, taking modular rotation into account.
replaceUsesAndPropagateType(rewriter, allocOp, subview);
// 7. Finally, erase the old allocOp.
rewriter.eraseOp(allocOp);
return mbAlloc;
}
FailureOr<memref::AllocOp>
mlir::memref::multiBuffer(memref::AllocOp allocOp,
unsigned multiBufferingFactor,
bool skipOverrideAnalysis) {
IRRewriter rewriter(allocOp->getContext());
return multiBuffer(rewriter, allocOp, multiBufferingFactor,
skipOverrideAnalysis);
}
|