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*c60b897dSRiver Riddle #include "mlir/AsmParser/AsmParser.h"
15a54f4eaeSMogball #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
16ace01605SRiver Riddle #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
1732fe1a8aSDiego Caballero #include "mlir/Dialect/DLTI/DLTI.h"
1836550692SRiver Riddle #include "mlir/Dialect/Func/IR/FuncOps.h"
19d7ef488bSMogball #include "mlir/Dialect/GPU/IR/GPUDialect.h"
20d7ef488bSMogball #include "mlir/Dialect/GPU/Transforms/Passes.h"
21d7ef488bSMogball #include "mlir/Dialect/GPU/Transforms/Utils.h"
22e2310704SJulian Gross #include "mlir/Dialect/MemRef/IR/MemRef.h"
2360965b46SAlex Zinenko #include "mlir/IR/BlockAndValueMapping.h"
2460965b46SAlex Zinenko #include "mlir/IR/Builders.h"
251f971e23SRiver Riddle #include "mlir/IR/Matchers.h"
26b8cd0c14STres Popp #include "mlir/IR/SymbolTable.h"
27edeff6e6SStephan Herhut #include "mlir/Support/LLVM.h"
28283b5e73SStephan Herhut #include "mlir/Transforms/RegionUtils.h"
2960965b46SAlex Zinenko 
3060965b46SAlex Zinenko using namespace mlir;
3160965b46SAlex Zinenko 
3260965b46SAlex Zinenko template <typename OpTy>
createForAllDimensions(OpBuilder & builder,Location loc,SmallVectorImpl<Value> & values)3360965b46SAlex Zinenko static void createForAllDimensions(OpBuilder &builder, Location loc,
34e62a6956SRiver Riddle                                    SmallVectorImpl<Value> &values) {
35aae51255SMogball   for (auto dim : {gpu::Dimension::x, gpu::Dimension::y, gpu::Dimension::z})
36aae51255SMogball     values.push_back(builder.create<OpTy>(loc, builder.getIndexType(), dim));
3760965b46SAlex Zinenko }
3860965b46SAlex Zinenko 
39edeff6e6SStephan Herhut /// Adds operations generating block/thread ids and grid/block dimensions at the
40edeff6e6SStephan Herhut /// beginning of the `launchFuncOpBody` region. Add mapping from argument in
41edeff6e6SStephan Herhut /// entry block of `launchOpBody`, to the corresponding result value of the
42edeff6e6SStephan Herhut /// added operations.
injectGpuIndexOperations(Location loc,Region & launchFuncOpBody,Region & launchOpBody,BlockAndValueMapping & map)433f44495dSMaheshRavishankar static void injectGpuIndexOperations(Location loc, Region &launchFuncOpBody,
443f44495dSMaheshRavishankar                                      Region &launchOpBody,
453f44495dSMaheshRavishankar                                      BlockAndValueMapping &map) {
466273fa0cSAlex Zinenko   OpBuilder builder(loc->getContext());
473f44495dSMaheshRavishankar   Block &firstBlock = launchOpBody.front();
483f44495dSMaheshRavishankar   builder.setInsertionPointToStart(&launchFuncOpBody.front());
49e62a6956SRiver Riddle   SmallVector<Value, 12> indexOps;
506273fa0cSAlex Zinenko   createForAllDimensions<gpu::BlockIdOp>(builder, loc, indexOps);
516273fa0cSAlex Zinenko   createForAllDimensions<gpu::ThreadIdOp>(builder, loc, indexOps);
526273fa0cSAlex Zinenko   createForAllDimensions<gpu::GridDimOp>(builder, loc, indexOps);
536273fa0cSAlex Zinenko   createForAllDimensions<gpu::BlockDimOp>(builder, loc, indexOps);
5460965b46SAlex Zinenko   // Replace the leading 12 function args with the respective thread/block index
5560965b46SAlex Zinenko   // operations. Iterate backwards since args are erased and indices change.
56e4853be2SMehdi Amini   for (const auto &indexOp : enumerate(indexOps))
573f44495dSMaheshRavishankar     map.map(firstBlock.getArgument(indexOp.index()), indexOp.value());
5860965b46SAlex Zinenko }
5960965b46SAlex Zinenko 
60edeff6e6SStephan Herhut /// Identifies operations that are beneficial to sink into kernels. These
61edeff6e6SStephan Herhut /// operations may not have side-effects, as otherwise sinking (and hence
62edeff6e6SStephan Herhut /// duplicating them) is not legal.
isLikelyAnIndexComputation(Operation * op)63d271fc04SIvan Butygin static bool isLikelyAnIndexComputation(Operation *op) {
641f971e23SRiver Riddle   return matchPattern(op, m_Constant()) ||
651f971e23SRiver Riddle          isa<memref::DimOp, arith::SelectOp, arith::CmpIOp>(op);
66edeff6e6SStephan Herhut }
67edeff6e6SStephan Herhut 
68edeff6e6SStephan Herhut /// For a given operation `op`, computes whether it is beneficial to sink the
69edeff6e6SStephan Herhut /// operation into the kernel. An operation can be sunk if doing so does not
70edeff6e6SStephan Herhut /// introduce new kernel arguments. Whether a value is already available in the
71edeff6e6SStephan Herhut /// kernel (and hence does not introduce new arguments) is checked by
72366d8435SStephan Herhut /// querying `existingDependencies` and `availableValues`.
73edeff6e6SStephan Herhut /// If an operand is not yet available, we recursively check whether it can be
74edeff6e6SStephan Herhut /// made available by siking its defining op.
75edeff6e6SStephan Herhut /// Operations that are indentified for sinking are added to `beneficiaryOps` in
76366d8435SStephan Herhut /// the order they should appear in the kernel. Furthermore, `availableValues`
77366d8435SStephan Herhut /// is updated with results that will be available after sinking the identified
78edeff6e6SStephan Herhut /// ops.
extractBeneficiaryOps(Operation * op,const SetVector<Value> & existingDependencies,SetVector<Operation * > & beneficiaryOps,llvm::SmallPtrSetImpl<Value> & availableValues,llvm::function_ref<bool (Operation *)> isSinkingBeneficiary)79a2e2fbbaSIvan Butygin static bool extractBeneficiaryOps(
80a2e2fbbaSIvan Butygin     Operation *op, const SetVector<Value> &existingDependencies,
814efb7754SRiver Riddle     SetVector<Operation *> &beneficiaryOps,
82a2e2fbbaSIvan Butygin     llvm::SmallPtrSetImpl<Value> &availableValues,
83a2e2fbbaSIvan Butygin     llvm::function_ref<bool(Operation *)> isSinkingBeneficiary) {
84edeff6e6SStephan Herhut   if (beneficiaryOps.count(op))
85edeff6e6SStephan Herhut     return true;
86edeff6e6SStephan Herhut 
87edeff6e6SStephan Herhut   if (!isSinkingBeneficiary(op))
88edeff6e6SStephan Herhut     return false;
89edeff6e6SStephan Herhut 
90edeff6e6SStephan Herhut   for (Value operand : op->getOperands()) {
9141b09f4eSKazuaki Ishizaki     // It is already visible in the kernel, keep going.
92edeff6e6SStephan Herhut     if (availableValues.count(operand))
93edeff6e6SStephan Herhut       continue;
94366d8435SStephan Herhut     // Else check whether it can be made available via sinking or already is a
95366d8435SStephan Herhut     // dependency.
96edeff6e6SStephan Herhut     Operation *definingOp = operand.getDefiningOp();
97a2e2fbbaSIvan Butygin     if ((!definingOp || !extractBeneficiaryOps(definingOp, existingDependencies,
98a2e2fbbaSIvan Butygin                                                beneficiaryOps, availableValues,
99a2e2fbbaSIvan Butygin                                                isSinkingBeneficiary)) &&
100366d8435SStephan Herhut         !existingDependencies.count(operand))
101edeff6e6SStephan Herhut       return false;
102edeff6e6SStephan Herhut   }
103edeff6e6SStephan Herhut   // We will sink the operation, mark its results as now available.
104edeff6e6SStephan Herhut   beneficiaryOps.insert(op);
105edeff6e6SStephan Herhut   for (Value result : op->getResults())
106edeff6e6SStephan Herhut     availableValues.insert(result);
107edeff6e6SStephan Herhut   return true;
108abb62668SStephan Herhut }
109abb62668SStephan Herhut 
sinkOperationsIntoLaunchOp(gpu::LaunchOp launchOp,llvm::function_ref<bool (Operation *)> isSinkingBeneficiary)110a2e2fbbaSIvan Butygin LogicalResult mlir::sinkOperationsIntoLaunchOp(
111a2e2fbbaSIvan Butygin     gpu::LaunchOp launchOp,
112a2e2fbbaSIvan Butygin     llvm::function_ref<bool(Operation *)> isSinkingBeneficiary) {
113a2e2fbbaSIvan Butygin   assert(isSinkingBeneficiary);
1143f44495dSMaheshRavishankar   Region &launchOpBody = launchOp.body();
115318ff019SStephan Herhut 
1163f44495dSMaheshRavishankar   // Identify uses from values defined outside of the scope of the launch
1173f44495dSMaheshRavishankar   // operation.
1184efb7754SRiver Riddle   SetVector<Value> sinkCandidates;
1193f44495dSMaheshRavishankar   getUsedValuesDefinedAbove(launchOpBody, sinkCandidates);
1203f44495dSMaheshRavishankar 
1214efb7754SRiver Riddle   SetVector<Operation *> toBeSunk;
122366d8435SStephan Herhut   llvm::SmallPtrSet<Value, 4> availableValues;
123366d8435SStephan Herhut   for (Value operand : sinkCandidates) {
1243f44495dSMaheshRavishankar     Operation *operandOp = operand.getDefiningOp();
125edeff6e6SStephan Herhut     if (!operandOp)
1263f44495dSMaheshRavishankar       continue;
127a2e2fbbaSIvan Butygin     extractBeneficiaryOps(operandOp, sinkCandidates, toBeSunk, availableValues,
128a2e2fbbaSIvan Butygin                           isSinkingBeneficiary);
129dfd06af5SStephan Herhut   }
1303f44495dSMaheshRavishankar 
1313f44495dSMaheshRavishankar   // Insert operations so that the defs get cloned before uses.
1323f44495dSMaheshRavishankar   BlockAndValueMapping map;
1333f44495dSMaheshRavishankar   OpBuilder builder(launchOpBody);
134edeff6e6SStephan Herhut   for (Operation *op : toBeSunk) {
135edeff6e6SStephan Herhut     Operation *clonedOp = builder.clone(*op, map);
1363f44495dSMaheshRavishankar     // Only replace uses within the launch op.
137edeff6e6SStephan Herhut     for (auto pair : llvm::zip(op->getResults(), clonedOp->getResults()))
138edeff6e6SStephan Herhut       replaceAllUsesInRegionWith(std::get<0>(pair), std::get<1>(pair),
139edeff6e6SStephan Herhut                                  launchOp.body());
1403f44495dSMaheshRavishankar   }
1413f44495dSMaheshRavishankar   return success();
142dfd06af5SStephan Herhut }
143dfd06af5SStephan Herhut 
144edeff6e6SStephan Herhut /// Outline the `gpu.launch` operation body into a kernel function. Replace
145edeff6e6SStephan Herhut /// `gpu.terminator` operations by `gpu.return` in the generated function.
outlineKernelFuncImpl(gpu::LaunchOp launchOp,StringRef kernelFnName,SetVector<Value> & operands)1463f44495dSMaheshRavishankar static gpu::GPUFuncOp outlineKernelFuncImpl(gpu::LaunchOp launchOp,
1473f44495dSMaheshRavishankar                                             StringRef kernelFnName,
1484efb7754SRiver Riddle                                             SetVector<Value> &operands) {
14960965b46SAlex Zinenko   Location loc = launchOp.getLoc();
1506273fa0cSAlex Zinenko   // Create a builder with no insertion point, insertion will happen separately
1516273fa0cSAlex Zinenko   // due to symbol table manipulation.
1526273fa0cSAlex Zinenko   OpBuilder builder(launchOp.getContext());
1533f44495dSMaheshRavishankar   Region &launchOpBody = launchOp.body();
1546273fa0cSAlex Zinenko 
155283b5e73SStephan Herhut   // Identify uses from values defined outside of the scope of the launch
156283b5e73SStephan Herhut   // operation.
1573f44495dSMaheshRavishankar   getUsedValuesDefinedAbove(launchOpBody, operands);
158283b5e73SStephan Herhut 
1593f44495dSMaheshRavishankar   // Create the gpu.func operation.
160283b5e73SStephan Herhut   SmallVector<Type, 4> kernelOperandTypes;
161283b5e73SStephan Herhut   kernelOperandTypes.reserve(operands.size());
162283b5e73SStephan Herhut   for (Value operand : operands) {
163283b5e73SStephan Herhut     kernelOperandTypes.push_back(operand.getType());
164283b5e73SStephan Herhut   }
16560965b46SAlex Zinenko   FunctionType type =
1661b97cdf8SRiver Riddle       FunctionType::get(launchOp.getContext(), kernelOperandTypes, {});
1673f44495dSMaheshRavishankar   auto outlinedFunc = builder.create<gpu::GPUFuncOp>(loc, kernelFnName, type);
1681ffc1aaaSChristian Sigg   outlinedFunc->setAttr(gpu::GPUDialect::getKernelFuncAttrName(),
16960965b46SAlex Zinenko                         builder.getUnitAttr());
1703f44495dSMaheshRavishankar   BlockAndValueMapping map;
1713f44495dSMaheshRavishankar 
1723f44495dSMaheshRavishankar   // Map the arguments corresponding to the launch parameters like blockIdx,
1733f44495dSMaheshRavishankar   // threadIdx, etc.
1743f44495dSMaheshRavishankar   Region &outlinedFuncBody = outlinedFunc.body();
1753f44495dSMaheshRavishankar   injectGpuIndexOperations(loc, outlinedFuncBody, launchOpBody, map);
1763f44495dSMaheshRavishankar 
1773f44495dSMaheshRavishankar   // Map arguments from gpu.launch region to the arguments of the gpu.func
1783f44495dSMaheshRavishankar   // operation.
1793f44495dSMaheshRavishankar   Block &entryBlock = outlinedFuncBody.front();
180e4853be2SMehdi Amini   for (const auto &operand : enumerate(operands))
1813f44495dSMaheshRavishankar     map.map(operand.value(), entryBlock.getArgument(operand.index()));
1823f44495dSMaheshRavishankar 
1833f44495dSMaheshRavishankar   // Clone the region of the gpu.launch operation into the gpu.func operation.
1849db53a18SRiver Riddle   // TODO: If cloneInto can be modified such that if a mapping for
1853f44495dSMaheshRavishankar   // a block exists, that block will be used to clone operations into (at the
1863f44495dSMaheshRavishankar   // end of the block), instead of creating a new block, this would be much
1873f44495dSMaheshRavishankar   // cleaner.
1883f44495dSMaheshRavishankar   launchOpBody.cloneInto(&outlinedFuncBody, map);
1893f44495dSMaheshRavishankar 
1905aacce3dSKazuaki Ishizaki   // Branch from entry of the gpu.func operation to the block that is cloned
1915aacce3dSKazuaki Ishizaki   // from the entry block of the gpu.launch operation.
1923f44495dSMaheshRavishankar   Block &launchOpEntry = launchOpBody.front();
1933f44495dSMaheshRavishankar   Block *clonedLaunchOpEntry = map.lookup(&launchOpEntry);
1943f44495dSMaheshRavishankar   builder.setInsertionPointToEnd(&entryBlock);
195ace01605SRiver Riddle   builder.create<cf::BranchOp>(loc, clonedLaunchOpEntry);
1963f44495dSMaheshRavishankar 
19726927518SStephan Herhut   outlinedFunc.walk([](gpu::TerminatorOp op) {
19826927518SStephan Herhut     OpBuilder replacer(op);
19926927518SStephan Herhut     replacer.create<gpu::ReturnOp>(op.getLoc());
20026927518SStephan Herhut     op.erase();
20126927518SStephan Herhut   });
20260965b46SAlex Zinenko   return outlinedFunc;
20360965b46SAlex Zinenko }
20460965b46SAlex Zinenko 
outlineKernelFunc(gpu::LaunchOp launchOp,StringRef kernelFnName,llvm::SmallVectorImpl<Value> & operands)2053f44495dSMaheshRavishankar gpu::GPUFuncOp mlir::outlineKernelFunc(gpu::LaunchOp launchOp,
2063f44495dSMaheshRavishankar                                        StringRef kernelFnName,
2073f44495dSMaheshRavishankar                                        llvm::SmallVectorImpl<Value> &operands) {
2083f44495dSMaheshRavishankar   DenseSet<Value> inputOperandSet;
2093f44495dSMaheshRavishankar   inputOperandSet.insert(operands.begin(), operands.end());
2104efb7754SRiver Riddle   SetVector<Value> operandSet(operands.begin(), operands.end());
2113f44495dSMaheshRavishankar   auto funcOp = outlineKernelFuncImpl(launchOp, kernelFnName, operandSet);
2123f44495dSMaheshRavishankar   for (auto operand : operandSet) {
2133f44495dSMaheshRavishankar     if (!inputOperandSet.count(operand))
2143f44495dSMaheshRavishankar       operands.push_back(operand);
2153f44495dSMaheshRavishankar   }
2163f44495dSMaheshRavishankar   return funcOp;
2173f44495dSMaheshRavishankar }
2183f44495dSMaheshRavishankar 
219edeff6e6SStephan Herhut /// Replace `gpu.launch` operations with an `gpu.launch_func` operation
220edeff6e6SStephan Herhut /// launching `kernelFunc`. The kernel func contains the body of the
221edeff6e6SStephan Herhut /// `gpu.launch` with constant region arguments inlined.
convertToLaunchFuncOp(gpu::LaunchOp launchOp,gpu::GPUFuncOp kernelFunc,ValueRange operands)2223f44495dSMaheshRavishankar static void convertToLaunchFuncOp(gpu::LaunchOp launchOp,
223283b5e73SStephan Herhut                                   gpu::GPUFuncOp kernelFunc,
224283b5e73SStephan Herhut                                   ValueRange operands) {
22560965b46SAlex Zinenko   OpBuilder builder(launchOp);
22608b63db8SUday Bondhugula   // The launch op has an optional dynamic shared memory size. If it doesn't
22708b63db8SUday Bondhugula   // exist, we use zero.
228f47a38f5SUday Bondhugula   Value asyncToken = launchOp.asyncToken();
229f47a38f5SUday Bondhugula   auto launchFunc = builder.create<gpu::LaunchFuncOp>(
23060965b46SAlex Zinenko       launchOp.getLoc(), kernelFunc, launchOp.getGridSizeOperandValues(),
23108b63db8SUday Bondhugula       launchOp.getBlockSizeOperandValues(), launchOp.dynamicSharedMemorySize(),
232f47a38f5SUday Bondhugula       operands, asyncToken ? asyncToken.getType() : nullptr,
233f47a38f5SUday Bondhugula       launchOp.asyncDependencies());
234f47a38f5SUday Bondhugula   launchOp.replaceAllUsesWith(launchFunc);
23560965b46SAlex Zinenko   launchOp.erase();
23660965b46SAlex Zinenko }
23760965b46SAlex Zinenko 
23860965b46SAlex Zinenko namespace {
239d271fc04SIvan Butygin /// Pass that moves ops which are likely an index computation into gpu.launch
240d271fc04SIvan Butygin /// body.
241d271fc04SIvan Butygin class GpuLaunchSinkIndexComputationsPass
242d271fc04SIvan Butygin     : public GpuLaunchSinkIndexComputationsBase<
243d271fc04SIvan Butygin           GpuLaunchSinkIndexComputationsPass> {
244d271fc04SIvan Butygin public:
runOnOperation()245d271fc04SIvan Butygin   void runOnOperation() override {
246d271fc04SIvan Butygin     Operation *op = getOperation();
247d271fc04SIvan Butygin     if (op->walk([](gpu::LaunchOp launch) {
248d271fc04SIvan Butygin             // Pull in instructions that can be sunk
249d271fc04SIvan Butygin             if (failed(sinkOperationsIntoLaunchOp(launch,
250d271fc04SIvan Butygin                                                   isLikelyAnIndexComputation)))
251d271fc04SIvan Butygin               return WalkResult::interrupt();
252d271fc04SIvan Butygin 
253d271fc04SIvan Butygin             return WalkResult::advance();
254d271fc04SIvan Butygin           }).wasInterrupted())
255d271fc04SIvan Butygin       signalPassFailure();
256d271fc04SIvan Butygin   }
257d271fc04SIvan Butygin };
258d271fc04SIvan Butygin 
259b8676da1SChristian Sigg /// Pass that moves the kernel of each LaunchOp into its separate nested module.
260b8676da1SChristian Sigg ///
261b8676da1SChristian Sigg /// This pass moves the kernel code of each LaunchOp into a function created
262b8676da1SChristian Sigg /// inside a nested module. It also creates an external function of the same
263b8676da1SChristian Sigg /// name in the parent module.
264b8676da1SChristian Sigg ///
2659a52ea5cSTres Popp /// The gpu.modules are intended to be compiled to a cubin blob independently in
2669a52ea5cSTres Popp /// a separate pass. The external functions can then be annotated with the
267b8676da1SChristian Sigg /// symbol of the cubin accessor function.
268722f909fSRiver Riddle class GpuKernelOutliningPass
2691834ad4aSRiver Riddle     : public GpuKernelOutliningBase<GpuKernelOutliningPass> {
27060965b46SAlex Zinenko public:
GpuKernelOutliningPass(StringRef dlStr)27132fe1a8aSDiego Caballero   GpuKernelOutliningPass(StringRef dlStr) {
27232fe1a8aSDiego Caballero     if (!dlStr.empty() && !dataLayoutStr.hasValue())
27332fe1a8aSDiego Caballero       dataLayoutStr = dlStr.str();
27432fe1a8aSDiego Caballero   }
27532fe1a8aSDiego Caballero 
GpuKernelOutliningPass(const GpuKernelOutliningPass & other)27632fe1a8aSDiego Caballero   GpuKernelOutliningPass(const GpuKernelOutliningPass &other)
27770c463efSDaniil Dudkin       : GpuKernelOutliningBase(other), dataLayoutSpec(other.dataLayoutSpec) {
27870c463efSDaniil Dudkin     dataLayoutStr = other.dataLayoutStr.getValue();
27932fe1a8aSDiego Caballero   }
28032fe1a8aSDiego Caballero 
initialize(MLIRContext * context)28132fe1a8aSDiego Caballero   LogicalResult initialize(MLIRContext *context) override {
28232fe1a8aSDiego Caballero     // Initialize the data layout specification from the data layout string.
28332fe1a8aSDiego Caballero     if (!dataLayoutStr.empty()) {
28432fe1a8aSDiego Caballero       Attribute resultAttr = mlir::parseAttribute(dataLayoutStr, context);
28532fe1a8aSDiego Caballero       if (!resultAttr)
28632fe1a8aSDiego Caballero         return failure();
28732fe1a8aSDiego Caballero 
28832fe1a8aSDiego Caballero       dataLayoutSpec = resultAttr.dyn_cast<DataLayoutSpecInterface>();
28932fe1a8aSDiego Caballero       if (!dataLayoutSpec)
29032fe1a8aSDiego Caballero         return failure();
29132fe1a8aSDiego Caballero     }
29232fe1a8aSDiego Caballero 
29332fe1a8aSDiego Caballero     return success();
29432fe1a8aSDiego Caballero   }
29532fe1a8aSDiego Caballero 
runOnOperation()296722f909fSRiver Riddle   void runOnOperation() override {
297722f909fSRiver Riddle     SymbolTable symbolTable(getOperation());
29890d65d32SAlex Zinenko     bool modified = false;
29958ceae95SRiver Riddle     for (auto func : getOperation().getOps<func::FuncOp>()) {
300b8676da1SChristian Sigg       // Insert just after the function.
301c4a04059SChristian Sigg       Block::iterator insertPt(func->getNextNode());
3023f44495dSMaheshRavishankar       auto funcWalkResult = func.walk([&](gpu::LaunchOp op) {
3034efb7754SRiver Riddle         SetVector<Value> operands;
3043f44495dSMaheshRavishankar         std::string kernelFnName =
30558ceae95SRiver Riddle             Twine(op->getParentOfType<func::FuncOp>().getName(), "_kernel")
30658ceae95SRiver Riddle                 .str();
3073f44495dSMaheshRavishankar 
3083f44495dSMaheshRavishankar         gpu::GPUFuncOp outlinedFunc =
3093f44495dSMaheshRavishankar             outlineKernelFuncImpl(op, kernelFnName, operands);
310b8676da1SChristian Sigg 
31190d65d32SAlex Zinenko         // Create nested module and insert outlinedFunc. The module will
31290d65d32SAlex Zinenko         // originally get the same name as the function, but may be renamed on
31390d65d32SAlex Zinenko         // insertion into the parent module.
314b8cd0c14STres Popp         auto kernelModule = createKernelModule(outlinedFunc, symbolTable);
315b8cd0c14STres Popp         symbolTable.insert(kernelModule, insertPt);
316b8676da1SChristian Sigg 
317b8676da1SChristian Sigg         // Potentially changes signature, pulling in constants.
318283b5e73SStephan Herhut         convertToLaunchFuncOp(op, outlinedFunc, operands.getArrayRef());
31990d65d32SAlex Zinenko         modified = true;
3203f44495dSMaheshRavishankar         return WalkResult::advance();
32160965b46SAlex Zinenko       });
3223f44495dSMaheshRavishankar       if (funcWalkResult.wasInterrupted())
3233f44495dSMaheshRavishankar         return signalPassFailure();
32460965b46SAlex Zinenko     }
32590d65d32SAlex Zinenko 
32690d65d32SAlex Zinenko     // If any new module was inserted in this module, annotate this module as
32790d65d32SAlex Zinenko     // a container module.
32890d65d32SAlex Zinenko     if (modified)
3291ffc1aaaSChristian Sigg       getOperation()->setAttr(gpu::GPUDialect::getContainerModuleAttrName(),
33090d65d32SAlex Zinenko                               UnitAttr::get(&getContext()));
33160965b46SAlex Zinenko   }
33274cdbf59SChristian Sigg 
33374cdbf59SChristian Sigg private:
334edeff6e6SStephan Herhut   /// Returns a gpu.module containing kernelFunc and all callees (recursive).
createKernelModule(gpu::GPUFuncOp kernelFunc,const SymbolTable & parentSymbolTable)3359a52ea5cSTres Popp   gpu::GPUModuleOp createKernelModule(gpu::GPUFuncOp kernelFunc,
336b8cd0c14STres Popp                                       const SymbolTable &parentSymbolTable) {
3379a52ea5cSTres Popp     // TODO: This code cannot use an OpBuilder because it must be inserted into
3389a52ea5cSTres Popp     // a SymbolTable by the caller. SymbolTable needs to be refactored to
3399a52ea5cSTres Popp     // prevent manual building of Ops with symbols in code using SymbolTables
3409a52ea5cSTres Popp     // and then this needs to use the OpBuilder.
34102b6fb21SMehdi Amini     auto *context = getOperation().getContext();
342bb1d976fSAlex Zinenko     OpBuilder builder(context);
343e1364f10SMehdi Amini     auto kernelModule = builder.create<gpu::GPUModuleOp>(kernelFunc.getLoc(),
344e1364f10SMehdi Amini                                                          kernelFunc.getName());
34532fe1a8aSDiego Caballero 
34632fe1a8aSDiego Caballero     // If a valid data layout spec was provided, attach it to the kernel module.
34732fe1a8aSDiego Caballero     // Otherwise, the default data layout will be used.
34832fe1a8aSDiego Caballero     if (dataLayoutSpec)
349e2b658cdSDiego Caballero       kernelModule->setAttr(DLTIDialect::kDataLayoutAttrName, dataLayoutSpec);
35032fe1a8aSDiego Caballero 
351b8cd0c14STres Popp     SymbolTable symbolTable(kernelModule);
352b8cd0c14STres Popp     symbolTable.insert(kernelFunc);
35374cdbf59SChristian Sigg 
3544562e389SRiver Riddle     SmallVector<Operation *, 8> symbolDefWorklist = {kernelFunc};
3559fbf52e3SMLIR Team     while (!symbolDefWorklist.empty()) {
3569fbf52e3SMLIR Team       if (Optional<SymbolTable::UseRange> symbolUses =
3579fbf52e3SMLIR Team               SymbolTable::getSymbolUses(symbolDefWorklist.pop_back_val())) {
3589fbf52e3SMLIR Team         for (SymbolTable::SymbolUse symbolUse : *symbolUses) {
3599b9c647cSRiver Riddle           StringRef symbolName =
3609b9c647cSRiver Riddle               symbolUse.getSymbolRef().cast<FlatSymbolRefAttr>().getValue();
361b8cd0c14STres Popp           if (symbolTable.lookup(symbolName))
3629fbf52e3SMLIR Team             continue;
36374cdbf59SChristian Sigg 
3649fbf52e3SMLIR Team           Operation *symbolDefClone =
365b8cd0c14STres Popp               parentSymbolTable.lookup(symbolName)->clone();
3669fbf52e3SMLIR Team           symbolDefWorklist.push_back(symbolDefClone);
367b8cd0c14STres Popp           symbolTable.insert(symbolDefClone);
3689fbf52e3SMLIR Team         }
3699fbf52e3SMLIR Team       }
37074cdbf59SChristian Sigg     }
37174cdbf59SChristian Sigg 
37274cdbf59SChristian Sigg     return kernelModule;
37374cdbf59SChristian Sigg   }
37432fe1a8aSDiego Caballero 
37532fe1a8aSDiego Caballero   Option<std::string> dataLayoutStr{
37632fe1a8aSDiego Caballero       *this, "data-layout-str",
37732fe1a8aSDiego Caballero       llvm::cl::desc("String containing the data layout specification to be "
37832fe1a8aSDiego Caballero                      "attached to the GPU kernel module")};
37932fe1a8aSDiego Caballero 
38032fe1a8aSDiego Caballero   DataLayoutSpecInterface dataLayoutSpec;
38160965b46SAlex Zinenko };
38260965b46SAlex Zinenko 
38360965b46SAlex Zinenko } // namespace
38460965b46SAlex Zinenko 
createGpuLauchSinkIndexComputationsPass()385d271fc04SIvan Butygin std::unique_ptr<Pass> mlir::createGpuLauchSinkIndexComputationsPass() {
386d271fc04SIvan Butygin   return std::make_unique<GpuLaunchSinkIndexComputationsPass>();
387d271fc04SIvan Butygin }
388d271fc04SIvan Butygin 
38932fe1a8aSDiego Caballero std::unique_ptr<OperationPass<ModuleOp>>
createGpuKernelOutliningPass(StringRef dataLayoutStr)39032fe1a8aSDiego Caballero mlir::createGpuKernelOutliningPass(StringRef dataLayoutStr) {
39132fe1a8aSDiego Caballero   return std::make_unique<GpuKernelOutliningPass>(dataLayoutStr);
39260965b46SAlex Zinenko }
393