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
|
//===- CreateAsyncGroups.cpp - Create async device copies -----------------===//
//
// 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/NVGPU/Transforms/Transforms.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/GPU/IR/GPUDialect.h"
#include "mlir/Dialect/NVGPU/IR/NVGPUDialect.h"
#include "mlir/Dialect/NVGPU/Transforms/Utils.h"
#include "mlir/Dialect/Vector/IR/VectorOps.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/IR/BuiltinTypes.h"
using namespace mlir;
/// Return "true" if the given vector transfer op is contiguous and suitable
/// for replacement with an async copy.
template <typename OpTy>
static bool isContiguousXferOp(OpTy op) {
return op.getPermutationMap().isMinorIdentity() && op.isDimInBounds(0) &&
op.hasPureBufferSemantics() &&
isLastMemrefDimUnitStride(
cast<MemRefType>(nvgpu::getMemrefOperand(op).getType()));
}
/// Return "true" if the given op is a contiguous and suitable
/// vector.transfer_write or vector.store op.
static bool isContiguousStore(Operation *write) {
if (auto transferWrite = dyn_cast<vector::TransferWriteOp>(write))
return isContiguousXferOp(transferWrite) && !transferWrite.getMask();
// vector.store are always contiguous.
return isa<vector::StoreOp>(write);
}
/// Return "true" if the given op is a contiguous and suitable
/// vector.transfer_read or vector.load op.
static bool isContiguousRead(Operation *read) {
if (auto transferRead = dyn_cast<vector::TransferReadOp>(read))
return isContiguousXferOp(transferRead);
// vector.load are always contiguous.
return isa<vector::LoadOp>(read);
}
namespace {
/// A vector.create_mask op and extract position.
struct TransferMask {
vector::CreateMaskOp createMaskOp;
SmallVector<int64_t> extractPosition;
};
} // namespace
/// If the given vector load op has a mask that is defined by
/// vector.create_mask, return that op.
static FailureOr<TransferMask> getMaskOp(Operation *loadOp) {
auto transferRead = dyn_cast<vector::TransferReadOp>(loadOp);
if (!transferRead || !transferRead.getMask())
return TransferMask{{}, {}};
assert(transferRead.getMask().getType().getRank() == 1 &&
"expected 1-D mask");
// Case 1: Mask is the result of a vector.create_mask.
if (auto maskOp =
transferRead.getMask().getDefiningOp<vector::CreateMaskOp>())
return TransferMask{maskOp, {}};
// Case 2: Mask is the result of a vector.extract(vector.create_mask).
if (auto extractOp =
transferRead.getMask().getDefiningOp<vector::ExtractOp>())
if (auto maskOp =
extractOp.getVector().getDefiningOp<vector::CreateMaskOp>())
return TransferMask{maskOp,
SmallVector<int64_t>(extractOp.getStaticPosition())};
// All other cases: not supported.
return failure();
}
/// Build an SSA value that represents the number of read elements.
static Value buildNumReadElements(OpBuilder &b, Location loc,
Operation *readOp) {
FailureOr<TransferMask> transferMask = getMaskOp(readOp);
assert(succeeded(transferMask) && "invalid transfer mask");
// No mask => no num_read_elements.
if (!transferMask->createMaskOp)
return Value();
// No extract: return size of "ones" segment in the mask.
if (transferMask->extractPosition.empty()) {
assert(transferMask->createMaskOp.getNumOperands() == 1 &&
"expected single operand");
return transferMask->createMaskOp.getOperand(0);
}
// vector.extract(vector.create_mask).
// If extract_pos < num_ones, take number of elements from the least
// significant dimension. (Do this for all dimensions and bit-AND the
// conditions.)
assert(transferMask->createMaskOp.getVectorType().getRank() -
transferMask->extractPosition.size() ==
1 &&
"expected N-D -> (N-1)-D extract");
Value cond;
// Note: There is one more `sz` than `pos`. The loop end with the last `pos`.
for (auto [pos, sz] : llvm::zip(transferMask->extractPosition,
transferMask->createMaskOp->getOperands())) {
Value cmp =
b.create<arith::CmpIOp>(loc, arith::CmpIPredicate::slt,
b.create<arith::ConstantIndexOp>(loc, pos), sz);
if (!cond) {
cond = cmp;
continue;
}
cond = b.create<arith::AndIOp>(loc, cmp, cond);
}
return b.create<arith::SelectOp>(
loc, cond, transferMask->createMaskOp->getOperands().back(),
b.create<arith::ConstantIndexOp>(loc, 0));
}
/// Return "true" if the conversion to async copy is supported by "async copy".
static bool resultsInSupportedAsyncCopy(MemRefType memrefType,
VectorType vecType) {
assert(vecType.getRank() == 1 && "expected 1-D vector");
constexpr int64_t kSupportedCpAsyncAlignmentsInBytes[3] = {4, 8, 16};
// Condition 1: the copy size must be supported.
bool supportedCopySize = false;
int64_t numElements = vecType.getNumElements();
Type elementType = vecType.getElementType();
for (int64_t alignmentInBytes : kSupportedCpAsyncAlignmentsInBytes) {
if (alignmentInBytes * 8 ==
numElements * elementType.getIntOrFloatBitWidth()) {
supportedCopySize = true;
break;
}
}
if (!supportedCopySize)
return false;
// TODO: Condition 2: the alignments must be supported. For cp.async the
// NVIDIA doc (section 6.4.1) says: "The address must be naturally aligned to
// a multiple of the access size. If an address is not properly aligned, the
// resulting behavior is undefined.".
return true;
}
void nvgpu::createAsyncGroups(RewriterBase &rewriter, Operation *op,
bool bypassL1) {
llvm::SmallSetVector<Operation *, 16> copyToSharedMem;
// Look for all the copy that can be converted to async copy ops.
op->walk([&](Operation *writeOp) {
// Look for contiguous 1D vector store into shared memory.
if (!isContiguousStore(writeOp))
return;
Value vectorVal = nvgpu::getValueStored(writeOp);
if (cast<VectorType>(vectorVal.getType()).getRank() != 1)
return;
Value storeBase = nvgpu::getMemrefOperand(writeOp);
if (!nvgpu::NVGPUDialect::hasSharedMemoryAddressSpace(
cast<MemRefType>(storeBase.getType())))
return;
// The stored vector must originate from a contiguous 1D vector load.
Operation *readOp = vectorVal.getDefiningOp();
if (readOp == nullptr || !isContiguousRead(readOp))
return;
Value loadBase = nvgpu::getMemrefOperand(readOp);
// Should be reading from global memory (not shared memory).
if (nvgpu::NVGPUDialect::hasSharedMemoryAddressSpace(
cast<MemRefType>(loadBase.getType())))
return;
// Look for compatible mask and padding.
if (auto transferRead = dyn_cast<vector::TransferReadOp>(readOp)) {
if (Value mask = transferRead.getMask()) {
if (getConstantIntValue(transferRead.getPadding()) ==
static_cast<int64_t>(0))
return;
if (failed(getMaskOp(readOp)))
return;
}
}
// Check whether both accesses are supported before we emit: this is
// necessary to ensure the correctness of DeviceAsyncCopyOp.
VectorType vecType = cast<VectorType>(vectorVal.getType());
if (!resultsInSupportedAsyncCopy(cast<MemRefType>(loadBase.getType()),
vecType) ||
!resultsInSupportedAsyncCopy(cast<MemRefType>(storeBase.getType()),
vecType))
return;
copyToSharedMem.insert(writeOp);
return;
});
while (!copyToSharedMem.empty()) {
// Start a group with the first write.
SmallVector<Operation *> group;
Operation *writeOp = *copyToSharedMem.begin();
copyToSharedMem.remove(writeOp);
group.push_back(writeOp);
Operation *nextNode = writeOp;
// Look in the next nodes for more copies to add to the same group.
while ((nextNode = nextNode->getNextNode())) {
// Ignore ops without side effects.
auto memInterface = dyn_cast<MemoryEffectOpInterface>(nextNode);
if (memInterface && memInterface.hasNoEffect() &&
!nextNode->hasTrait<OpTrait::HasRecursiveMemoryEffects>())
continue;
// Ignore read from a different address space.
if (isa<vector::TransferReadOp, vector::LoadOp>(nextNode)) {
Operation *readOp = nextNode;
Value memrefOperand = nvgpu::getMemrefOperand(readOp);
if (!nvgpu::NVGPUDialect::hasSharedMemoryAddressSpace(
cast<MemRefType>(memrefOperand.getType()))) {
continue;
}
}
if (copyToSharedMem.count(nextNode)) {
// Found another copy, add it to the group.
copyToSharedMem.remove(nextNode);
group.push_back(nextNode);
continue;
}
// If the op is something else stop the accumulating op in the group.
break;
}
// Emit the group.
SmallVector<Value> tokens;
for (Operation *writeOp : group) {
rewriter.setInsertionPoint(writeOp);
Value vectorVal = nvgpu::getValueStored(writeOp);
auto vectorType = cast<VectorType>(vectorVal.getType());
int64_t numElements = vectorType.getNumElements();
Operation *readOp = vectorVal.getDefiningOp();
Value storeBase = nvgpu::getMemrefOperand(writeOp);
Value loadBase = nvgpu::getMemrefOperand(readOp);
Value numReadElements =
buildNumReadElements(rewriter, writeOp->getLoc(), readOp);
auto dstMemref = cast<MemRefType>(storeBase.getType());
int64_t sizeInBytes =
(dstMemref.getElementTypeBitWidth() * numElements) / 8;
// bypass_l1 only possible with 16 byte transfer.
Value token = rewriter.create<nvgpu::DeviceAsyncCopyOp>(
writeOp->getLoc(), nvgpu::DeviceAsyncTokenType::get(op->getContext()),
/*dst=*/storeBase, /*dstIndices=*/nvgpu::getIndices(writeOp),
/*src=*/loadBase,
/*srcIndices=*/nvgpu::getIndices(readOp),
/*dstElements=*/rewriter.getIndexAttr(numElements),
/*srcElements=*/numReadElements,
/*bypassL1=*/bypassL1 && sizeInBytes == 16 ? rewriter.getUnitAttr()
: UnitAttr());
tokens.push_back(token);
}
// Create the group and wait for it right after.
Value groupToken = rewriter.create<nvgpu::DeviceAsyncCreateGroupOp>(
op->getLoc(), nvgpu::DeviceAsyncTokenType::get(op->getContext()),
tokens);
rewriter.create<nvgpu::DeviceAsyncWaitOp>(op->getLoc(), groupToken,
nullptr);
// Clean up old stores.
for (Operation *writeOp : group)
rewriter.eraseOp(writeOp);
}
}
|