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" 14a54f4eaeSMogball #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" 15ace01605SRiver Riddle #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" 1632fe1a8aSDiego Caballero #include "mlir/Dialect/DLTI/DLTI.h" 1760965b46SAlex Zinenko #include "mlir/Dialect/GPU/GPUDialect.h" 1860965b46SAlex Zinenko #include "mlir/Dialect/GPU/Passes.h" 193f44495dSMaheshRavishankar #include "mlir/Dialect/GPU/Utils.h" 20e2310704SJulian Gross #include "mlir/Dialect/MemRef/IR/MemRef.h" 2169d757c0SRob Suderman #include "mlir/Dialect/StandardOps/IR/Ops.h" 2260965b46SAlex Zinenko #include "mlir/IR/BlockAndValueMapping.h" 2360965b46SAlex Zinenko #include "mlir/IR/Builders.h" 24b8cd0c14STres Popp #include "mlir/IR/SymbolTable.h" 2532fe1a8aSDiego Caballero #include "mlir/Parser.h" 26edeff6e6SStephan Herhut #include "mlir/Support/LLVM.h" 27283b5e73SStephan Herhut #include "mlir/Transforms/RegionUtils.h" 2860965b46SAlex Zinenko 2960965b46SAlex Zinenko using namespace mlir; 3060965b46SAlex Zinenko 3160965b46SAlex Zinenko template <typename OpTy> 3260965b46SAlex Zinenko static void createForAllDimensions(OpBuilder &builder, Location loc, 33e62a6956SRiver Riddle SmallVectorImpl<Value> &values) { 34aae51255SMogball for (auto dim : {gpu::Dimension::x, gpu::Dimension::y, gpu::Dimension::z}) 35aae51255SMogball values.push_back(builder.create<OpTy>(loc, builder.getIndexType(), dim)); 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. 55e4853be2SMehdi Amini for (const 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. 62*a2e2fbbaSIvan Butygin static bool isLikelyAnIndexComputatio(Operation *op) { 63dec8af70SRiver Riddle return isa<arith::ConstantOp, ConstantOp, memref::DimOp, arith::SelectOp, 64a54f4eaeSMogball 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. 78*a2e2fbbaSIvan Butygin static bool extractBeneficiaryOps( 79*a2e2fbbaSIvan Butygin Operation *op, const SetVector<Value> &existingDependencies, 804efb7754SRiver Riddle SetVector<Operation *> &beneficiaryOps, 81*a2e2fbbaSIvan Butygin llvm::SmallPtrSetImpl<Value> &availableValues, 82*a2e2fbbaSIvan Butygin llvm::function_ref<bool(Operation *)> isSinkingBeneficiary) { 83edeff6e6SStephan Herhut if (beneficiaryOps.count(op)) 84edeff6e6SStephan Herhut return true; 85edeff6e6SStephan Herhut 86edeff6e6SStephan Herhut if (!isSinkingBeneficiary(op)) 87edeff6e6SStephan Herhut return false; 88edeff6e6SStephan Herhut 89edeff6e6SStephan Herhut for (Value operand : op->getOperands()) { 9041b09f4eSKazuaki Ishizaki // It is already visible in the kernel, keep going. 91edeff6e6SStephan Herhut if (availableValues.count(operand)) 92edeff6e6SStephan Herhut continue; 93366d8435SStephan Herhut // Else check whether it can be made available via sinking or already is a 94366d8435SStephan Herhut // dependency. 95edeff6e6SStephan Herhut Operation *definingOp = operand.getDefiningOp(); 96*a2e2fbbaSIvan Butygin if ((!definingOp || !extractBeneficiaryOps(definingOp, existingDependencies, 97*a2e2fbbaSIvan Butygin beneficiaryOps, availableValues, 98*a2e2fbbaSIvan Butygin isSinkingBeneficiary)) && 99366d8435SStephan Herhut !existingDependencies.count(operand)) 100edeff6e6SStephan Herhut return false; 101edeff6e6SStephan Herhut } 102edeff6e6SStephan Herhut // We will sink the operation, mark its results as now available. 103edeff6e6SStephan Herhut beneficiaryOps.insert(op); 104edeff6e6SStephan Herhut for (Value result : op->getResults()) 105edeff6e6SStephan Herhut availableValues.insert(result); 106edeff6e6SStephan Herhut return true; 107abb62668SStephan Herhut } 108abb62668SStephan Herhut 109*a2e2fbbaSIvan Butygin LogicalResult mlir::sinkOperationsIntoLaunchOp( 110*a2e2fbbaSIvan Butygin gpu::LaunchOp launchOp, 111*a2e2fbbaSIvan Butygin llvm::function_ref<bool(Operation *)> isSinkingBeneficiary) { 112*a2e2fbbaSIvan Butygin assert(isSinkingBeneficiary); 1133f44495dSMaheshRavishankar Region &launchOpBody = launchOp.body(); 114318ff019SStephan Herhut 1153f44495dSMaheshRavishankar // Identify uses from values defined outside of the scope of the launch 1163f44495dSMaheshRavishankar // operation. 1174efb7754SRiver Riddle SetVector<Value> sinkCandidates; 1183f44495dSMaheshRavishankar getUsedValuesDefinedAbove(launchOpBody, sinkCandidates); 1193f44495dSMaheshRavishankar 1204efb7754SRiver Riddle SetVector<Operation *> toBeSunk; 121366d8435SStephan Herhut llvm::SmallPtrSet<Value, 4> availableValues; 122366d8435SStephan Herhut for (Value operand : sinkCandidates) { 1233f44495dSMaheshRavishankar Operation *operandOp = operand.getDefiningOp(); 124edeff6e6SStephan Herhut if (!operandOp) 1253f44495dSMaheshRavishankar continue; 126*a2e2fbbaSIvan Butygin extractBeneficiaryOps(operandOp, sinkCandidates, toBeSunk, availableValues, 127*a2e2fbbaSIvan Butygin isSinkingBeneficiary); 128dfd06af5SStephan Herhut } 1293f44495dSMaheshRavishankar 1303f44495dSMaheshRavishankar // Insert operations so that the defs get cloned before uses. 1313f44495dSMaheshRavishankar BlockAndValueMapping map; 1323f44495dSMaheshRavishankar OpBuilder builder(launchOpBody); 133edeff6e6SStephan Herhut for (Operation *op : toBeSunk) { 134edeff6e6SStephan Herhut Operation *clonedOp = builder.clone(*op, map); 1353f44495dSMaheshRavishankar // Only replace uses within the launch op. 136edeff6e6SStephan Herhut for (auto pair : llvm::zip(op->getResults(), clonedOp->getResults())) 137edeff6e6SStephan Herhut replaceAllUsesInRegionWith(std::get<0>(pair), std::get<1>(pair), 138edeff6e6SStephan Herhut launchOp.body()); 1393f44495dSMaheshRavishankar } 1403f44495dSMaheshRavishankar return success(); 141dfd06af5SStephan Herhut } 142dfd06af5SStephan Herhut 143edeff6e6SStephan Herhut /// Outline the `gpu.launch` operation body into a kernel function. Replace 144edeff6e6SStephan Herhut /// `gpu.terminator` operations by `gpu.return` in the generated function. 1453f44495dSMaheshRavishankar static gpu::GPUFuncOp outlineKernelFuncImpl(gpu::LaunchOp launchOp, 1463f44495dSMaheshRavishankar StringRef kernelFnName, 1474efb7754SRiver Riddle SetVector<Value> &operands) { 14860965b46SAlex Zinenko Location loc = launchOp.getLoc(); 1496273fa0cSAlex Zinenko // Create a builder with no insertion point, insertion will happen separately 1506273fa0cSAlex Zinenko // due to symbol table manipulation. 1516273fa0cSAlex Zinenko OpBuilder builder(launchOp.getContext()); 1523f44495dSMaheshRavishankar Region &launchOpBody = launchOp.body(); 1536273fa0cSAlex Zinenko 154283b5e73SStephan Herhut // Identify uses from values defined outside of the scope of the launch 155283b5e73SStephan Herhut // operation. 1563f44495dSMaheshRavishankar getUsedValuesDefinedAbove(launchOpBody, operands); 157283b5e73SStephan Herhut 1583f44495dSMaheshRavishankar // Create the gpu.func operation. 159283b5e73SStephan Herhut SmallVector<Type, 4> kernelOperandTypes; 160283b5e73SStephan Herhut kernelOperandTypes.reserve(operands.size()); 161283b5e73SStephan Herhut for (Value operand : operands) { 162283b5e73SStephan Herhut kernelOperandTypes.push_back(operand.getType()); 163283b5e73SStephan Herhut } 16460965b46SAlex Zinenko FunctionType type = 1651b97cdf8SRiver Riddle FunctionType::get(launchOp.getContext(), kernelOperandTypes, {}); 1663f44495dSMaheshRavishankar auto outlinedFunc = builder.create<gpu::GPUFuncOp>(loc, kernelFnName, type); 1671ffc1aaaSChristian Sigg outlinedFunc->setAttr(gpu::GPUDialect::getKernelFuncAttrName(), 16860965b46SAlex Zinenko builder.getUnitAttr()); 1693f44495dSMaheshRavishankar BlockAndValueMapping map; 1703f44495dSMaheshRavishankar 1713f44495dSMaheshRavishankar // Map the arguments corresponding to the launch parameters like blockIdx, 1723f44495dSMaheshRavishankar // threadIdx, etc. 1733f44495dSMaheshRavishankar Region &outlinedFuncBody = outlinedFunc.body(); 1743f44495dSMaheshRavishankar injectGpuIndexOperations(loc, outlinedFuncBody, launchOpBody, map); 1753f44495dSMaheshRavishankar 1763f44495dSMaheshRavishankar // Map arguments from gpu.launch region to the arguments of the gpu.func 1773f44495dSMaheshRavishankar // operation. 1783f44495dSMaheshRavishankar Block &entryBlock = outlinedFuncBody.front(); 179e4853be2SMehdi Amini for (const auto &operand : enumerate(operands)) 1803f44495dSMaheshRavishankar map.map(operand.value(), entryBlock.getArgument(operand.index())); 1813f44495dSMaheshRavishankar 1823f44495dSMaheshRavishankar // Clone the region of the gpu.launch operation into the gpu.func operation. 1839db53a18SRiver Riddle // TODO: If cloneInto can be modified such that if a mapping for 1843f44495dSMaheshRavishankar // a block exists, that block will be used to clone operations into (at the 1853f44495dSMaheshRavishankar // end of the block), instead of creating a new block, this would be much 1863f44495dSMaheshRavishankar // cleaner. 1873f44495dSMaheshRavishankar launchOpBody.cloneInto(&outlinedFuncBody, map); 1883f44495dSMaheshRavishankar 1895aacce3dSKazuaki Ishizaki // Branch from entry of the gpu.func operation to the block that is cloned 1905aacce3dSKazuaki Ishizaki // from the entry block of the gpu.launch operation. 1913f44495dSMaheshRavishankar Block &launchOpEntry = launchOpBody.front(); 1923f44495dSMaheshRavishankar Block *clonedLaunchOpEntry = map.lookup(&launchOpEntry); 1933f44495dSMaheshRavishankar builder.setInsertionPointToEnd(&entryBlock); 194ace01605SRiver Riddle builder.create<cf::BranchOp>(loc, clonedLaunchOpEntry); 1953f44495dSMaheshRavishankar 19626927518SStephan Herhut outlinedFunc.walk([](gpu::TerminatorOp op) { 19726927518SStephan Herhut OpBuilder replacer(op); 19826927518SStephan Herhut replacer.create<gpu::ReturnOp>(op.getLoc()); 19926927518SStephan Herhut op.erase(); 20026927518SStephan Herhut }); 20160965b46SAlex Zinenko return outlinedFunc; 20260965b46SAlex Zinenko } 20360965b46SAlex Zinenko 2043f44495dSMaheshRavishankar gpu::GPUFuncOp mlir::outlineKernelFunc(gpu::LaunchOp launchOp, 2053f44495dSMaheshRavishankar StringRef kernelFnName, 2063f44495dSMaheshRavishankar llvm::SmallVectorImpl<Value> &operands) { 2073f44495dSMaheshRavishankar DenseSet<Value> inputOperandSet; 2083f44495dSMaheshRavishankar inputOperandSet.insert(operands.begin(), operands.end()); 2094efb7754SRiver Riddle SetVector<Value> operandSet(operands.begin(), operands.end()); 2103f44495dSMaheshRavishankar auto funcOp = outlineKernelFuncImpl(launchOp, kernelFnName, operandSet); 2113f44495dSMaheshRavishankar for (auto operand : operandSet) { 2123f44495dSMaheshRavishankar if (!inputOperandSet.count(operand)) 2133f44495dSMaheshRavishankar operands.push_back(operand); 2143f44495dSMaheshRavishankar } 2153f44495dSMaheshRavishankar return funcOp; 2163f44495dSMaheshRavishankar } 2173f44495dSMaheshRavishankar 218edeff6e6SStephan Herhut /// Replace `gpu.launch` operations with an `gpu.launch_func` operation 219edeff6e6SStephan Herhut /// launching `kernelFunc`. The kernel func contains the body of the 220edeff6e6SStephan Herhut /// `gpu.launch` with constant region arguments inlined. 2213f44495dSMaheshRavishankar static void convertToLaunchFuncOp(gpu::LaunchOp launchOp, 222283b5e73SStephan Herhut gpu::GPUFuncOp kernelFunc, 223283b5e73SStephan Herhut ValueRange operands) { 22460965b46SAlex Zinenko OpBuilder builder(launchOp); 22508b63db8SUday Bondhugula // The launch op has an optional dynamic shared memory size. If it doesn't 22608b63db8SUday Bondhugula // exist, we use zero. 2273f44495dSMaheshRavishankar builder.create<gpu::LaunchFuncOp>( 22860965b46SAlex Zinenko launchOp.getLoc(), kernelFunc, launchOp.getGridSizeOperandValues(), 22908b63db8SUday Bondhugula launchOp.getBlockSizeOperandValues(), launchOp.dynamicSharedMemorySize(), 23008b63db8SUday Bondhugula operands); 23160965b46SAlex Zinenko launchOp.erase(); 23260965b46SAlex Zinenko } 23360965b46SAlex Zinenko 23460965b46SAlex Zinenko namespace { 235b8676da1SChristian Sigg /// Pass that moves the kernel of each LaunchOp into its separate nested module. 236b8676da1SChristian Sigg /// 237b8676da1SChristian Sigg /// This pass moves the kernel code of each LaunchOp into a function created 238b8676da1SChristian Sigg /// inside a nested module. It also creates an external function of the same 239b8676da1SChristian Sigg /// name in the parent module. 240b8676da1SChristian Sigg /// 2419a52ea5cSTres Popp /// The gpu.modules are intended to be compiled to a cubin blob independently in 2429a52ea5cSTres Popp /// a separate pass. The external functions can then be annotated with the 243b8676da1SChristian Sigg /// symbol of the cubin accessor function. 244722f909fSRiver Riddle class GpuKernelOutliningPass 2451834ad4aSRiver Riddle : public GpuKernelOutliningBase<GpuKernelOutliningPass> { 24660965b46SAlex Zinenko public: 24732fe1a8aSDiego Caballero GpuKernelOutliningPass(StringRef dlStr) { 24832fe1a8aSDiego Caballero if (!dlStr.empty() && !dataLayoutStr.hasValue()) 24932fe1a8aSDiego Caballero dataLayoutStr = dlStr.str(); 25032fe1a8aSDiego Caballero } 25132fe1a8aSDiego Caballero 25232fe1a8aSDiego Caballero GpuKernelOutliningPass(const GpuKernelOutliningPass &other) 25332fe1a8aSDiego Caballero : dataLayoutSpec(other.dataLayoutSpec) { 25432fe1a8aSDiego Caballero dataLayoutStr = other.dataLayoutStr; 25532fe1a8aSDiego Caballero } 25632fe1a8aSDiego Caballero 25732fe1a8aSDiego Caballero LogicalResult initialize(MLIRContext *context) override { 25832fe1a8aSDiego Caballero // Initialize the data layout specification from the data layout string. 25932fe1a8aSDiego Caballero if (!dataLayoutStr.empty()) { 26032fe1a8aSDiego Caballero Attribute resultAttr = mlir::parseAttribute(dataLayoutStr, context); 26132fe1a8aSDiego Caballero if (!resultAttr) 26232fe1a8aSDiego Caballero return failure(); 26332fe1a8aSDiego Caballero 26432fe1a8aSDiego Caballero dataLayoutSpec = resultAttr.dyn_cast<DataLayoutSpecInterface>(); 26532fe1a8aSDiego Caballero if (!dataLayoutSpec) 26632fe1a8aSDiego Caballero return failure(); 26732fe1a8aSDiego Caballero } 26832fe1a8aSDiego Caballero 26932fe1a8aSDiego Caballero return success(); 27032fe1a8aSDiego Caballero } 27132fe1a8aSDiego Caballero 272722f909fSRiver Riddle void runOnOperation() override { 273722f909fSRiver Riddle SymbolTable symbolTable(getOperation()); 27490d65d32SAlex Zinenko bool modified = false; 275722f909fSRiver Riddle for (auto func : getOperation().getOps<FuncOp>()) { 276b8676da1SChristian Sigg // Insert just after the function. 277c4a04059SChristian Sigg Block::iterator insertPt(func->getNextNode()); 2783f44495dSMaheshRavishankar auto funcWalkResult = func.walk([&](gpu::LaunchOp op) { 2794efb7754SRiver Riddle SetVector<Value> operands; 2803f44495dSMaheshRavishankar std::string kernelFnName = 2810bf4a82aSChristian Sigg Twine(op->getParentOfType<FuncOp>().getName(), "_kernel").str(); 2823f44495dSMaheshRavishankar 2833f44495dSMaheshRavishankar // Pull in instructions that can be sunk 284*a2e2fbbaSIvan Butygin if (failed(sinkOperationsIntoLaunchOp(op, isLikelyAnIndexComputatio))) 2853f44495dSMaheshRavishankar return WalkResult::interrupt(); 2863f44495dSMaheshRavishankar gpu::GPUFuncOp outlinedFunc = 2873f44495dSMaheshRavishankar outlineKernelFuncImpl(op, kernelFnName, operands); 288b8676da1SChristian Sigg 28990d65d32SAlex Zinenko // Create nested module and insert outlinedFunc. The module will 29090d65d32SAlex Zinenko // originally get the same name as the function, but may be renamed on 29190d65d32SAlex Zinenko // insertion into the parent module. 292b8cd0c14STres Popp auto kernelModule = createKernelModule(outlinedFunc, symbolTable); 293b8cd0c14STres Popp symbolTable.insert(kernelModule, insertPt); 294b8676da1SChristian Sigg 295b8676da1SChristian Sigg // Potentially changes signature, pulling in constants. 296283b5e73SStephan Herhut convertToLaunchFuncOp(op, outlinedFunc, operands.getArrayRef()); 29790d65d32SAlex Zinenko modified = true; 2983f44495dSMaheshRavishankar return WalkResult::advance(); 29960965b46SAlex Zinenko }); 3003f44495dSMaheshRavishankar if (funcWalkResult.wasInterrupted()) 3013f44495dSMaheshRavishankar return signalPassFailure(); 30260965b46SAlex Zinenko } 30390d65d32SAlex Zinenko 30490d65d32SAlex Zinenko // If any new module was inserted in this module, annotate this module as 30590d65d32SAlex Zinenko // a container module. 30690d65d32SAlex Zinenko if (modified) 3071ffc1aaaSChristian Sigg getOperation()->setAttr(gpu::GPUDialect::getContainerModuleAttrName(), 30890d65d32SAlex Zinenko UnitAttr::get(&getContext())); 30960965b46SAlex Zinenko } 31074cdbf59SChristian Sigg 31174cdbf59SChristian Sigg private: 312edeff6e6SStephan Herhut /// Returns a gpu.module containing kernelFunc and all callees (recursive). 3139a52ea5cSTres Popp gpu::GPUModuleOp createKernelModule(gpu::GPUFuncOp kernelFunc, 314b8cd0c14STres Popp const SymbolTable &parentSymbolTable) { 3159a52ea5cSTres Popp // TODO: This code cannot use an OpBuilder because it must be inserted into 3169a52ea5cSTres Popp // a SymbolTable by the caller. SymbolTable needs to be refactored to 3179a52ea5cSTres Popp // prevent manual building of Ops with symbols in code using SymbolTables 3189a52ea5cSTres Popp // and then this needs to use the OpBuilder. 31902b6fb21SMehdi Amini auto *context = getOperation().getContext(); 320bb1d976fSAlex Zinenko OpBuilder builder(context); 321e1364f10SMehdi Amini auto kernelModule = builder.create<gpu::GPUModuleOp>(kernelFunc.getLoc(), 322e1364f10SMehdi Amini kernelFunc.getName()); 32332fe1a8aSDiego Caballero 32432fe1a8aSDiego Caballero // If a valid data layout spec was provided, attach it to the kernel module. 32532fe1a8aSDiego Caballero // Otherwise, the default data layout will be used. 32632fe1a8aSDiego Caballero if (dataLayoutSpec) 327e2b658cdSDiego Caballero kernelModule->setAttr(DLTIDialect::kDataLayoutAttrName, dataLayoutSpec); 32832fe1a8aSDiego Caballero 329b8cd0c14STres Popp SymbolTable symbolTable(kernelModule); 330b8cd0c14STres Popp symbolTable.insert(kernelFunc); 33174cdbf59SChristian Sigg 3324562e389SRiver Riddle SmallVector<Operation *, 8> symbolDefWorklist = {kernelFunc}; 3339fbf52e3SMLIR Team while (!symbolDefWorklist.empty()) { 3349fbf52e3SMLIR Team if (Optional<SymbolTable::UseRange> symbolUses = 3359fbf52e3SMLIR Team SymbolTable::getSymbolUses(symbolDefWorklist.pop_back_val())) { 3369fbf52e3SMLIR Team for (SymbolTable::SymbolUse symbolUse : *symbolUses) { 3379b9c647cSRiver Riddle StringRef symbolName = 3389b9c647cSRiver Riddle symbolUse.getSymbolRef().cast<FlatSymbolRefAttr>().getValue(); 339b8cd0c14STres Popp if (symbolTable.lookup(symbolName)) 3409fbf52e3SMLIR Team continue; 34174cdbf59SChristian Sigg 3429fbf52e3SMLIR Team Operation *symbolDefClone = 343b8cd0c14STres Popp parentSymbolTable.lookup(symbolName)->clone(); 3449fbf52e3SMLIR Team symbolDefWorklist.push_back(symbolDefClone); 345b8cd0c14STres Popp symbolTable.insert(symbolDefClone); 3469fbf52e3SMLIR Team } 3479fbf52e3SMLIR Team } 34874cdbf59SChristian Sigg } 34974cdbf59SChristian Sigg 35074cdbf59SChristian Sigg return kernelModule; 35174cdbf59SChristian Sigg } 35232fe1a8aSDiego Caballero 35332fe1a8aSDiego Caballero Option<std::string> dataLayoutStr{ 35432fe1a8aSDiego Caballero *this, "data-layout-str", 35532fe1a8aSDiego Caballero llvm::cl::desc("String containing the data layout specification to be " 35632fe1a8aSDiego Caballero "attached to the GPU kernel module")}; 35732fe1a8aSDiego Caballero 35832fe1a8aSDiego Caballero DataLayoutSpecInterface dataLayoutSpec; 35960965b46SAlex Zinenko }; 36060965b46SAlex Zinenko 36160965b46SAlex Zinenko } // namespace 36260965b46SAlex Zinenko 36332fe1a8aSDiego Caballero std::unique_ptr<OperationPass<ModuleOp>> 36432fe1a8aSDiego Caballero mlir::createGpuKernelOutliningPass(StringRef dataLayoutStr) { 36532fe1a8aSDiego Caballero return std::make_unique<GpuKernelOutliningPass>(dataLayoutStr); 36660965b46SAlex Zinenko } 367