#include "PassDetail.h"
#include "mlir/AsmParser/AsmParser.h"
#include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
#include "mlir/Dialect/DLTI/DLTI.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/GPU/IR/GPUDialect.h"
#include "mlir/Dialect/GPU/Transforms/Passes.h"
#include "mlir/Dialect/GPU/Transforms/Utils.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/IR/BlockAndValueMapping.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/SymbolTable.h"
#include "mlir/Support/LLVM.h"
#include "mlir/Transforms/RegionUtils.h"
using namespace mlir;
template <typename OpTy>
static void createForAllDimensions(OpBuilder &builder, Location loc,
SmallVectorImpl<Value> &values) {
for (auto dim : {gpu::Dimension::x, gpu::Dimension::y, gpu::Dimension::z})
values.push_back(builder.create<OpTy>(loc, builder.getIndexType(), dim));
}
static void injectGpuIndexOperations(Location loc, Region &launchFuncOpBody,
Region &launchOpBody,
BlockAndValueMapping &map) {
OpBuilder builder(loc->getContext());
Block &firstBlock = launchOpBody.front();
builder.setInsertionPointToStart(&launchFuncOpBody.front());
SmallVector<Value, 12> indexOps;
createForAllDimensions<gpu::BlockIdOp>(builder, loc, indexOps);
createForAllDimensions<gpu::ThreadIdOp>(builder, loc, indexOps);
createForAllDimensions<gpu::GridDimOp>(builder, loc, indexOps);
createForAllDimensions<gpu::BlockDimOp>(builder, loc, indexOps);
for (const auto &indexOp : enumerate(indexOps))
map.map(firstBlock.getArgument(indexOp.index()), indexOp.value());
}
static bool isLikelyAnIndexComputation(Operation *op) {
return matchPattern(op, m_Constant()) ||
isa<memref::DimOp, arith::SelectOp, arith::CmpIOp>(op);
}
static bool extractBeneficiaryOps(
Operation *op, const SetVector<Value> &existingDependencies,
SetVector<Operation *> &beneficiaryOps,
llvm::SmallPtrSetImpl<Value> &availableValues,
llvm::function_ref<bool(Operation *)> isSinkingBeneficiary) {
if (beneficiaryOps.count(op))
return true;
if (!isSinkingBeneficiary(op))
return false;
for (Value operand : op->getOperands()) {
if (availableValues.count(operand))
continue;
Operation *definingOp = operand.getDefiningOp();
if ((!definingOp || !extractBeneficiaryOps(definingOp, existingDependencies,
beneficiaryOps, availableValues,
isSinkingBeneficiary)) &&
!existingDependencies.count(operand))
return false;
}
beneficiaryOps.insert(op);
for (Value result : op->getResults())
availableValues.insert(result);
return true;
}
LogicalResult mlir::sinkOperationsIntoLaunchOp(
gpu::LaunchOp launchOp,
llvm::function_ref<bool(Operation *)> isSinkingBeneficiary) {
assert(isSinkingBeneficiary);
Region &launchOpBody = launchOp.body();
SetVector<Value> sinkCandidates;
getUsedValuesDefinedAbove(launchOpBody, sinkCandidates);
SetVector<Operation *> toBeSunk;
llvm::SmallPtrSet<Value, 4> availableValues;
for (Value operand : sinkCandidates) {
Operation *operandOp = operand.getDefiningOp();
if (!operandOp)
continue;
extractBeneficiaryOps(operandOp, sinkCandidates, toBeSunk, availableValues,
isSinkingBeneficiary);
}
BlockAndValueMapping map;
OpBuilder builder(launchOpBody);
for (Operation *op : toBeSunk) {
Operation *clonedOp = builder.clone(*op, map);
for (auto pair : llvm::zip(op->getResults(), clonedOp->getResults()))
replaceAllUsesInRegionWith(std::get<0>(pair), std::get<1>(pair),
launchOp.body());
}
return success();
}
static gpu::GPUFuncOp outlineKernelFuncImpl(gpu::LaunchOp launchOp,
StringRef kernelFnName,
SetVector<Value> &operands) {
Location loc = launchOp.getLoc();
OpBuilder builder(launchOp.getContext());
Region &launchOpBody = launchOp.body();
getUsedValuesDefinedAbove(launchOpBody, operands);
SmallVector<Type, 4> kernelOperandTypes;
kernelOperandTypes.reserve(operands.size());
for (Value operand : operands) {
kernelOperandTypes.push_back(operand.getType());
}
FunctionType type =
FunctionType::get(launchOp.getContext(), kernelOperandTypes, {});
auto outlinedFunc = builder.create<gpu::GPUFuncOp>(loc, kernelFnName, type);
outlinedFunc->setAttr(gpu::GPUDialect::getKernelFuncAttrName(),
builder.getUnitAttr());
BlockAndValueMapping map;
Region &outlinedFuncBody = outlinedFunc.body();
injectGpuIndexOperations(loc, outlinedFuncBody, launchOpBody, map);
Block &entryBlock = outlinedFuncBody.front();
for (const auto &operand : enumerate(operands))
map.map(operand.value(), entryBlock.getArgument(operand.index()));
launchOpBody.cloneInto(&outlinedFuncBody, map);
Block &launchOpEntry = launchOpBody.front();
Block *clonedLaunchOpEntry = map.lookup(&launchOpEntry);
builder.setInsertionPointToEnd(&entryBlock);
builder.create<cf::BranchOp>(loc, clonedLaunchOpEntry);
outlinedFunc.walk([](gpu::TerminatorOp op) {
OpBuilder replacer(op);
replacer.create<gpu::ReturnOp>(op.getLoc());
op.erase();
});
return outlinedFunc;
}
gpu::GPUFuncOp mlir::outlineKernelFunc(gpu::LaunchOp launchOp,
StringRef kernelFnName,
llvm::SmallVectorImpl<Value> &operands) {
DenseSet<Value> inputOperandSet;
inputOperandSet.insert(operands.begin(), operands.end());
SetVector<Value> operandSet(operands.begin(), operands.end());
auto funcOp = outlineKernelFuncImpl(launchOp, kernelFnName, operandSet);
for (auto operand : operandSet) {
if (!inputOperandSet.count(operand))
operands.push_back(operand);
}
return funcOp;
}
static void convertToLaunchFuncOp(gpu::LaunchOp launchOp,
gpu::GPUFuncOp kernelFunc,
ValueRange operands) {
OpBuilder builder(launchOp);
Value asyncToken = launchOp.asyncToken();
auto launchFunc = builder.create<gpu::LaunchFuncOp>(
launchOp.getLoc(), kernelFunc, launchOp.getGridSizeOperandValues(),
launchOp.getBlockSizeOperandValues(), launchOp.dynamicSharedMemorySize(),
operands, asyncToken ? asyncToken.getType() : nullptr,
launchOp.asyncDependencies());
launchOp.replaceAllUsesWith(launchFunc);
launchOp.erase();
}
namespace {
class GpuLaunchSinkIndexComputationsPass
: public GpuLaunchSinkIndexComputationsBase<
GpuLaunchSinkIndexComputationsPass> {
public:
void runOnOperation() override {
Operation *op = getOperation();
if (op->walk([](gpu::LaunchOp launch) {
if (failed(sinkOperationsIntoLaunchOp(launch,
isLikelyAnIndexComputation)))
return WalkResult::interrupt();
return WalkResult::advance();
}).wasInterrupted())
signalPassFailure();
}
};
class GpuKernelOutliningPass
: public GpuKernelOutliningBase<GpuKernelOutliningPass> {
public:
GpuKernelOutliningPass(StringRef dlStr) {
if (!dlStr.empty() && !dataLayoutStr.hasValue())
dataLayoutStr = dlStr.str();
}
GpuKernelOutliningPass(const GpuKernelOutliningPass &other)
: GpuKernelOutliningBase(other), dataLayoutSpec(other.dataLayoutSpec) {
dataLayoutStr = other.dataLayoutStr.getValue();
}
LogicalResult initialize(MLIRContext *context) override {
if (!dataLayoutStr.empty()) {
Attribute resultAttr = mlir::parseAttribute(dataLayoutStr, context);
if (!resultAttr)
return failure();
dataLayoutSpec = resultAttr.dyn_cast<DataLayoutSpecInterface>();
if (!dataLayoutSpec)
return failure();
}
return success();
}
void runOnOperation() override {
SymbolTable symbolTable(getOperation());
bool modified = false;
for (auto func : getOperation().getOps<func::FuncOp>()) {
Block::iterator insertPt(func->getNextNode());
auto funcWalkResult = func.walk([&](gpu::LaunchOp op) {
SetVector<Value> operands;
std::string kernelFnName =
Twine(op->getParentOfType<func::FuncOp>().getName(), "_kernel")
.str();
gpu::GPUFuncOp outlinedFunc =
outlineKernelFuncImpl(op, kernelFnName, operands);
auto kernelModule = createKernelModule(outlinedFunc, symbolTable);
symbolTable.insert(kernelModule, insertPt);
convertToLaunchFuncOp(op, outlinedFunc, operands.getArrayRef());
modified = true;
return WalkResult::advance();
});
if (funcWalkResult.wasInterrupted())
return signalPassFailure();
}
if (modified)
getOperation()->setAttr(gpu::GPUDialect::getContainerModuleAttrName(),
UnitAttr::get(&getContext()));
}
private:
gpu::GPUModuleOp createKernelModule(gpu::GPUFuncOp kernelFunc,
const SymbolTable &parentSymbolTable) {
auto *context = getOperation().getContext();
OpBuilder builder(context);
auto kernelModule = builder.create<gpu::GPUModuleOp>(kernelFunc.getLoc(),
kernelFunc.getName());
if (dataLayoutSpec)
kernelModule->setAttr(DLTIDialect::kDataLayoutAttrName, dataLayoutSpec);
SymbolTable symbolTable(kernelModule);
symbolTable.insert(kernelFunc);
SmallVector<Operation *, 8> symbolDefWorklist = {kernelFunc};
while (!symbolDefWorklist.empty()) {
if (Optional<SymbolTable::UseRange> symbolUses =
SymbolTable::getSymbolUses(symbolDefWorklist.pop_back_val())) {
for (SymbolTable::SymbolUse symbolUse : *symbolUses) {
StringRef symbolName =
symbolUse.getSymbolRef().cast<FlatSymbolRefAttr>().getValue();
if (symbolTable.lookup(symbolName))
continue;
Operation *symbolDefClone =
parentSymbolTable.lookup(symbolName)->clone();
symbolDefWorklist.push_back(symbolDefClone);
symbolTable.insert(symbolDefClone);
}
}
}
return kernelModule;
}
Option<std::string> dataLayoutStr{
*this, "data-layout-str",
llvm::cl::desc("String containing the data layout specification to be "
"attached to the GPU kernel module")};
DataLayoutSpecInterface dataLayoutSpec;
};
}
std::unique_ptr<Pass> mlir::createGpuLauchSinkIndexComputationsPass() {
return std::make_unique<GpuLaunchSinkIndexComputationsPass>();
}
std::unique_ptr<OperationPass<ModuleOp>>
mlir::createGpuKernelOutliningPass(StringRef dataLayoutStr) {
return std::make_unique<GpuKernelOutliningPass>(dataLayoutStr);
}