18bfedb3cSKazuaki Ishizaki //===- KernelOutlining.cpp - Implementation of GPU kernel outlining -------===// 260965b46SAlex Zinenko // 330857107SMehdi Amini // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 456222a06SMehdi Amini // See https://llvm.org/LICENSE.txt for license information. 556222a06SMehdi Amini // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 660965b46SAlex Zinenko // 756222a06SMehdi Amini //===----------------------------------------------------------------------===// 860965b46SAlex Zinenko // 960965b46SAlex Zinenko // This file implements the GPU dialect kernel outlining pass. 1060965b46SAlex Zinenko // 1160965b46SAlex Zinenko //===----------------------------------------------------------------------===// 1260965b46SAlex Zinenko 131834ad4aSRiver Riddle #include "PassDetail.h" 14*a54f4eaeSMogball #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" 1560965b46SAlex Zinenko #include "mlir/Dialect/GPU/GPUDialect.h" 1660965b46SAlex Zinenko #include "mlir/Dialect/GPU/Passes.h" 173f44495dSMaheshRavishankar #include "mlir/Dialect/GPU/Utils.h" 18e2310704SJulian Gross #include "mlir/Dialect/MemRef/IR/MemRef.h" 1969d757c0SRob Suderman #include "mlir/Dialect/StandardOps/IR/Ops.h" 2060965b46SAlex Zinenko #include "mlir/IR/BlockAndValueMapping.h" 2160965b46SAlex Zinenko #include "mlir/IR/Builders.h" 22b8cd0c14STres Popp #include "mlir/IR/SymbolTable.h" 23edeff6e6SStephan Herhut #include "mlir/Support/LLVM.h" 24283b5e73SStephan Herhut #include "mlir/Transforms/RegionUtils.h" 2560965b46SAlex Zinenko 2660965b46SAlex Zinenko using namespace mlir; 2760965b46SAlex Zinenko 2860965b46SAlex Zinenko template <typename OpTy> 2960965b46SAlex Zinenko static void createForAllDimensions(OpBuilder &builder, Location loc, 30e62a6956SRiver Riddle SmallVectorImpl<Value> &values) { 3160965b46SAlex Zinenko for (StringRef dim : {"x", "y", "z"}) { 32e62a6956SRiver Riddle Value v = builder.create<OpTy>(loc, builder.getIndexType(), 3360965b46SAlex Zinenko builder.getStringAttr(dim)); 3460965b46SAlex Zinenko values.push_back(v); 3560965b46SAlex Zinenko } 3660965b46SAlex Zinenko } 3760965b46SAlex Zinenko 38edeff6e6SStephan Herhut /// Adds operations generating block/thread ids and grid/block dimensions at the 39edeff6e6SStephan Herhut /// beginning of the `launchFuncOpBody` region. Add mapping from argument in 40edeff6e6SStephan Herhut /// entry block of `launchOpBody`, to the corresponding result value of the 41edeff6e6SStephan Herhut /// added operations. 423f44495dSMaheshRavishankar static void injectGpuIndexOperations(Location loc, Region &launchFuncOpBody, 433f44495dSMaheshRavishankar Region &launchOpBody, 443f44495dSMaheshRavishankar BlockAndValueMapping &map) { 456273fa0cSAlex Zinenko OpBuilder builder(loc->getContext()); 463f44495dSMaheshRavishankar Block &firstBlock = launchOpBody.front(); 473f44495dSMaheshRavishankar builder.setInsertionPointToStart(&launchFuncOpBody.front()); 48e62a6956SRiver Riddle SmallVector<Value, 12> indexOps; 496273fa0cSAlex Zinenko createForAllDimensions<gpu::BlockIdOp>(builder, loc, indexOps); 506273fa0cSAlex Zinenko createForAllDimensions<gpu::ThreadIdOp>(builder, loc, indexOps); 516273fa0cSAlex Zinenko createForAllDimensions<gpu::GridDimOp>(builder, loc, indexOps); 526273fa0cSAlex Zinenko createForAllDimensions<gpu::BlockDimOp>(builder, loc, indexOps); 5360965b46SAlex Zinenko // Replace the leading 12 function args with the respective thread/block index 5460965b46SAlex Zinenko // operations. Iterate backwards since args are erased and indices change. 553f44495dSMaheshRavishankar for (auto indexOp : enumerate(indexOps)) 563f44495dSMaheshRavishankar map.map(firstBlock.getArgument(indexOp.index()), indexOp.value()); 5760965b46SAlex Zinenko } 5860965b46SAlex Zinenko 59edeff6e6SStephan Herhut /// Identifies operations that are beneficial to sink into kernels. These 60edeff6e6SStephan Herhut /// operations may not have side-effects, as otherwise sinking (and hence 61edeff6e6SStephan Herhut /// duplicating them) is not legal. 623f44495dSMaheshRavishankar static bool isSinkingBeneficiary(Operation *op) { 63*a54f4eaeSMogball return isa<arith::ConstantOp, ConstantOp, memref::DimOp, SelectOp, 64*a54f4eaeSMogball arith::CmpIOp>(op); 65edeff6e6SStephan Herhut } 66edeff6e6SStephan Herhut 67edeff6e6SStephan Herhut /// For a given operation `op`, computes whether it is beneficial to sink the 68edeff6e6SStephan Herhut /// operation into the kernel. An operation can be sunk if doing so does not 69edeff6e6SStephan Herhut /// introduce new kernel arguments. Whether a value is already available in the 70edeff6e6SStephan Herhut /// kernel (and hence does not introduce new arguments) is checked by 71366d8435SStephan Herhut /// querying `existingDependencies` and `availableValues`. 72edeff6e6SStephan Herhut /// If an operand is not yet available, we recursively check whether it can be 73edeff6e6SStephan Herhut /// made available by siking its defining op. 74edeff6e6SStephan Herhut /// Operations that are indentified for sinking are added to `beneficiaryOps` in 75366d8435SStephan Herhut /// the order they should appear in the kernel. Furthermore, `availableValues` 76366d8435SStephan Herhut /// is updated with results that will be available after sinking the identified 77edeff6e6SStephan Herhut /// ops. 78366d8435SStephan Herhut static bool 794efb7754SRiver Riddle extractBeneficiaryOps(Operation *op, SetVector<Value> existingDependencies, 804efb7754SRiver Riddle SetVector<Operation *> &beneficiaryOps, 81366d8435SStephan Herhut llvm::SmallPtrSetImpl<Value> &availableValues) { 82edeff6e6SStephan Herhut if (beneficiaryOps.count(op)) 83edeff6e6SStephan Herhut return true; 84edeff6e6SStephan Herhut 85edeff6e6SStephan Herhut if (!isSinkingBeneficiary(op)) 86edeff6e6SStephan Herhut return false; 87edeff6e6SStephan Herhut 88edeff6e6SStephan Herhut for (Value operand : op->getOperands()) { 8941b09f4eSKazuaki Ishizaki // It is already visible in the kernel, keep going. 90edeff6e6SStephan Herhut if (availableValues.count(operand)) 91edeff6e6SStephan Herhut continue; 92366d8435SStephan Herhut // Else check whether it can be made available via sinking or already is a 93366d8435SStephan Herhut // dependency. 94edeff6e6SStephan Herhut Operation *definingOp = operand.getDefiningOp(); 95366d8435SStephan Herhut if ((!definingOp || 96366d8435SStephan Herhut !extractBeneficiaryOps(definingOp, existingDependencies, 97366d8435SStephan Herhut beneficiaryOps, availableValues)) && 98366d8435SStephan Herhut !existingDependencies.count(operand)) 99edeff6e6SStephan Herhut return false; 100edeff6e6SStephan Herhut } 101edeff6e6SStephan Herhut // We will sink the operation, mark its results as now available. 102edeff6e6SStephan Herhut beneficiaryOps.insert(op); 103edeff6e6SStephan Herhut for (Value result : op->getResults()) 104edeff6e6SStephan Herhut availableValues.insert(result); 105edeff6e6SStephan Herhut return true; 106abb62668SStephan Herhut } 107abb62668SStephan Herhut 1083f44495dSMaheshRavishankar LogicalResult mlir::sinkOperationsIntoLaunchOp(gpu::LaunchOp launchOp) { 1093f44495dSMaheshRavishankar Region &launchOpBody = launchOp.body(); 110318ff019SStephan Herhut 1113f44495dSMaheshRavishankar // Identify uses from values defined outside of the scope of the launch 1123f44495dSMaheshRavishankar // operation. 1134efb7754SRiver Riddle SetVector<Value> sinkCandidates; 1143f44495dSMaheshRavishankar getUsedValuesDefinedAbove(launchOpBody, sinkCandidates); 1153f44495dSMaheshRavishankar 1164efb7754SRiver Riddle SetVector<Operation *> toBeSunk; 117366d8435SStephan Herhut llvm::SmallPtrSet<Value, 4> availableValues; 118366d8435SStephan Herhut for (Value operand : sinkCandidates) { 1193f44495dSMaheshRavishankar Operation *operandOp = operand.getDefiningOp(); 120edeff6e6SStephan Herhut if (!operandOp) 1213f44495dSMaheshRavishankar continue; 122366d8435SStephan Herhut extractBeneficiaryOps(operandOp, sinkCandidates, toBeSunk, availableValues); 123dfd06af5SStephan Herhut } 1243f44495dSMaheshRavishankar 1253f44495dSMaheshRavishankar // Insert operations so that the defs get cloned before uses. 1263f44495dSMaheshRavishankar BlockAndValueMapping map; 1273f44495dSMaheshRavishankar OpBuilder builder(launchOpBody); 128edeff6e6SStephan Herhut for (Operation *op : toBeSunk) { 129edeff6e6SStephan Herhut Operation *clonedOp = builder.clone(*op, map); 1303f44495dSMaheshRavishankar // Only replace uses within the launch op. 131edeff6e6SStephan Herhut for (auto pair : llvm::zip(op->getResults(), clonedOp->getResults())) 132edeff6e6SStephan Herhut replaceAllUsesInRegionWith(std::get<0>(pair), std::get<1>(pair), 133edeff6e6SStephan Herhut launchOp.body()); 1343f44495dSMaheshRavishankar } 1353f44495dSMaheshRavishankar return success(); 136dfd06af5SStephan Herhut } 137dfd06af5SStephan Herhut 138edeff6e6SStephan Herhut /// Outline the `gpu.launch` operation body into a kernel function. Replace 139edeff6e6SStephan Herhut /// `gpu.terminator` operations by `gpu.return` in the generated function. 1403f44495dSMaheshRavishankar static gpu::GPUFuncOp outlineKernelFuncImpl(gpu::LaunchOp launchOp, 1413f44495dSMaheshRavishankar StringRef kernelFnName, 1424efb7754SRiver Riddle SetVector<Value> &operands) { 14360965b46SAlex Zinenko Location loc = launchOp.getLoc(); 1446273fa0cSAlex Zinenko // Create a builder with no insertion point, insertion will happen separately 1456273fa0cSAlex Zinenko // due to symbol table manipulation. 1466273fa0cSAlex Zinenko OpBuilder builder(launchOp.getContext()); 1473f44495dSMaheshRavishankar Region &launchOpBody = launchOp.body(); 1486273fa0cSAlex Zinenko 149283b5e73SStephan Herhut // Identify uses from values defined outside of the scope of the launch 150283b5e73SStephan Herhut // operation. 1513f44495dSMaheshRavishankar getUsedValuesDefinedAbove(launchOpBody, operands); 152283b5e73SStephan Herhut 1533f44495dSMaheshRavishankar // Create the gpu.func operation. 154283b5e73SStephan Herhut SmallVector<Type, 4> kernelOperandTypes; 155283b5e73SStephan Herhut kernelOperandTypes.reserve(operands.size()); 156283b5e73SStephan Herhut for (Value operand : operands) { 157283b5e73SStephan Herhut kernelOperandTypes.push_back(operand.getType()); 158283b5e73SStephan Herhut } 15960965b46SAlex Zinenko FunctionType type = 1601b97cdf8SRiver Riddle FunctionType::get(launchOp.getContext(), kernelOperandTypes, {}); 1613f44495dSMaheshRavishankar auto outlinedFunc = builder.create<gpu::GPUFuncOp>(loc, kernelFnName, type); 1621ffc1aaaSChristian Sigg outlinedFunc->setAttr(gpu::GPUDialect::getKernelFuncAttrName(), 16360965b46SAlex Zinenko builder.getUnitAttr()); 1643f44495dSMaheshRavishankar BlockAndValueMapping map; 1653f44495dSMaheshRavishankar 1663f44495dSMaheshRavishankar // Map the arguments corresponding to the launch parameters like blockIdx, 1673f44495dSMaheshRavishankar // threadIdx, etc. 1683f44495dSMaheshRavishankar Region &outlinedFuncBody = outlinedFunc.body(); 1693f44495dSMaheshRavishankar injectGpuIndexOperations(loc, outlinedFuncBody, launchOpBody, map); 1703f44495dSMaheshRavishankar 1713f44495dSMaheshRavishankar // Map arguments from gpu.launch region to the arguments of the gpu.func 1723f44495dSMaheshRavishankar // operation. 1733f44495dSMaheshRavishankar Block &entryBlock = outlinedFuncBody.front(); 1743f44495dSMaheshRavishankar for (auto operand : enumerate(operands)) 1753f44495dSMaheshRavishankar map.map(operand.value(), entryBlock.getArgument(operand.index())); 1763f44495dSMaheshRavishankar 1773f44495dSMaheshRavishankar // Clone the region of the gpu.launch operation into the gpu.func operation. 1789db53a18SRiver Riddle // TODO: If cloneInto can be modified such that if a mapping for 1793f44495dSMaheshRavishankar // a block exists, that block will be used to clone operations into (at the 1803f44495dSMaheshRavishankar // end of the block), instead of creating a new block, this would be much 1813f44495dSMaheshRavishankar // cleaner. 1823f44495dSMaheshRavishankar launchOpBody.cloneInto(&outlinedFuncBody, map); 1833f44495dSMaheshRavishankar 1845aacce3dSKazuaki Ishizaki // Branch from entry of the gpu.func operation to the block that is cloned 1855aacce3dSKazuaki Ishizaki // from the entry block of the gpu.launch operation. 1863f44495dSMaheshRavishankar Block &launchOpEntry = launchOpBody.front(); 1873f44495dSMaheshRavishankar Block *clonedLaunchOpEntry = map.lookup(&launchOpEntry); 1883f44495dSMaheshRavishankar builder.setInsertionPointToEnd(&entryBlock); 1893f44495dSMaheshRavishankar builder.create<BranchOp>(loc, clonedLaunchOpEntry); 1903f44495dSMaheshRavishankar 19126927518SStephan Herhut outlinedFunc.walk([](gpu::TerminatorOp op) { 19226927518SStephan Herhut OpBuilder replacer(op); 19326927518SStephan Herhut replacer.create<gpu::ReturnOp>(op.getLoc()); 19426927518SStephan Herhut op.erase(); 19526927518SStephan Herhut }); 19660965b46SAlex Zinenko return outlinedFunc; 19760965b46SAlex Zinenko } 19860965b46SAlex Zinenko 1993f44495dSMaheshRavishankar gpu::GPUFuncOp mlir::outlineKernelFunc(gpu::LaunchOp launchOp, 2003f44495dSMaheshRavishankar StringRef kernelFnName, 2013f44495dSMaheshRavishankar llvm::SmallVectorImpl<Value> &operands) { 2023f44495dSMaheshRavishankar DenseSet<Value> inputOperandSet; 2033f44495dSMaheshRavishankar inputOperandSet.insert(operands.begin(), operands.end()); 2044efb7754SRiver Riddle SetVector<Value> operandSet(operands.begin(), operands.end()); 2053f44495dSMaheshRavishankar auto funcOp = outlineKernelFuncImpl(launchOp, kernelFnName, operandSet); 2063f44495dSMaheshRavishankar for (auto operand : operandSet) { 2073f44495dSMaheshRavishankar if (!inputOperandSet.count(operand)) 2083f44495dSMaheshRavishankar operands.push_back(operand); 2093f44495dSMaheshRavishankar } 2103f44495dSMaheshRavishankar return funcOp; 2113f44495dSMaheshRavishankar } 2123f44495dSMaheshRavishankar 213edeff6e6SStephan Herhut /// Replace `gpu.launch` operations with an `gpu.launch_func` operation 214edeff6e6SStephan Herhut /// launching `kernelFunc`. The kernel func contains the body of the 215edeff6e6SStephan Herhut /// `gpu.launch` with constant region arguments inlined. 2163f44495dSMaheshRavishankar static void convertToLaunchFuncOp(gpu::LaunchOp launchOp, 217283b5e73SStephan Herhut gpu::GPUFuncOp kernelFunc, 218283b5e73SStephan Herhut ValueRange operands) { 21960965b46SAlex Zinenko OpBuilder builder(launchOp); 22008b63db8SUday Bondhugula // The launch op has an optional dynamic shared memory size. If it doesn't 22108b63db8SUday Bondhugula // exist, we use zero. 2223f44495dSMaheshRavishankar builder.create<gpu::LaunchFuncOp>( 22360965b46SAlex Zinenko launchOp.getLoc(), kernelFunc, launchOp.getGridSizeOperandValues(), 22408b63db8SUday Bondhugula launchOp.getBlockSizeOperandValues(), launchOp.dynamicSharedMemorySize(), 22508b63db8SUday Bondhugula operands); 22660965b46SAlex Zinenko launchOp.erase(); 22760965b46SAlex Zinenko } 22860965b46SAlex Zinenko 22960965b46SAlex Zinenko namespace { 230b8676da1SChristian Sigg /// Pass that moves the kernel of each LaunchOp into its separate nested module. 231b8676da1SChristian Sigg /// 232b8676da1SChristian Sigg /// This pass moves the kernel code of each LaunchOp into a function created 233b8676da1SChristian Sigg /// inside a nested module. It also creates an external function of the same 234b8676da1SChristian Sigg /// name in the parent module. 235b8676da1SChristian Sigg /// 2369a52ea5cSTres Popp /// The gpu.modules are intended to be compiled to a cubin blob independently in 2379a52ea5cSTres Popp /// a separate pass. The external functions can then be annotated with the 238b8676da1SChristian Sigg /// symbol of the cubin accessor function. 239722f909fSRiver Riddle class GpuKernelOutliningPass 2401834ad4aSRiver Riddle : public GpuKernelOutliningBase<GpuKernelOutliningPass> { 24160965b46SAlex Zinenko public: 242722f909fSRiver Riddle void runOnOperation() override { 243722f909fSRiver Riddle SymbolTable symbolTable(getOperation()); 24490d65d32SAlex Zinenko bool modified = false; 245722f909fSRiver Riddle for (auto func : getOperation().getOps<FuncOp>()) { 246b8676da1SChristian Sigg // Insert just after the function. 247c4a04059SChristian Sigg Block::iterator insertPt(func->getNextNode()); 2483f44495dSMaheshRavishankar auto funcWalkResult = func.walk([&](gpu::LaunchOp op) { 2494efb7754SRiver Riddle SetVector<Value> operands; 2503f44495dSMaheshRavishankar std::string kernelFnName = 2510bf4a82aSChristian Sigg Twine(op->getParentOfType<FuncOp>().getName(), "_kernel").str(); 2523f44495dSMaheshRavishankar 2533f44495dSMaheshRavishankar // Pull in instructions that can be sunk 2543f44495dSMaheshRavishankar if (failed(sinkOperationsIntoLaunchOp(op))) 2553f44495dSMaheshRavishankar return WalkResult::interrupt(); 2563f44495dSMaheshRavishankar gpu::GPUFuncOp outlinedFunc = 2573f44495dSMaheshRavishankar outlineKernelFuncImpl(op, kernelFnName, operands); 258b8676da1SChristian Sigg 25990d65d32SAlex Zinenko // Create nested module and insert outlinedFunc. The module will 26090d65d32SAlex Zinenko // originally get the same name as the function, but may be renamed on 26190d65d32SAlex Zinenko // insertion into the parent module. 262b8cd0c14STres Popp auto kernelModule = createKernelModule(outlinedFunc, symbolTable); 263b8cd0c14STres Popp symbolTable.insert(kernelModule, insertPt); 264b8676da1SChristian Sigg 265b8676da1SChristian Sigg // Potentially changes signature, pulling in constants. 266283b5e73SStephan Herhut convertToLaunchFuncOp(op, outlinedFunc, operands.getArrayRef()); 26790d65d32SAlex Zinenko modified = true; 2683f44495dSMaheshRavishankar return WalkResult::advance(); 26960965b46SAlex Zinenko }); 2703f44495dSMaheshRavishankar if (funcWalkResult.wasInterrupted()) 2713f44495dSMaheshRavishankar return signalPassFailure(); 27260965b46SAlex Zinenko } 27390d65d32SAlex Zinenko 27490d65d32SAlex Zinenko // If any new module was inserted in this module, annotate this module as 27590d65d32SAlex Zinenko // a container module. 27690d65d32SAlex Zinenko if (modified) 2771ffc1aaaSChristian Sigg getOperation()->setAttr(gpu::GPUDialect::getContainerModuleAttrName(), 27890d65d32SAlex Zinenko UnitAttr::get(&getContext())); 27960965b46SAlex Zinenko } 28074cdbf59SChristian Sigg 28174cdbf59SChristian Sigg private: 282edeff6e6SStephan Herhut /// Returns a gpu.module containing kernelFunc and all callees (recursive). 2839a52ea5cSTres Popp gpu::GPUModuleOp createKernelModule(gpu::GPUFuncOp kernelFunc, 284b8cd0c14STres Popp const SymbolTable &parentSymbolTable) { 2859a52ea5cSTres Popp // TODO: This code cannot use an OpBuilder because it must be inserted into 2869a52ea5cSTres Popp // a SymbolTable by the caller. SymbolTable needs to be refactored to 2879a52ea5cSTres Popp // prevent manual building of Ops with symbols in code using SymbolTables 2889a52ea5cSTres Popp // and then this needs to use the OpBuilder. 289722f909fSRiver Riddle auto context = getOperation().getContext(); 290bb1d976fSAlex Zinenko OpBuilder builder(context); 291e1364f10SMehdi Amini auto kernelModule = builder.create<gpu::GPUModuleOp>(kernelFunc.getLoc(), 292e1364f10SMehdi Amini kernelFunc.getName()); 293b8cd0c14STres Popp SymbolTable symbolTable(kernelModule); 294b8cd0c14STres Popp symbolTable.insert(kernelFunc); 29574cdbf59SChristian Sigg 2964562e389SRiver Riddle SmallVector<Operation *, 8> symbolDefWorklist = {kernelFunc}; 2979fbf52e3SMLIR Team while (!symbolDefWorklist.empty()) { 2989fbf52e3SMLIR Team if (Optional<SymbolTable::UseRange> symbolUses = 2999fbf52e3SMLIR Team SymbolTable::getSymbolUses(symbolDefWorklist.pop_back_val())) { 3009fbf52e3SMLIR Team for (SymbolTable::SymbolUse symbolUse : *symbolUses) { 3019b9c647cSRiver Riddle StringRef symbolName = 3029b9c647cSRiver Riddle symbolUse.getSymbolRef().cast<FlatSymbolRefAttr>().getValue(); 303b8cd0c14STres Popp if (symbolTable.lookup(symbolName)) 3049fbf52e3SMLIR Team continue; 30574cdbf59SChristian Sigg 3069fbf52e3SMLIR Team Operation *symbolDefClone = 307b8cd0c14STres Popp parentSymbolTable.lookup(symbolName)->clone(); 3089fbf52e3SMLIR Team symbolDefWorklist.push_back(symbolDefClone); 309b8cd0c14STres Popp symbolTable.insert(symbolDefClone); 3109fbf52e3SMLIR Team } 3119fbf52e3SMLIR Team } 31274cdbf59SChristian Sigg } 31374cdbf59SChristian Sigg 31474cdbf59SChristian Sigg return kernelModule; 31574cdbf59SChristian Sigg } 31660965b46SAlex Zinenko }; 31760965b46SAlex Zinenko 31860965b46SAlex Zinenko } // namespace 31960965b46SAlex Zinenko 32080aca1eaSRiver Riddle std::unique_ptr<OperationPass<ModuleOp>> mlir::createGpuKernelOutliningPass() { 32179f53b0cSJacques Pienaar return std::make_unique<GpuKernelOutliningPass>(); 32260965b46SAlex Zinenko } 323