MLIR 24.0.0git
CreateAsyncGroups.cpp
Go to the documentation of this file.
1//===- CreateAsyncGroups.cpp - Create async device copies -----------------===//
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
10
17
18using namespace mlir;
19
20/// Return "true" if the given vector transfer op is contiguous and suitable
21/// for replacement with an async copy. An op masked by an enclosing
22/// vector.mask is not: replacing it would drop the mask and leave non-maskable
23/// ops inside the vector.mask region.
24template <typename OpTy>
25static bool isContiguousXferOp(OpTy op) {
26 return !op.isMasked() && op.getPermutationMap().isMinorIdentity() &&
27 op.isDimInBounds(0) && op.hasPureBufferSemantics() &&
28 cast<MemRefType>(nvgpu::getMemrefOperand(op).getType())
29 .isLastDimUnitStride();
30}
31
32/// Return "true" if the given op is a contiguous and suitable
33/// vector.transfer_write or vector.store op.
34static bool isContiguousStore(Operation *write) {
35 if (auto transferWrite = dyn_cast<vector::TransferWriteOp>(write))
36 return isContiguousXferOp(transferWrite) && !transferWrite.getMask();
37 // vector.store are always contiguous.
38 return isa<vector::StoreOp>(write);
39}
40
41/// Return "true" if the given op is a contiguous and suitable
42/// vector.transfer_read or vector.load op.
43static bool isContiguousRead(Operation *read) {
44 if (auto transferRead = dyn_cast<vector::TransferReadOp>(read))
45 return isContiguousXferOp(transferRead);
46 // vector.load are always contiguous.
47 return isa<vector::LoadOp>(read);
48}
49
50namespace {
51/// A vector.create_mask op and extract position.
52struct TransferMask {
53 vector::CreateMaskOp createMaskOp;
54 SmallVector<int64_t> extractPosition;
55};
56} // namespace
57
58/// If the given vector load op has a mask that is defined by
59/// vector.create_mask, return that op.
60static FailureOr<TransferMask> getMaskOp(Operation *loadOp) {
61 auto transferRead = dyn_cast<vector::TransferReadOp>(loadOp);
62 if (!transferRead || !transferRead.getMask())
63 return TransferMask{{}, {}};
64 assert(transferRead.getMask().getType().getRank() == 1 &&
65 "expected 1-D mask");
66
67 // Case 1: Mask is the result of a vector.create_mask.
68 if (auto maskOp =
69 transferRead.getMask().getDefiningOp<vector::CreateMaskOp>())
70 return TransferMask{maskOp, {}};
71
72 // Case 2: Mask is the result of a vector.extract(vector.create_mask) at a
73 // static position.
74 // TODO: Support a dynamic position by carrying it as an SSA value into the
75 // comparisons in `buildNumReadElements`.
76 if (auto extractOp =
77 transferRead.getMask().getDefiningOp<vector::ExtractOp>())
78 if (auto maskOp =
79 extractOp.getSource().getDefiningOp<vector::CreateMaskOp>())
80 if (!extractOp.hasDynamicPosition())
81 return TransferMask{
82 maskOp, SmallVector<int64_t>(extractOp.getStaticPosition())};
83
84 // All other cases: not supported.
85 return failure();
86}
87
88/// Build an SSA value that represents the number of read elements.
90 Operation *readOp) {
91 FailureOr<TransferMask> transferMask = getMaskOp(readOp);
92 assert(succeeded(transferMask) && "invalid transfer mask");
93
94 // No mask => no num_read_elements.
95 if (!transferMask->createMaskOp)
96 return Value();
97
98 // vector.create_mask treats a negative size as 0 and a size larger than the
99 // dimension as the dimension size. The async copy must not read more
100 // elements than it writes, so clamp the size of the "ones" segment in the
101 // same way.
102 auto clampToDimSize = [&](Value size) -> Value {
103 int64_t dimSize =
104 transferMask->createMaskOp.getVectorType().getShape().back();
105 if (std::optional<int64_t> cst = getConstantIntValue(size))
107 b, loc, std::clamp(*cst, int64_t(0), dimSize));
108 Value zero = arith::ConstantIndexOp::create(b, loc, 0);
109 Value dim = arith::ConstantIndexOp::create(b, loc, dimSize);
110 Value nonNegative = arith::MaxSIOp::create(b, loc, size, zero);
111 return arith::MinSIOp::create(b, loc, nonNegative, dim);
112 };
113
114 // No extract: return size of "ones" segment in the mask.
115 if (transferMask->extractPosition.empty()) {
116 assert(transferMask->createMaskOp.getNumOperands() == 1 &&
117 "expected single operand");
118 return clampToDimSize(transferMask->createMaskOp.getOperand(0));
119 }
120
121 // vector.extract(vector.create_mask).
122 // If extract_pos < num_ones, take number of elements from the least
123 // significant dimension. (Do this for all dimensions and bit-AND the
124 // conditions.)
125 assert(transferMask->createMaskOp.getVectorType().getRank() -
126 transferMask->extractPosition.size() ==
127 1 &&
128 "expected N-D -> (N-1)-D extract");
129 Value cond;
130 // Note: There is one more `sz` than `pos`. The loop end with the last `pos`.
131 for (auto [pos, sz] : llvm::zip(transferMask->extractPosition,
132 transferMask->createMaskOp->getOperands())) {
133 Value cmp =
134 arith::CmpIOp::create(b, loc, arith::CmpIPredicate::slt,
135 arith::ConstantIndexOp::create(b, loc, pos), sz);
136 if (!cond) {
137 cond = cmp;
138 continue;
139 }
140 cond = arith::AndIOp::create(b, loc, cmp, cond);
141 }
142 return arith::SelectOp::create(
143 b, loc, cond,
144 clampToDimSize(transferMask->createMaskOp->getOperands().back()),
146}
147
148/// Return "true" if the conversion to async copy is supported by "async copy".
149static bool resultsInSupportedAsyncCopy(MemRefType memrefType,
150 VectorType vecType) {
151 assert(vecType.getRank() == 1 && "expected 1-D vector");
152 constexpr int64_t kSupportedCpAsyncAlignmentsInBytes[3] = {4, 8, 16};
153
154 // The copy size must be known at compile time.
155 if (vecType.isScalable())
156 return false;
157
158 // The copy size is computed from the memref element type, so it must be the
159 // vector element type (this is not the case for a memref of vectors).
160 if (memrefType.getElementType() != vecType.getElementType())
161 return false;
162
163 // Condition 1: the copy size must be supported. It is computed from the bit
164 // width of the element type, so only 8-, 16-, 32-, 64- and 128-bit integers
165 // or floats are supported: sub-byte elements are stored in whole bytes, and
166 // index has no bit width.
167 Type elementType = vecType.getElementType();
168 if (!elementType.isIntOrFloat() ||
169 !llvm::is_contained({8u, 16u, 32u, 64u, 128u},
170 elementType.getIntOrFloatBitWidth()))
171 return false;
172 bool supportedCopySize = false;
173 int64_t numElements = vecType.getNumElements();
174 for (int64_t alignmentInBytes : kSupportedCpAsyncAlignmentsInBytes) {
175 if (alignmentInBytes * 8 ==
176 numElements * elementType.getIntOrFloatBitWidth()) {
177 supportedCopySize = true;
178 break;
179 }
180 }
181 if (!supportedCopySize)
182 return false;
183
184 // TODO: Condition 2: the alignments must be supported. For cp.async the
185 // NVIDIA doc (section 6.4.1) says: "The address must be naturally aligned to
186 // a multiple of the access size. If an address is not properly aligned, the
187 // resulting behavior is undefined.".
188 return true;
189}
190
192 bool bypassL1) {
193 llvm::SmallSetVector<Operation *, 16> copyToSharedMem;
194
195 // Look for all the copy that can be converted to async copy ops.
196 op->walk([&](Operation *writeOp) {
197 // Look for contiguous 1D vector store into shared memory.
198 if (!isContiguousStore(writeOp))
199 return;
200 Value vectorVal = nvgpu::getValueStored(writeOp);
201 if (cast<VectorType>(vectorVal.getType()).getRank() != 1)
202 return;
203 Value storeBase = nvgpu::getMemrefOperand(writeOp);
204 if (!nvgpu::NVGPUDialect::hasSharedMemoryAddressSpace(
205 cast<MemRefType>(storeBase.getType())))
206 return;
207
208 // The stored vector must originate from a contiguous 1D vector load.
209 Operation *readOp = vectorVal.getDefiningOp();
210 if (readOp == nullptr || !isContiguousRead(readOp))
211 return;
212 Value loadBase = nvgpu::getMemrefOperand(readOp);
213 // Should be reading from global memory (not shared memory).
214 if (nvgpu::NVGPUDialect::hasSharedMemoryAddressSpace(
215 cast<MemRefType>(loadBase.getType())))
216 return;
217
218 // Look for compatible mask and padding.
219 if (auto transferRead = dyn_cast<vector::TransferReadOp>(readOp)) {
220 if (Value mask = transferRead.getMask()) {
221 if (getConstantIntValue(transferRead.getPadding()) ==
222 static_cast<int64_t>(0))
223 return;
224 if (failed(getMaskOp(readOp)))
225 return;
226 }
227 }
228
229 // Check whether both accesses are supported before we emit: this is
230 // necessary to ensure the correctness of DeviceAsyncCopyOp.
231 VectorType vecType = cast<VectorType>(vectorVal.getType());
232
233 if (!resultsInSupportedAsyncCopy(cast<MemRefType>(loadBase.getType()),
234 vecType) ||
235 !resultsInSupportedAsyncCopy(cast<MemRefType>(storeBase.getType()),
236 vecType))
237 return;
238
239 copyToSharedMem.insert(writeOp);
240 return;
241 });
242
243 while (!copyToSharedMem.empty()) {
244 // Start a group with the first write.
246 Operation *writeOp = *copyToSharedMem.begin();
247 copyToSharedMem.remove(writeOp);
248 group.push_back(writeOp);
249 Operation *nextNode = writeOp;
250
251 // Look in the next nodes for more copies to add to the same group.
252 while ((nextNode = nextNode->getNextNode())) {
253 // Ignore ops without side effects.
254 auto memInterface = dyn_cast<MemoryEffectOpInterface>(nextNode);
255 if (memInterface && memInterface.hasNoEffect() &&
257 continue;
258 // Ignore read from a different address space.
259 if (isa<vector::TransferReadOp, vector::LoadOp>(nextNode)) {
260 Operation *readOp = nextNode;
261 Value memrefOperand = nvgpu::getMemrefOperand(readOp);
262 if (!nvgpu::NVGPUDialect::hasSharedMemoryAddressSpace(
263 cast<MemRefType>(memrefOperand.getType()))) {
264 continue;
265 }
266 }
267 if (copyToSharedMem.count(nextNode)) {
268 // Found another copy, add it to the group.
269 copyToSharedMem.remove(nextNode);
270 group.push_back(nextNode);
271 continue;
272 }
273 // If the op is something else stop the accumulating op in the group.
274 break;
275 }
276
277 // Emit the group.
278 SmallVector<Value> tokens;
279 for (Operation *writeOp : group) {
280 rewriter.setInsertionPoint(writeOp);
281 Value vectorVal = nvgpu::getValueStored(writeOp);
282 auto vectorType = cast<VectorType>(vectorVal.getType());
283 int64_t numElements = vectorType.getNumElements();
284 Operation *readOp = vectorVal.getDefiningOp();
285 Value storeBase = nvgpu::getMemrefOperand(writeOp);
286 Value loadBase = nvgpu::getMemrefOperand(readOp);
287 Value numReadElements =
288 buildNumReadElements(rewriter, writeOp->getLoc(), readOp);
289 auto dstMemref = cast<MemRefType>(storeBase.getType());
290 int64_t sizeInBytes =
291 (dstMemref.getElementTypeBitWidth() * numElements) / 8;
292 // bypass_l1 only possible with 16 byte transfer.
293 Value token = nvgpu::DeviceAsyncCopyOp::create(
294 rewriter, writeOp->getLoc(),
295 nvgpu::DeviceAsyncTokenType::get(op->getContext()),
296 /*dst=*/storeBase, /*dstIndices=*/nvgpu::getIndices(writeOp),
297 /*src=*/loadBase,
298 /*srcIndices=*/nvgpu::getIndices(readOp),
299 /*dstElements=*/rewriter.getIndexAttr(numElements),
300 /*srcElements=*/numReadElements,
301 /*bypassL1=*/bypassL1 && sizeInBytes == 16 ? rewriter.getUnitAttr()
302 : UnitAttr());
303 tokens.push_back(token);
304 }
305
306 // Create the group and wait for it right after.
307 Value groupToken = nvgpu::DeviceAsyncCreateGroupOp::create(
308 rewriter, op->getLoc(),
309 nvgpu::DeviceAsyncTokenType::get(op->getContext()), tokens);
310 nvgpu::DeviceAsyncWaitOp::create(rewriter, op->getLoc(), groupToken,
311 nullptr);
312 // Clean up old stores.
313 for (Operation *writeOp : group)
314 rewriter.eraseOp(writeOp);
315 }
316}
static bool isContiguousStore(Operation *write)
Return "true" if the given op is a contiguous and suitable vector.transfer_write or vector....
static bool isContiguousXferOp(OpTy op)
Return "true" if the given vector transfer op is contiguous and suitable for replacement with an asyn...
static FailureOr< TransferMask > getMaskOp(Operation *loadOp)
If the given vector load op has a mask that is defined by vector.create_mask, return that op.
static bool resultsInSupportedAsyncCopy(MemRefType memrefType, VectorType vecType)
Return "true" if the conversion to async copy is supported by "async copy".
static bool isContiguousRead(Operation *read)
Return "true" if the given op is a contiguous and suitable vector.transfer_read or vector....
static Value buildNumReadElements(OpBuilder &b, Location loc, Operation *readOp)
Build an SSA value that represents the number of read elements.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
UnitAttr getUnitAttr()
Definition Builders.cpp:106
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
This class helps build Operations.
Definition Builders.h:210
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
This trait indicates that the memory effects of an operation includes the effects of operations neste...
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
void remove()
Remove the operation from its parent block, but don't delete it.
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:851
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:233
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Definition ArithOps.cpp:453
Value getMemrefOperand(Operation *op)
Get the memref that is loaded from/stored into by the given load/store operation.
Definition Utils.cpp:68
Value getValueStored(Operation *op)
Get the value that is stored by the given store operation.
Definition Utils.cpp:58
Operation::operand_range getIndices(Operation *op)
Get the indices that the given load/store operation is operating on.
Definition Utils.cpp:18
void createAsyncGroups(RewriterBase &rewriter, Operation *op, bool bypassL1)
Convert global->shared vector transfers to async device copies.
Include the generated interface declarations.
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311