43 #include "../GPUCommon/GPUOpsLowering.h"
44 #include "../GPUCommon/IndexIntrinsicsOpLowering.h"
47 #define GEN_PASS_DEF_CONVERTGPUOPSTOROCDLOPS
48 #include "mlir/Conversion/Passes.h.inc"
58 int64_t intWidth = cast<IntegerType>(value.
getType()).getWidth();
60 auto indexBitwidthType =
63 if (indexBitwidth > intWidth) {
64 return rewriter.
create<LLVM::SExtOp>(loc, indexBitwidthType, value);
66 if (indexBitwidth < intWidth) {
67 return rewriter.
create<LLVM::TruncOp>(loc, indexBitwidthType, value);
75 bool canBeBare =
true;
76 for (
Type type : func.getArgumentTypes())
77 if (
auto memrefTy = dyn_cast<BaseMemRefType>(type))
83 const unsigned indexBitwidth) {
85 Value zero = rewriter.
create<arith::ConstantIntOp>(loc, 0, 32);
86 Value minus1 = rewriter.
create<arith::ConstantIntOp>(loc, -1, 32);
87 Value mbcntLo = rewriter.
create<ROCDL::MbcntLoOp>(loc, int32Type,
89 Value laneId = rewriter.
create<ROCDL::MbcntHiOp>(loc, int32Type,
94 "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32"
95 "-p7:160:256:256:32-p8:128:128:128:48-p9:192:256:256:32-i64:64-v16:16-v24:"
97 "32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:"
98 "64-S32-A5-G1-ni:7:8:9";
105 matchAndRewrite(gpu::LaneIdOp op, gpu::LaneIdOp::Adaptor adaptor,
107 auto loc = op->getLoc();
113 Value zero = rewriter.
create<arith::ConstantIntOp>(loc, 0, 32);
114 Value minus1 = rewriter.
create<arith::ConstantIntOp>(loc, -1, 32);
121 const unsigned indexBitwidth = getTypeConverter()->getIndexTypeBitwidth();
122 if (indexBitwidth > 32) {
123 laneId = rewriter.
create<LLVM::SExtOp>(
125 }
else if (indexBitwidth < 32) {
126 laneId = rewriter.
create<LLVM::TruncOp>(
138 amdgpu::Chipset chipset)
143 matchAndRewrite(gpu::SubgroupSizeOp op, gpu::SubgroupSizeOp::Adaptor adaptor,
145 LLVM::ConstantRangeAttr bounds =
nullptr;
146 bool isBeforeGfx10 = chipset.majorVersion < 10;
147 if (
auto upperBoundAttr = op.getUpperBoundAttr()) {
148 bounds = rewriter.
getAttr<LLVM::ConstantRangeAttr>(
149 32, isBeforeGfx10 ? 64 : 32,
150 op.getUpperBoundAttr().getInt() + 1);
152 Value wavefrontOp = rewriter.
create<ROCDL::WavefrontSizeOp>(
155 *getTypeConverter());
160 const amdgpu::Chipset chipset;
183 matchAndRewrite(gpu::ShuffleOp op, OpAdaptor adaptor,
186 Value initShflValue = adaptor.getValue();
188 const unsigned indexBitwidth = getTypeConverter()->getIndexTypeBitwidth();
192 Value width = adaptor.getWidth();
193 Value zero = rewriter.
create<LLVM::ConstantOp>(loc, int32Type, 0);
194 Value negwidth = rewriter.
create<LLVM::SubOp>(loc, int32Type, zero, width);
195 Value add = rewriter.
create<LLVM::AddOp>(loc, int32Type, srcLaneId, width);
196 Value widthOrZeroIfOutside =
197 rewriter.
create<LLVM::AndOp>(loc, int32Type, add, negwidth);
200 switch (op.getMode()) {
201 case gpu::ShuffleMode::UP:
202 dstLane = rewriter.
create<LLVM::SubOp>(loc, int32Type, srcLaneId,
203 adaptor.getOffset());
205 case gpu::ShuffleMode::DOWN:
206 dstLane = rewriter.
create<LLVM::AddOp>(loc, int32Type, srcLaneId,
207 adaptor.getOffset());
209 case gpu::ShuffleMode::XOR:
210 dstLane = rewriter.
create<LLVM::XOrOp>(loc, int32Type, srcLaneId,
211 adaptor.getOffset());
213 case gpu::ShuffleMode::IDX:
214 dstLane = adaptor.getOffset();
217 Value isActiveSrcLane = rewriter.
create<LLVM::ICmpOp>(
218 loc, LLVM::ICmpPredicate::slt, dstLane, widthOrZeroIfOutside);
219 Value selectDstLane = rewriter.
create<LLVM::SelectOp>(loc, isActiveSrcLane,
221 Value two = rewriter.
create<LLVM::ConstantOp>(loc, int32Type, 2);
222 Value dwordAlignedDstLane =
223 rewriter.
create<LLVM::ShlOp>(loc, int32Type, selectDstLane, two);
228 for (
Value v : decomposed) {
229 Value res = rewriter.
create<ROCDL::DsBpermuteOp>(loc, int32Type,
230 dwordAlignedDstLane, v);
231 swizzled.emplace_back(res);
235 rewriter.
replaceOp(op, {shflValue, isActiveSrcLane});
241 #include "GPUToROCDL.cpp.inc"
248 struct LowerGpuOpsToROCDLOpsPass final
249 :
public impl::ConvertGpuOpsToROCDLOpsBase<LowerGpuOpsToROCDLOpsPass> {
250 LowerGpuOpsToROCDLOpsPass() =
default;
251 LowerGpuOpsToROCDLOpsPass(
const std::string &chipset,
unsigned indexBitwidth,
252 bool useBarePtrCallConv,
254 if (this->chipset.getNumOccurrences() == 0)
255 this->chipset = chipset;
256 if (this->indexBitwidth.getNumOccurrences() == 0)
257 this->indexBitwidth = indexBitwidth;
258 if (this->useBarePtrCallConv.getNumOccurrences() == 0)
259 this->useBarePtrCallConv = useBarePtrCallConv;
260 if (this->runtime.getNumOccurrences() == 0)
261 this->runtime = runtime;
265 Base::getDependentDialects(registry);
269 void runOnOperation()
override {
270 gpu::GPUModuleOp m = getOperation();
273 auto llvmDataLayout = m->getAttrOfType<StringAttr>(
274 LLVM::LLVMDialect::getDataLayoutAttrName());
275 if (!llvmDataLayout) {
277 m->setAttr(LLVM::LLVMDialect::getDataLayoutAttrName(), llvmDataLayout);
280 for (
auto func : m.getOps<func::FuncOp>()) {
281 func->setAttr(LLVM::LLVMDialect::getEmitCWrapperAttrName(),
286 if (failed(maybeChipset)) {
288 return signalPassFailure();
293 ctx,
DataLayout(cast<DataLayoutOpInterface>(m.getOperation())));
294 options.dataLayout = llvm::DataLayout(llvmDataLayout.getValue());
296 options.overrideIndexBitwidth(indexBitwidth);
298 if (useBarePtrCallConv) {
299 options.useBarePtrCallConv =
true;
301 m.walk([](gpu::GPUFuncOp func) ->
WalkResult {
308 "bare pointer calling convention requires all memrefs to "
309 "have static shape and use the identity map");
310 return signalPassFailure();
326 converter, [](gpu::AddressSpace space) {
328 case gpu::AddressSpace::Global:
330 case gpu::AddressSpace::Workgroup:
332 case gpu::AddressSpace::Private:
335 llvm_unreachable(
"unknown address space enum value");
342 llvm::SmallDenseSet<StringRef> allowedDialectsSet(allowedDialects.begin(),
343 allowedDialects.end());
345 bool allowed = allowedDialectsSet.contains(dialect->getNamespace());
347 if (!allowedDialectsSet.empty() && !allowed)
350 auto iface = dyn_cast<ConvertToLLVMPatternInterface>(dialect);
356 <<
"dialect does not implement ConvertToLLVMPatternInterface: "
357 << dialect->getNamespace();
358 return signalPassFailure();
363 iface->populateConvertToLLVMConversionPatterns(target, converter,
375 auto reqdWorkGroupSizeAttrHelper =
376 rocdlDialect->getReqdWorkGroupSizeAttrHelper();
377 auto flatWorkGroupSizeAttrHelper =
378 rocdlDialect->getFlatWorkGroupSizeAttrHelper();
381 m.walk([&](LLVM::LLVMFuncOp op) {
382 if (reqdWorkGroupSizeAttrHelper.isAttrPresent(op)) {
383 auto blockSizes = reqdWorkGroupSizeAttrHelper.getAttr(op);
386 uint32_t flatSize = 1;
387 for (uint32_t size : blockSizes.asArrayRef()) {
390 StringAttr flatSizeAttr =
392 flatWorkGroupSizeAttrHelper.setAttr(op, flatSizeAttr);
405 target.
addIllegalOp<LLVM::CosOp, LLVM::ExpOp, LLVM::Exp2Op, LLVM::FCeilOp,
406 LLVM::FFloorOp, LLVM::FRemOp, LLVM::LogOp, LLVM::Log10Op,
407 LLVM::Log2Op, LLVM::PowOp, LLVM::SinOp>();
410 return any_of(op->getOperandTypes(), llvm::IsaPred<Float32Type>);
413 target.
addLegalOp<gpu::YieldOp, gpu::GPUModuleOp>();
427 ROCDL::ThreadIdYOp, ROCDL::ThreadIdZOp>>(
428 converter, IndexKind::Block, IntrType::Id);
430 gpu::BlockIdOp, ROCDL::BlockIdXOp, ROCDL::BlockIdYOp, ROCDL::BlockIdZOp>>(
431 converter, IndexKind::Grid, IntrType::Id);
434 ROCDL::BlockDimYOp, ROCDL::BlockDimZOp>>(
435 converter, IndexKind::Block, IntrType::Dim);
437 gpu::GridDimOp, ROCDL::GridDimXOp, ROCDL::GridDimYOp, ROCDL::GridDimZOp>>(
438 converter, IndexKind::Grid, IntrType::Dim);
443 ROCDL::ROCDLDialect::kPrivateMemoryAddressSpace,
444 ROCDL::ROCDLDialect::kSharedMemoryAddressSpace,
445 rocdlDialect->getKernelAttrHelper().getName(),
446 rocdlDialect->getReqdWorkGroupSizeAttrHelper().getName()});
456 patterns.add<GPUShuffleOpLowering, GPULaneIdOpToROCDL>(converter);
457 patterns.add<GPUSubgroupSizeOpToROCDL>(converter, chipset);
462 std::unique_ptr<OperationPass<gpu::GPUModuleOp>>
464 unsigned indexBitwidth,
465 bool useBarePtrCallConv,
467 return std::make_unique<LowerGpuOpsToROCDLOpsPass>(
468 chipset, indexBitwidth, useBarePtrCallConv, runtime);
static MLIRContext * getContext(OpFoldResult val)
static bool canBeCalledWithBarePointers(gpu::GPUFuncOp func)
Returns true if the given gpu.func can be safely called using the bare pointer calling convention.
static constexpr StringLiteral amdgcnDataLayout
static Value getLaneId(ConversionPatternRewriter &rewriter, Location loc, const unsigned indexBitwidth)
static Value truncOrExtToLLVMType(ConversionPatternRewriter &rewriter, Location loc, Value value, const LLVMTypeConverter &converter)
static llvm::ManagedStatic< PassManagerOptions > options
MLIRContext * getContext() const
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
This class implements a pattern rewriter for use with ConversionPatterns.
void replaceOp(Operation *op, ValueRange newValues) override
Replace the given operation with the new values.
This class describes a specific conversion target.
void addLegalOp(OperationName op)
Register the given operations as legal.
void addLegalDialect(StringRef name, Names... names)
Register the operations of the given dialects as legal.
void addDynamicallyLegalOp(OperationName op, const DynamicLegalityCallbackFn &callback)
Register the given operation as dynamically legal and set the dynamic legalization callback to the on...
void addIllegalDialect(StringRef name, Names... names)
Register the operations of the given dialects as illegal, i.e.
void addIllegalOp(OperationName op)
Register the given operation as illegal, i.e.
Utility class for operation conversions targeting the LLVM dialect that match exactly one source oper...
ConvertOpToLLVMPattern(const LLVMTypeConverter &typeConverter, PatternBenefit benefit=1)
The main mechanism for performing data layout queries.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
Derived class that automatically populates legalization information for different LLVM ops.
Conversion from types to the LLVM IR dialect.
static bool canConvertToBarePtr(BaseMemRefType type)
Check if a memref type can be converted to a bare pointer.
MLIRContext & getContext() const
Returns the MLIR context.
unsigned getIndexTypeBitwidth() const
Gets the bitwidth of the index type when converted to LLVM.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Options to control the LLVM lowering.
MLIRContext is the top-level object for a collection of MLIR operations.
Dialect * getLoadedDialect(StringRef name)
Get a registered IR dialect with the given namespace.
std::vector< Dialect * > getLoadedDialects()
Return information about all IR dialects loaded in the context.
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Operation is the basic unit of execution within MLIR.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
A utility result that is used to signal how to proceed with an ongoing walk:
static WalkResult advance()
bool wasInterrupted() const
Returns true if the walk was interrupted.
static WalkResult interrupt()
Value composeValue(OpBuilder &builder, Location loc, ValueRange src, Type dstType)
Composes a set of src values into a single value of type dstType through series of bitcasts and vecto...
SmallVector< Value > decomposeValue(OpBuilder &builder, Location loc, Value src, Type dstType)
Decomposes a src value into a set of values of type dstType through series of bitcasts and vector ops...
Runtime
Potential runtimes for AMD GPU kernels.
Include the generated interface declarations.
void populateGpuToROCDLConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, gpu::amd::Runtime runtime, amdgpu::Chipset chipset)
Collect a set of patterns to convert from the GPU dialect to ROCDL.
static constexpr unsigned kDeriveIndexBitwidthFromDataLayout
Value to pass as bitwidth for the index type when the converter is expected to derive the bitwidth fr...
LogicalResult applyPatternsGreedily(Region ®ion, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
void populateGpuRewritePatterns(RewritePatternSet &patterns)
Collect all patterns to rewrite ops within the GPU dialect.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
void configureGpuToROCDLConversionLegality(ConversionTarget &target)
Configure target to convert from the GPU dialect to ROCDL.
std::unique_ptr< OperationPass< gpu::GPUModuleOp > > createLowerGpuOpsToROCDLOpsPass(const std::string &chipset="gfx900", unsigned indexBitwidth=kDeriveIndexBitwidthFromDataLayout, bool useBarePtrCallConv=false, gpu::amd::Runtime runtime=gpu::amd::Runtime::Unknown)
Creates a pass that lowers GPU dialect operations to ROCDL counterparts.
const FrozenRewritePatternSet & patterns
void registerConvertToLLVMDependentDialectLoading(DialectRegistry ®istry)
Register the extension that will load dependent dialects for LLVM conversion.
void populateGpuMemorySpaceAttributeConversions(TypeConverter &typeConverter, const MemorySpaceMapping &mapping)
Populates memory space attribute conversion rules for lowering gpu.address_space to integer values.
void populateAMDGPUToROCDLConversionPatterns(LLVMTypeConverter &converter, RewritePatternSet &patterns, amdgpu::Chipset chipset)
Note: This function will also add conversions for the AMDGPU-specific address spaces,...
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
void populateGpuPromoteShuffleToAMDGPUPatterns(RewritePatternSet &patterns)
Tries to promote gpu.shuffles to specialized AMDGPU intrinsics.
LogicalResult applyPartialConversion(ArrayRef< Operation * > ops, const ConversionTarget &target, const FrozenRewritePatternSet &patterns, ConversionConfig config=ConversionConfig())
Below we define several entry points for operation conversion.
void populateMathToROCDLConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns)
Populate the given list with patterns that convert from Math to ROCDL calls.
Lowering for gpu.dynamic.shared.memory to LLVM dialect.
The lowering of gpu.printf to a call to HIP hostcalls.
The lowering of gpu.printf to a call to an external printf() function.
Represents the amdgpu gfx chipset version, e.g., gfx90a, gfx942, gfx1103.
static FailureOr< Chipset > parse(StringRef name)
Parses the chipset version string and returns the chipset on success, and failure otherwise.