1 //===- KernelOutlining.cpp - Implementation of GPU kernel outlining -------===// 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 kernel outlining pass. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PassDetail.h" 14 #include "mlir/Dialect/GPU/GPUDialect.h" 15 #include "mlir/Dialect/GPU/Passes.h" 16 #include "mlir/Dialect/GPU/Utils.h" 17 #include "mlir/Dialect/StandardOps/IR/Ops.h" 18 #include "mlir/IR/BlockAndValueMapping.h" 19 #include "mlir/IR/Builders.h" 20 #include "mlir/IR/SymbolTable.h" 21 #include "mlir/Support/LLVM.h" 22 #include "mlir/Transforms/RegionUtils.h" 23 24 using namespace mlir; 25 26 template <typename OpTy> 27 static void createForAllDimensions(OpBuilder &builder, Location loc, 28 SmallVectorImpl<Value> &values) { 29 for (StringRef dim : {"x", "y", "z"}) { 30 Value v = builder.create<OpTy>(loc, builder.getIndexType(), 31 builder.getStringAttr(dim)); 32 values.push_back(v); 33 } 34 } 35 36 /// Adds operations generating block/thread ids and grid/block dimensions at the 37 /// beginning of the `launchFuncOpBody` region. Add mapping from argument in 38 /// entry block of `launchOpBody`, to the corresponding result value of the 39 /// added operations. 40 static void injectGpuIndexOperations(Location loc, Region &launchFuncOpBody, 41 Region &launchOpBody, 42 BlockAndValueMapping &map) { 43 OpBuilder builder(loc->getContext()); 44 Block &firstBlock = launchOpBody.front(); 45 builder.setInsertionPointToStart(&launchFuncOpBody.front()); 46 SmallVector<Value, 12> indexOps; 47 createForAllDimensions<gpu::BlockIdOp>(builder, loc, indexOps); 48 createForAllDimensions<gpu::ThreadIdOp>(builder, loc, indexOps); 49 createForAllDimensions<gpu::GridDimOp>(builder, loc, indexOps); 50 createForAllDimensions<gpu::BlockDimOp>(builder, loc, indexOps); 51 // Replace the leading 12 function args with the respective thread/block index 52 // operations. Iterate backwards since args are erased and indices change. 53 for (auto indexOp : enumerate(indexOps)) 54 map.map(firstBlock.getArgument(indexOp.index()), indexOp.value()); 55 } 56 57 /// Identifies operations that are beneficial to sink into kernels. These 58 /// operations may not have side-effects, as otherwise sinking (and hence 59 /// duplicating them) is not legal. 60 static bool isSinkingBeneficiary(Operation *op) { 61 return isa<ConstantOp, DimOp, SelectOp, CmpIOp>(op); 62 } 63 64 /// For a given operation `op`, computes whether it is beneficial to sink the 65 /// operation into the kernel. An operation can be sunk if doing so does not 66 /// introduce new kernel arguments. Whether a value is already available in the 67 /// kernel (and hence does not introduce new arguments) is checked by 68 /// querying `availableValues`. 69 /// If an operand is not yet available, we recursively check whether it can be 70 /// made available by siking its defining op. 71 /// Operations that are indentified for sinking are added to `beneficiaryOps` in 72 /// the order the should appear in the kernel. Furthermore, `availableValues` is 73 /// updated with results that will be available after sinking the identified 74 /// ops. 75 static bool extractBeneficiaryOps(Operation *op, 76 llvm::SetVector<Operation *> &beneficiaryOps, 77 llvm::SetVector<Value> &availableValues) { 78 if (beneficiaryOps.count(op)) 79 return true; 80 81 if (!isSinkingBeneficiary(op)) 82 return false; 83 84 for (Value operand : op->getOperands()) { 85 // It is already visisble in the kernel, keep going. 86 if (availableValues.count(operand)) 87 continue; 88 // Else check whether it can be made available via sinking. 89 Operation *definingOp = operand.getDefiningOp(); 90 if (!definingOp || 91 !extractBeneficiaryOps(definingOp, beneficiaryOps, availableValues)) 92 return false; 93 } 94 // We will sink the operation, mark its results as now available. 95 beneficiaryOps.insert(op); 96 for (Value result : op->getResults()) 97 availableValues.insert(result); 98 return true; 99 } 100 101 LogicalResult mlir::sinkOperationsIntoLaunchOp(gpu::LaunchOp launchOp) { 102 Region &launchOpBody = launchOp.body(); 103 104 // Identify uses from values defined outside of the scope of the launch 105 // operation. 106 llvm::SetVector<Value> sinkCandidates; 107 getUsedValuesDefinedAbove(launchOpBody, sinkCandidates); 108 109 SmallVector<Value, 4> worklist(sinkCandidates.begin(), sinkCandidates.end()); 110 llvm::SetVector<Operation *> toBeSunk; 111 for (Value operand : worklist) { 112 Operation *operandOp = operand.getDefiningOp(); 113 if (!operandOp) 114 continue; 115 extractBeneficiaryOps(operandOp, toBeSunk, sinkCandidates); 116 } 117 118 // Insert operations so that the defs get cloned before uses. 119 BlockAndValueMapping map; 120 OpBuilder builder(launchOpBody); 121 for (Operation *op : toBeSunk) { 122 Operation *clonedOp = builder.clone(*op, map); 123 // Only replace uses within the launch op. 124 for (auto pair : llvm::zip(op->getResults(), clonedOp->getResults())) 125 replaceAllUsesInRegionWith(std::get<0>(pair), std::get<1>(pair), 126 launchOp.body()); 127 } 128 return success(); 129 } 130 131 /// Outline the `gpu.launch` operation body into a kernel function. Replace 132 /// `gpu.terminator` operations by `gpu.return` in the generated function. 133 static gpu::GPUFuncOp outlineKernelFuncImpl(gpu::LaunchOp launchOp, 134 StringRef kernelFnName, 135 llvm::SetVector<Value> &operands) { 136 Location loc = launchOp.getLoc(); 137 // Create a builder with no insertion point, insertion will happen separately 138 // due to symbol table manipulation. 139 OpBuilder builder(launchOp.getContext()); 140 Region &launchOpBody = launchOp.body(); 141 142 // Identify uses from values defined outside of the scope of the launch 143 // operation. 144 getUsedValuesDefinedAbove(launchOpBody, operands); 145 146 // Create the gpu.func operation. 147 SmallVector<Type, 4> kernelOperandTypes; 148 kernelOperandTypes.reserve(operands.size()); 149 for (Value operand : operands) { 150 kernelOperandTypes.push_back(operand.getType()); 151 } 152 FunctionType type = 153 FunctionType::get(kernelOperandTypes, {}, launchOp.getContext()); 154 auto outlinedFunc = builder.create<gpu::GPUFuncOp>(loc, kernelFnName, type); 155 outlinedFunc.setAttr(gpu::GPUDialect::getKernelFuncAttrName(), 156 builder.getUnitAttr()); 157 BlockAndValueMapping map; 158 159 // Map the arguments corresponding to the launch parameters like blockIdx, 160 // threadIdx, etc. 161 Region &outlinedFuncBody = outlinedFunc.body(); 162 injectGpuIndexOperations(loc, outlinedFuncBody, launchOpBody, map); 163 164 // Map arguments from gpu.launch region to the arguments of the gpu.func 165 // operation. 166 Block &entryBlock = outlinedFuncBody.front(); 167 for (auto operand : enumerate(operands)) 168 map.map(operand.value(), entryBlock.getArgument(operand.index())); 169 170 // Clone the region of the gpu.launch operation into the gpu.func operation. 171 // TODO: If cloneInto can be modified such that if a mapping for 172 // a block exists, that block will be used to clone operations into (at the 173 // end of the block), instead of creating a new block, this would be much 174 // cleaner. 175 launchOpBody.cloneInto(&outlinedFuncBody, map); 176 177 // Branch from entry of the gpu.func operation to the block that is cloned 178 // from the entry block of the gpu.launch operation. 179 Block &launchOpEntry = launchOpBody.front(); 180 Block *clonedLaunchOpEntry = map.lookup(&launchOpEntry); 181 builder.setInsertionPointToEnd(&entryBlock); 182 builder.create<BranchOp>(loc, clonedLaunchOpEntry); 183 184 outlinedFunc.walk([](gpu::TerminatorOp op) { 185 OpBuilder replacer(op); 186 replacer.create<gpu::ReturnOp>(op.getLoc()); 187 op.erase(); 188 }); 189 return outlinedFunc; 190 } 191 192 gpu::GPUFuncOp mlir::outlineKernelFunc(gpu::LaunchOp launchOp, 193 StringRef kernelFnName, 194 llvm::SmallVectorImpl<Value> &operands) { 195 DenseSet<Value> inputOperandSet; 196 inputOperandSet.insert(operands.begin(), operands.end()); 197 llvm::SetVector<Value> operandSet(operands.begin(), operands.end()); 198 auto funcOp = outlineKernelFuncImpl(launchOp, kernelFnName, operandSet); 199 for (auto operand : operandSet) { 200 if (!inputOperandSet.count(operand)) 201 operands.push_back(operand); 202 } 203 return funcOp; 204 } 205 206 /// Replace `gpu.launch` operations with an `gpu.launch_func` operation 207 /// launching `kernelFunc`. The kernel func contains the body of the 208 /// `gpu.launch` with constant region arguments inlined. 209 static void convertToLaunchFuncOp(gpu::LaunchOp launchOp, 210 gpu::GPUFuncOp kernelFunc, 211 ValueRange operands) { 212 OpBuilder builder(launchOp); 213 builder.create<gpu::LaunchFuncOp>( 214 launchOp.getLoc(), kernelFunc, launchOp.getGridSizeOperandValues(), 215 launchOp.getBlockSizeOperandValues(), operands); 216 launchOp.erase(); 217 } 218 219 namespace { 220 /// Pass that moves the kernel of each LaunchOp into its separate nested module. 221 /// 222 /// This pass moves the kernel code of each LaunchOp into a function created 223 /// inside a nested module. It also creates an external function of the same 224 /// name in the parent module. 225 /// 226 /// The gpu.modules are intended to be compiled to a cubin blob independently in 227 /// a separate pass. The external functions can then be annotated with the 228 /// symbol of the cubin accessor function. 229 class GpuKernelOutliningPass 230 : public GpuKernelOutliningBase<GpuKernelOutliningPass> { 231 public: 232 void runOnOperation() override { 233 SymbolTable symbolTable(getOperation()); 234 bool modified = false; 235 for (auto func : getOperation().getOps<FuncOp>()) { 236 // Insert just after the function. 237 Block::iterator insertPt(func.getOperation()->getNextNode()); 238 auto funcWalkResult = func.walk([&](gpu::LaunchOp op) { 239 llvm::SetVector<Value> operands; 240 std::string kernelFnName = 241 Twine(op.getParentOfType<FuncOp>().getName(), "_kernel").str(); 242 243 // Pull in instructions that can be sunk 244 if (failed(sinkOperationsIntoLaunchOp(op))) 245 return WalkResult::interrupt(); 246 gpu::GPUFuncOp outlinedFunc = 247 outlineKernelFuncImpl(op, kernelFnName, operands); 248 249 // Create nested module and insert outlinedFunc. The module will 250 // originally get the same name as the function, but may be renamed on 251 // insertion into the parent module. 252 auto kernelModule = createKernelModule(outlinedFunc, symbolTable); 253 symbolTable.insert(kernelModule, insertPt); 254 255 // Potentially changes signature, pulling in constants. 256 convertToLaunchFuncOp(op, outlinedFunc, operands.getArrayRef()); 257 modified = true; 258 return WalkResult::advance(); 259 }); 260 if (funcWalkResult.wasInterrupted()) 261 return signalPassFailure(); 262 } 263 264 // If any new module was inserted in this module, annotate this module as 265 // a container module. 266 if (modified) 267 getOperation().setAttr(gpu::GPUDialect::getContainerModuleAttrName(), 268 UnitAttr::get(&getContext())); 269 } 270 271 private: 272 /// Returns a gpu.module containing kernelFunc and all callees (recursive). 273 gpu::GPUModuleOp createKernelModule(gpu::GPUFuncOp kernelFunc, 274 const SymbolTable &parentSymbolTable) { 275 // TODO: This code cannot use an OpBuilder because it must be inserted into 276 // a SymbolTable by the caller. SymbolTable needs to be refactored to 277 // prevent manual building of Ops with symbols in code using SymbolTables 278 // and then this needs to use the OpBuilder. 279 auto context = getOperation().getContext(); 280 OpBuilder builder(context); 281 OperationState state(kernelFunc.getLoc(), 282 gpu::GPUModuleOp::getOperationName()); 283 gpu::GPUModuleOp::build(builder, state, kernelFunc.getName()); 284 auto kernelModule = cast<gpu::GPUModuleOp>(Operation::create(state)); 285 SymbolTable symbolTable(kernelModule); 286 symbolTable.insert(kernelFunc); 287 288 SmallVector<Operation *, 8> symbolDefWorklist = {kernelFunc}; 289 while (!symbolDefWorklist.empty()) { 290 if (Optional<SymbolTable::UseRange> symbolUses = 291 SymbolTable::getSymbolUses(symbolDefWorklist.pop_back_val())) { 292 for (SymbolTable::SymbolUse symbolUse : *symbolUses) { 293 StringRef symbolName = 294 symbolUse.getSymbolRef().cast<FlatSymbolRefAttr>().getValue(); 295 if (symbolTable.lookup(symbolName)) 296 continue; 297 298 Operation *symbolDefClone = 299 parentSymbolTable.lookup(symbolName)->clone(); 300 symbolDefWorklist.push_back(symbolDefClone); 301 symbolTable.insert(symbolDefClone); 302 } 303 } 304 } 305 306 return kernelModule; 307 } 308 }; 309 310 } // namespace 311 312 std::unique_ptr<OperationPass<ModuleOp>> mlir::createGpuKernelOutliningPass() { 313 return std::make_unique<GpuKernelOutliningPass>(); 314 } 315