1 //===- AsyncRegionRewriter.cpp - Implementation of GPU async rewriters ----===// 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 implements the GPU dialect pattern rewriters that make GPU op 10 // within a region execute asynchronously. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "mlir/Dialect/GPU/Transforms/Passes.h" 15 16 #include "mlir/Dialect/Async/IR/Async.h" 17 #include "mlir/Dialect/Func/IR/FuncOps.h" 18 #include "mlir/Dialect/GPU/IR/GPUDialect.h" 19 #include "mlir/Dialect/GPU/Transforms/Utils.h" 20 #include "mlir/IR/BlockAndValueMapping.h" 21 #include "mlir/IR/Builders.h" 22 #include "mlir/IR/PatternMatch.h" 23 #include "mlir/IR/SymbolTable.h" 24 #include "mlir/Support/LLVM.h" 25 #include "mlir/Transforms/RegionUtils.h" 26 #include "llvm/ADT/TypeSwitch.h" 27 28 namespace mlir { 29 #define GEN_PASS_DEF_GPUASYNCREGIONPASS 30 #include "mlir/Dialect/GPU/Transforms/Passes.h.inc" 31 } // namespace mlir 32 33 using namespace mlir; 34 35 namespace { 36 class GpuAsyncRegionPass 37 : public impl::GpuAsyncRegionPassBase<GpuAsyncRegionPass> { 38 struct ThreadTokenCallback; 39 struct DeferWaitCallback; 40 struct SingleTokenUseCallback; 41 void runOnOperation() override; 42 }; 43 } // namespace 44 45 static bool isTerminator(Operation *op) { 46 return op->mightHaveTrait<OpTrait::IsTerminator>(); 47 } 48 static bool hasSideEffects(Operation *op) { 49 return !MemoryEffectOpInterface::hasNoEffect(op); 50 } 51 52 // Region walk callback which makes GPU ops implementing the AsyncOpInterface 53 // execute asynchronously. 54 struct GpuAsyncRegionPass::ThreadTokenCallback { 55 ThreadTokenCallback(MLIRContext &context) : builder(&context) {} 56 57 WalkResult operator()(Block *block) { 58 for (Operation &op : make_early_inc_range(*block)) { 59 if (failed(visit(&op))) 60 return WalkResult::interrupt(); 61 } 62 return WalkResult::advance(); 63 } 64 65 private: 66 // If `op` implements the AsyncOpInterface, insert a `gpu.wait async` to 67 // create a current token (unless it already exists), and 'thread' that token 68 // through the `op` so that it executes asynchronously. 69 // 70 // If `op` is a terminator or an op with side-effects, insert a `gpu.wait` to 71 // host-synchronize execution. A `!gpu.async.token` will therefore only be 72 // used inside of its block and GPU execution will always synchronize with 73 // the host at block boundaries. 74 LogicalResult visit(Operation *op) { 75 if (isa<gpu::LaunchOp>(op)) 76 return op->emitOpError("replace with gpu.launch_func first"); 77 if (auto waitOp = llvm::dyn_cast<gpu::WaitOp>(op)) { 78 if (currentToken) 79 waitOp.addAsyncDependency(currentToken); 80 currentToken = waitOp.getAsyncToken(); 81 return success(); 82 } 83 builder.setInsertionPoint(op); 84 if (auto asyncOp = dyn_cast<gpu::AsyncOpInterface>(op)) 85 return rewriteAsyncOp(asyncOp); // Replace GPU op with async version. 86 if (!currentToken) 87 return success(); 88 // Insert host synchronization before terminator or op with side effects. 89 if (isTerminator(op) || hasSideEffects(op)) 90 currentToken = createWaitOp(op->getLoc(), Type(), {currentToken}); 91 return success(); 92 } 93 94 // Replaces asyncOp with a clone that returns a token. 95 LogicalResult rewriteAsyncOp(gpu::AsyncOpInterface asyncOp) { 96 auto *op = asyncOp.getOperation(); 97 auto tokenType = builder.getType<gpu::AsyncTokenType>(); 98 99 // If there is no current token, insert a `gpu.wait async` without 100 // dependencies to create one. 101 if (!currentToken) 102 currentToken = createWaitOp(op->getLoc(), tokenType, {}); 103 asyncOp.addAsyncDependency(currentToken); 104 105 // Return early if op returns a token already. 106 currentToken = asyncOp.getAsyncToken(); 107 if (currentToken) 108 return success(); 109 110 // Clone the op to return a token in addition to the other results. 111 SmallVector<Type, 1> resultTypes; 112 resultTypes.reserve(1 + op->getNumResults()); 113 copy(op->getResultTypes(), std::back_inserter(resultTypes)); 114 resultTypes.push_back(tokenType); 115 auto *newOp = Operation::create(op->getLoc(), op->getName(), resultTypes, 116 op->getOperands(), op->getAttrDictionary(), 117 op->getSuccessors(), op->getNumRegions()); 118 119 // Clone regions into new op. 120 BlockAndValueMapping mapping; 121 for (auto pair : llvm::zip_first(op->getRegions(), newOp->getRegions())) 122 std::get<0>(pair).cloneInto(&std::get<1>(pair), mapping); 123 124 // Replace the op with the async clone. 125 auto results = newOp->getResults(); 126 currentToken = results.back(); 127 builder.insert(newOp); 128 op->replaceAllUsesWith(results.drop_back()); 129 op->erase(); 130 131 return success(); 132 } 133 134 Value createWaitOp(Location loc, Type resultType, ValueRange operands) { 135 return builder.create<gpu::WaitOp>(loc, resultType, operands) 136 .getAsyncToken(); 137 } 138 139 OpBuilder builder; 140 141 // The token that represents the current asynchronous dependency. It's valid 142 // range starts with a `gpu.wait async` op, and ends with a `gpu.wait` op. 143 // In between, each gpu::AsyncOpInterface depends on the current token and 144 // produces the new one. 145 Value currentToken = {}; 146 }; 147 148 /// Erases `executeOp` and returns a clone with additional `results`. 149 async::ExecuteOp addExecuteResults(async::ExecuteOp executeOp, 150 ValueRange results) { 151 // Add values to async.yield op. 152 Operation *yieldOp = executeOp.getBody()->getTerminator(); 153 yieldOp->insertOperands(yieldOp->getNumOperands(), results); 154 155 // Construct new result type list with additional types. 156 SmallVector<Type, 2> resultTypes; 157 resultTypes.reserve(executeOp.getNumResults() + results.size()); 158 transform(executeOp.getResultTypes(), std::back_inserter(resultTypes), 159 [](Type type) { 160 // Extract value type from !async.value. 161 if (auto valueType = type.dyn_cast<async::ValueType>()) 162 return valueType.getValueType(); 163 assert(type.isa<async::TokenType>() && "expected token type"); 164 return type; 165 }); 166 transform(results, std::back_inserter(resultTypes), 167 [](Value value) { return value.getType(); }); 168 169 // Clone executeOp with the extra results. 170 OpBuilder builder(executeOp); 171 auto newOp = builder.create<async::ExecuteOp>( 172 executeOp.getLoc(), TypeRange{resultTypes}.drop_front() /*drop token*/, 173 executeOp.getDependencies(), executeOp.getBodyOperands()); 174 BlockAndValueMapping mapper; 175 newOp.getRegion().getBlocks().clear(); 176 executeOp.getRegion().cloneInto(&newOp.getRegion(), mapper); 177 178 // Replace executeOp with cloned one. 179 executeOp.getOperation()->replaceAllUsesWith( 180 newOp.getResults().drop_back(results.size())); 181 executeOp.erase(); 182 183 return newOp; 184 } 185 186 // Callback for `async.execute` ops which tries to push the contained 187 // synchronous `gpu.wait` op to the dependencies of the `async.execute`. 188 struct GpuAsyncRegionPass::DeferWaitCallback { 189 // If the `executeOp`s token is used only in `async.execute` or `async.await` 190 // ops, add the region's last `gpu.wait` op to the worklist if it is 191 // synchronous and is the last op with side effects. 192 void operator()(async::ExecuteOp executeOp) { 193 if (!areAllUsersExecuteOrAwait(executeOp.getToken())) 194 return; 195 // async.execute's region is currently restricted to one block. 196 for (auto &op : llvm::reverse(executeOp.getBody()->without_terminator())) { 197 if (auto waitOp = dyn_cast<gpu::WaitOp>(op)) { 198 if (!waitOp.getAsyncToken()) 199 worklist.push_back(waitOp); 200 return; 201 } 202 if (hasSideEffects(&op)) 203 return; 204 } 205 } 206 207 // The destructor performs the actual rewrite work. 208 ~DeferWaitCallback() { 209 for (size_t i = 0; i < worklist.size(); ++i) { 210 auto waitOp = worklist[i]; 211 auto executeOp = waitOp->getParentOfType<async::ExecuteOp>(); 212 213 // Erase `gpu.wait` and return async dependencies from execute op instead. 214 SmallVector<Value, 4> dependencies = waitOp.getAsyncDependencies(); 215 waitOp.erase(); 216 executeOp = addExecuteResults(executeOp, dependencies); 217 218 // Add the async dependency to each user of the `async.execute` token. 219 auto asyncTokens = executeOp.getResults().take_back(dependencies.size()); 220 SmallVector<Operation *, 4> users(executeOp.getToken().user_begin(), 221 executeOp.getToken().user_end()); 222 for (Operation *user : users) 223 addAsyncDependencyAfter(asyncTokens, user); 224 } 225 } 226 227 private: 228 // Returns whether all token users are either 'async.execute' or 'async.await' 229 // ops. This is used as a requirement for pushing 'gpu.wait' ops from a 230 // 'async.execute' body to it's users. Specifically, we do not allow 231 // terminator users, because it could mean that the `async.execute` is inside 232 // control flow code. 233 static bool areAllUsersExecuteOrAwait(Value token) { 234 return !token.use_empty() && 235 llvm::all_of(token.getUsers(), [](Operation *user) { 236 return isa<async::ExecuteOp, async::AwaitOp>(user); 237 }); 238 } 239 240 // Add the `asyncToken` as dependency as needed after `op`. 241 void addAsyncDependencyAfter(ValueRange asyncTokens, Operation *op) { 242 OpBuilder builder(op->getContext()); 243 auto loc = op->getLoc(); 244 245 Block::iterator it; 246 SmallVector<Value, 1> tokens; 247 tokens.reserve(asyncTokens.size()); 248 TypeSwitch<Operation *>(op) 249 .Case<async::AwaitOp>([&](auto awaitOp) { 250 // Add async.await ops to wait for the !gpu.async.tokens. 251 builder.setInsertionPointAfter(op); 252 for (auto asyncToken : asyncTokens) 253 tokens.push_back( 254 builder.create<async::AwaitOp>(loc, asyncToken).getResult()); 255 // Set `it` after the inserted async.await ops. 256 it = builder.getInsertionPoint(); 257 }) 258 .Case<async::ExecuteOp>([&](auto executeOp) { 259 // Set `it` to the beginning of the region and add asyncTokens to the 260 // async.execute operands. 261 it = executeOp.getBody()->begin(); 262 executeOp.getBodyOperandsMutable().append(asyncTokens); 263 SmallVector<Type, 1> tokenTypes( 264 asyncTokens.size(), builder.getType<gpu::AsyncTokenType>()); 265 SmallVector<Location, 1> tokenLocs(asyncTokens.size(), 266 executeOp.getLoc()); 267 copy(executeOp.getBody()->addArguments(tokenTypes, tokenLocs), 268 std::back_inserter(tokens)); 269 }); 270 271 // Advance `it` to terminator or op with side-effects. 272 it = std::find_if(it, Block::iterator(), [](Operation &op) { 273 return isTerminator(&op) || hasSideEffects(&op); 274 }); 275 276 // If `op` implements the AsyncOpInterface, add `token` to the list of async 277 // dependencies. 278 if (auto asyncOp = dyn_cast<gpu::AsyncOpInterface>(*it)) { 279 for (auto token : tokens) 280 asyncOp.addAsyncDependency(token); 281 return; 282 } 283 284 // Otherwise, insert a gpu.wait before 'it'. 285 builder.setInsertionPoint(it->getBlock(), it); 286 auto waitOp = builder.create<gpu::WaitOp>(loc, Type{}, tokens); 287 288 // If the new waitOp is at the end of an async.execute region, add it to the 289 // worklist. 'operator()(executeOp)' would do the same, but this is faster. 290 auto executeOp = dyn_cast<async::ExecuteOp>(it->getParentOp()); 291 if (executeOp && areAllUsersExecuteOrAwait(executeOp.getToken()) && 292 !it->getNextNode()) 293 worklist.push_back(waitOp); 294 } 295 296 SmallVector<gpu::WaitOp, 8> worklist; 297 }; 298 299 // Callback for `async.execute` ops which repeats !gpu.async.token results 300 // so that each of them is only used once. 301 struct GpuAsyncRegionPass::SingleTokenUseCallback { 302 void operator()(async::ExecuteOp executeOp) { 303 // Extract !gpu.async.token results which have multiple uses. 304 auto multiUseResults = llvm::make_filter_range( 305 executeOp.getBodyResults(), [](OpResult result) { 306 if (result.use_empty() || result.hasOneUse()) 307 return false; 308 auto valueType = result.getType().dyn_cast<async::ValueType>(); 309 return valueType && 310 valueType.getValueType().isa<gpu::AsyncTokenType>(); 311 }); 312 if (multiUseResults.empty()) 313 return; 314 315 // Indices within !async.execute results (i.e. without the async.token). 316 SmallVector<int, 4> indices; 317 transform(multiUseResults, std::back_inserter(indices), 318 [](OpResult result) { 319 return result.getResultNumber() - 1; // Index without token. 320 }); 321 322 for (auto index : indices) { 323 assert(!executeOp.getBodyResults()[index].getUses().empty()); 324 // Repeat async.yield token result, one for each use after the first one. 325 auto uses = llvm::drop_begin(executeOp.getBodyResults()[index].getUses()); 326 auto count = std::distance(uses.begin(), uses.end()); 327 auto yieldOp = cast<async::YieldOp>(executeOp.getBody()->getTerminator()); 328 SmallVector<Value, 4> operands(count, yieldOp.getOperand(index)); 329 executeOp = addExecuteResults(executeOp, operands); 330 // Update 'uses' to refer to the new executeOp. 331 uses = llvm::drop_begin(executeOp.getBodyResults()[index].getUses()); 332 auto results = executeOp.getBodyResults().take_back(count); 333 for (auto pair : llvm::zip(uses, results)) 334 std::get<0>(pair).set(std::get<1>(pair)); 335 } 336 } 337 }; 338 339 // Replaces synchronous GPU ops in the op's region with asynchronous ones and 340 // inserts the necessary synchronization (as gpu.wait ops). Assumes sequential 341 // execution semantics and that no GPU ops are asynchronous yet. 342 void GpuAsyncRegionPass::runOnOperation() { 343 if (getOperation()->walk(ThreadTokenCallback(getContext())).wasInterrupted()) 344 return signalPassFailure(); 345 346 // Collect gpu.wait ops that we can move out of async.execute regions. 347 getOperation().getRegion().walk(DeferWaitCallback()); 348 // Makes each !gpu.async.token returned from async.execute op have single use. 349 getOperation().getRegion().walk(SingleTokenUseCallback()); 350 } 351 352 std::unique_ptr<OperationPass<func::FuncOp>> mlir::createGpuAsyncRegionPass() { 353 return std::make_unique<GpuAsyncRegionPass>(); 354 } 355