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