39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/SmallVector.h"
41#include "llvm/ADT/TypeSwitch.h"
42#include "llvm/Support/DebugLog.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/InterleavedRange.h"
45#include "llvm/Support/LogicalResult.h"
54#define DEBUG_TYPE "gpu-transforms"
60void transform::ApplyGPUToNVVMConversionPatternsOp::populatePatterns(
70transform::ApplyGPUToNVVMConversionPatternsOp::verifyTypeConverter(
71 transform::TypeConverterBuilderOpInterface builder) {
72 if (builder.getTypeConverterType() !=
"LLVMTypeConverter")
73 return emitOpError(
"expected LLVMTypeConverter");
77void transform::ApplyGPUWwmaToNVVMConversionPatternsOp::populatePatterns(
84transform::ApplyGPUWwmaToNVVMConversionPatternsOp::verifyTypeConverter(
85 transform::TypeConverterBuilderOpInterface builder) {
86 if (builder.getTypeConverterType() !=
"LLVMTypeConverter")
87 return emitOpError(
"expected LLVMTypeConverter");
91void transform::ApplyGPUSubgroupReduceToNVVMConversionPatternsOp::
98LogicalResult transform::ApplyGPUSubgroupReduceToNVVMConversionPatternsOp::
99 verifyTypeConverter(transform::TypeConverterBuilderOpInterface builder) {
100 if (builder.getTypeConverterType() !=
"LLVMTypeConverter")
101 return emitOpError(
"expected LLVMTypeConverter");
105void transform::ApplyGPUToROCDLConversionPatternsOp::populatePatterns(
110 FailureOr<ROCDL::TargetInfo> targetInfo =
112 assert(llvm::succeeded(targetInfo) &&
"verifier accepted this target");
118transform::ApplyGPUToROCDLConversionPatternsOp::verifyTypeConverter(
119 transform::TypeConverterBuilderOpInterface builder) {
121 [&] {
return emitOpError(); })))
123 if (builder.getTypeConverterType() !=
"LLVMTypeConverter")
124 return emitOpError(
"expected LLVMTypeConverter");
136void transform::ApplyGPUPromoteShuffleToAMDGPUPatternsOp::populatePatterns(
138 std::optional<StringRef> archName = getArch();
139 std::optional<ROCDL::TargetInfo> targetInfo;
143 assert(llvm::succeeded(parsed) &&
"verifier accepted this target");
144 targetInfo = *parsed;
150LogicalResult transform::ApplyGPUPromoteShuffleToAMDGPUPatternsOp::verify() {
151 std::optional<StringRef> archName = getArch();
156 [&] {
return emitOpError(); })))
175struct MappingKind {};
176struct BlockMappingKind : MappingKind {};
177struct ThreadMappingKind : MappingKind {};
183 if (transformOp.has_value())
184 return transformOp->emitDefiniteFailure() << message;
189template <
typename MappingKindType>
192 scf::ForallOp forallOp) {
193 if (!forallOp.getMapping().has_value()) {
195 "scf.forall op requires a mapping attribute");
198 bool hasBlockMapping = llvm::any_of(forallOp.getMapping().value(),
199 llvm::IsaPred<GPUBlockMappingAttr>);
200 bool hasWarpgroupMapping = llvm::any_of(
201 forallOp.getMapping().value(), llvm::IsaPred<GPUWarpgroupMappingAttr>);
202 bool hasWarpMapping = llvm::any_of(forallOp.getMapping().value(),
203 llvm::IsaPred<GPUWarpMappingAttr>);
204 bool hasThreadMapping = llvm::any_of(forallOp.getMapping().value(),
205 llvm::IsaPred<GPUThreadMappingAttr>);
206 bool hasLaneMapping = llvm::any_of(forallOp.getMapping().value(),
207 llvm::IsaPred<GPULaneMappingAttr>);
209 countMappingTypes += hasBlockMapping ? 1 : 0;
210 countMappingTypes += hasWarpgroupMapping ? 1 : 0;
211 countMappingTypes += hasWarpMapping ? 1 : 0;
212 countMappingTypes += hasThreadMapping ? 1 : 0;
213 countMappingTypes += hasLaneMapping ? 1 : 0;
214 if (countMappingTypes > 1) {
216 transformOp, forallOp,
217 "cannot mix different mapping types, use nesting");
219 if (std::is_same<MappingKindType, BlockMappingKind>::value &&
222 transformOp, forallOp,
223 "scf.forall op requires a mapping attribute of kind 'block'");
225 if (std::is_same<MappingKindType, ThreadMappingKind>::value &&
226 !hasLaneMapping && !hasThreadMapping && !hasWarpMapping &&
227 !hasWarpgroupMapping) {
229 "scf.forall op requires a mapping attribute "
230 "of kind 'thread' or 'warp'");
234 for (
Attribute map : forallOp.getMapping()->getValue()) {
235 if (seen.contains(map)) {
237 transformOp, forallOp,
238 "duplicate attribute, cannot map different loops "
239 "to the same mapping id");
244 auto isLinear = [](DeviceMappingAttrInterface attr) {
245 return attr.isLinearMapping();
247 if (llvm::any_of(forallOp.getDeviceMappingAttrs(), isLinear) &&
248 !llvm::all_of(forallOp.getDeviceMappingAttrs(), isLinear)) {
250 transformOp, forallOp,
251 "cannot mix linear and non-linear mapping modes");
254 FailureOr<DeviceMaskingAttrInterface> maybeMaskingAttr =
255 forallOp.getDeviceMaskingAttr();
256 if (succeeded(maybeMaskingAttr) && *maybeMaskingAttr &&
257 !forallOp.usesLinearMapping()) {
259 transformOp, forallOp,
260 "device masking is only available in linear mapping mode");
266template <
typename MappingKindType>
269 scf::ForallOp forallOp) {
277 if (!forallOp.isNormalized())
279 "unsupported non-normalized loops");
280 if (forallOp.getNumResults() > 0)
282 "only bufferized scf.forall can be mapped");
283 bool useLinearMapping = forallOp.usesLinearMapping();
286 int64_t maxNumMappingsSupported =
287 useLinearMapping ? (getMaxEnumValForMappingId() -
288 static_cast<uint64_t
>(MappingId::DimZ))
290 if (forallOp.getRank() > maxNumMappingsSupported) {
292 "scf.forall with rank > ")
293 << maxNumMappingsSupported
294 <<
" does not lower for the specified mapping attribute type";
296 auto numParallelIterations =
298 if (!forallOp.isNormalized() || !numParallelIterations.has_value()) {
300 transformOp, forallOp,
301 "requires statically sized, normalized forall op");
313template <
typename OpTy,
typename OperationOrBlock>
318 parent->walk([&](OpTy idOp) {
319 if (availableMappingSizes[
static_cast<int64_t>(idOp.getDimension())] == 1)
325 RewriterBase &rewriter, std::optional<TransformOpInterface> transformOp,
328 LDBG() <<
"--start rewriteOneForallCommonImpl";
331 auto numParallelIterations =
333 assert(forallOp.isNormalized() && numParallelIterations.has_value() &&
334 "requires statically sized, normalized forall op");
337 forallOp.getDeviceMappingAttrs();
339 forallMappingAttrs.insert_range(forallMappingAttrsVec);
341 return cast<DeviceMappingAttrInterface>(a).getMappingId() <
342 cast<DeviceMappingAttrInterface>(
b).getMappingId();
348 DeviceMappingAttrInterface maxMapping = cast<DeviceMappingAttrInterface>(
349 *llvm::max_element(forallMappingAttrs, comparator));
350 DeviceMappingAttrInterface maxLinearMapping;
351 if (maxMapping.isLinearMapping())
352 maxLinearMapping = maxMapping;
355 if (maxLinearMapping && comparator(maxLinearMapping, attr))
358 if (!forallMappingAttrs.insert(attr))
361 tmpMappingSizes.push_back(1);
363 LDBG() <<
"----tmpMappingSizes extracted from scf.forall op: "
364 << llvm::interleaved(tmpMappingSizes);
368 forallMappingAttrs.getArrayRef(), tmpMappingSizes, comparator);
369 LDBG() <<
"----forallMappingSizes: " << llvm::interleaved(forallMappingSizes);
370 LDBG() <<
"----forallMappingAttrs: " << llvm::interleaved(forallMappingAttrs);
377 bool originalBasisWasProvided = !originalBasis.empty();
378 if (!originalBasisWasProvided) {
379 LDBG() <<
"----originalBasis was not provided, deriving it and there will "
382 originalBasis = forallMappingSizes;
383 while (originalBasis.size() < 3)
384 originalBasis.push_back(1);
386 LDBG() <<
"----originalBasis was provided, using it, there will be "
389 LDBG() <<
"------originalBasis: " << llvm::interleaved(originalBasis);
392 gpuIdBuilder.
idBuilder(rewriter, loc, forallMappingSizes, originalBasis);
393 if (!builderResult.
errorMsg.empty())
396 LDBG() << builderResult;
402 for (
auto [iv, dim] : llvm::zip_equal(
403 forallOp.getInductionVars(),
404 forallMappingAttrs.getArrayRef().take_front(forallOp.getRank()))) {
405 auto mappingAttr = cast<DeviceMappingAttrInterface>(dim);
406 Value peIdOp = mappingIdOps[mappingAttr.getRelativeIndex()];
407 LDBG() <<
"----map: " << iv <<
" to " << peIdOp;
415 if (originalBasisWasProvided) {
417 predicate = predicate ? arith::AndIOp::create(rewriter, loc, predicate,
425 rewriter.
eraseOp(forallOp.getTerminator());
430 auto ifOp = scf::IfOp::create(rewriter, loc, predicate,
432 targetBlock = ifOp.thenBlock();
433 insertionPoint = ifOp.thenBlock()->
begin();
437 targetBlock = forallOp->getBlock();
440 Block &sourceBlock = forallOp.getRegion().
front();
445 for (
Value loopIndex : forallOp.getInductionVars()) {
453 LDBG() <<
"----result forallMappingSizes: "
454 << llvm::interleaved(forallMappingSizes);
455 LDBG() <<
"----result mappingIdOps: " << llvm::interleaved(mappingIdOps);
466 RewriterBase &rewriter, TransformOpInterface transformOp,
469 LDBG() <<
"Start mapForallToBlocksImpl";
477 if (!
diag.succeeded())
482 Block *parentBlock = forallOp->getBlock();
494 rewriter, transformOp, forallOp,
495 gridDims, rewriteResult, gpuIdBuilder);
499 if (!
diag.succeeded())
503 if (gridDims.empty()) {
505 while (gridDims.size() < 3)
506 gridDims.push_back(1);
508 assert(gridDims.size() == 3 &&
"Need 3-D gridDims");
520 scf::ForallOp &topLevelForallOp,
521 TransformOpInterface transformOp) {
522 auto walkResult =
target->walk([&](scf::ForallOp forallOp) {
523 if (forallOp->getParentOfType<scf::ForallOp>())
525 if (topLevelForallOp)
528 topLevelForallOp = forallOp;
532 if (walkResult.wasInterrupted() || !topLevelForallOp)
533 return transformOp.emitSilenceableError()
534 <<
"could not find a unique topLevel scf.forall";
541 LaunchOp gpuLaunch = dyn_cast<LaunchOp>(
target);
542 auto transformOp = cast<TransformOpInterface>(getOperation());
544 if (!getGenerateGpuLaunch() && !gpuLaunch) {
546 emitSilenceableError()
547 <<
"Given target is not gpu.launch, set `generate_gpu_launch` "
549 diag.attachNote(
target->getLoc()) <<
"when applied to this payload op";
553 scf::ForallOp topLevelForallOp;
555 target, topLevelForallOp, transformOp);
556 if (!
diag.succeeded()) {
557 diag.attachNote(
target->getLoc()) <<
"when applied to this payload op";
560 assert(topLevelForallOp &&
"expect an scf.forall");
563 if (!getGenerateGpuLaunch() && gridDims.size() != 3)
564 return transformOp.emitDefiniteFailure(
"transform require size-3 mapping");
570 if (getGenerateGpuLaunch()) {
573 if (!
diag.succeeded())
578 rewriter.
eraseOp(topLevelForallOp);
579 topLevelForallOp = cast<scf::ForallOp>(newForallOp);
583 bool useLinearMapping =
false;
584 if (topLevelForallOp.getMapping())
585 useLinearMapping = topLevelForallOp.usesLinearMapping();
587 FailureOr<DeviceMaskingAttrInterface> maybeMaskingAttr =
588 topLevelForallOp.getDeviceMaskingAttr();
589 assert(succeeded(maybeMaskingAttr) &&
"unexpected failed maybeMaskingAttr");
590 assert((!*maybeMaskingAttr || useLinearMapping) &&
591 "masking requires linear mapping");
597 rewriter, transformOp, topLevelForallOp, gridDims, gpuBlockIdBuilder);
598 if (!
diag.succeeded())
604 cast<TransformOpInterface>(getOperation()), gridDims[0],
605 gridDims[1], gridDims[2]);
611LogicalResult transform::MapForallToBlocks::verify() {
612 if (!getGridDims().empty() && getGridDims().size() != 3) {
613 return emitOpError() <<
"transform requires empty or size-3 grid_dims";
623 std::optional<TransformOpInterface> transformOp, scf::ForallOp forallOp,
625 int factor,
bool useLinearMapping =
false) {
626 if (llvm::any_of(blockOrGridSizes, [](
int64_t i) {
return i <= 0; })) {
628 "block/grid sizes must be strictly positive");
630 if (!useLinearMapping && blockOrGridSizes.front() % factor != 0) {
632 transformOp, forallOp,
633 Twine(
"3-D mapping: size of threadIdx.x must be a multiple of ") +
637 bool hasZeroParallelIteration =
638 llvm::any_of(numParallelIterations, [](
int64_t i) {
return i == 0; });
642 int64_t requiredResourceCount =
643 hasZeroParallelIteration ? 0
646 if (requiredResourceCount > availableResourceCount) {
648 transformOp, forallOp,
649 Twine(
"the number of required parallel resources (blocks or "
651 Twine(requiredResourceCount) +
652 " overflows the number of available resources " +
653 Twine(availableResourceCount));
663 DeviceMappingAttrInterface mappingAttr =
664 forallOp.getDeviceMappingAttrs().front();
665 bool useLinearMapping = mappingAttr.isLinearMapping();
668 auto numParallelIterations =
670 if (!forallOp.isNormalized() || !numParallelIterations.has_value()) {
672 transformOp, forallOp,
673 "requires statically sized, normalized forall op");
676 if (isa<GPUWarpgroupMappingAttr>(mappingAttr)) {
678 }
else if (isa<GPUWarpMappingAttr>(mappingAttr)) {
683 blockSizes, factor, useLinearMapping);
684 if (!
diag.succeeded())
687 FailureOr<DeviceMaskingAttrInterface> maybeMaskingAttr =
688 forallOp.getDeviceMaskingAttr();
689 assert(succeeded(maybeMaskingAttr) &&
"unexpected failed maybeMaskingAttr");
690 assert((!*maybeMaskingAttr || useLinearMapping) &&
691 "masking requires linear mapping");
697 .Case([&](GPUWarpgroupMappingAttr) {
701 .Case([&](GPUWarpMappingAttr) {
705 .Case([&](GPUThreadMappingAttr) {
708 .Case([&](GPULaneMappingAttr) {
712 .DefaultUnreachable(
"unknown mapping attribute");
717 RewriterBase &rewriter, std::optional<TransformOpInterface> transformOp,
719 bool syncAfterDistribute) {
727 if (!
diag.succeeded())
735 transformOp, forallOp, blockSizes, warpSize, gpuIdBuilder);
736 if (!
diag.succeeded())
746 rewriter, transformOp, forallOp, blockSizes, rewriteResult, gpuIdBuilder);
747 if (!
diag.succeeded())
750 if (syncAfterDistribute)
751 BarrierOp::create(rewriter, loc);
757 RewriterBase &rewriter, std::optional<TransformOpInterface> transformOp,
759 bool syncAfterDistribute) {
760 LDBG() <<
"Start mapNestedForallToThreadsImpl";
761 if (blockDims.size() != 3) {
763 "requires size-3 thread mapping");
772 rewriter, transformOp, forallOp, blockDims, warpSize,
773 syncAfterDistribute);
774 if (
diag.isDefiniteFailure())
776 if (
diag.succeeded())
794 LaunchOp gpuLaunch = dyn_cast<LaunchOp>(
target);
795 auto transformOp = cast<TransformOpInterface>(getOperation());
799 return emitSilenceableError() <<
"Given target is not a gpu.launch";
804 checkGpuLimits(transformOp, std::nullopt, std::nullopt, std::nullopt,
805 blockDims[0], blockDims[1], blockDims[2]);
806 if (
diag.isSilenceableFailure()) {
807 diag.attachNote(getLoc()) << getBlockDimsAttrName() <<
" is too large";
814 std::nullopt, std::nullopt, blockDims[0], blockDims[1],
820 getWarpSize(), getSyncAfterDistribute());
822 results.
push_back(gpuLaunch.getOperation());
833class GPUTransformDialectExtension
835 GPUTransformDialectExtension> {
839 GPUTransformDialectExtension() {
840 declareGeneratedDialect<GPUDialect>();
841 declareGeneratedDialect<amdgpu::AMDGPUDialect>();
842 declareGeneratedDialect<arith::ArithDialect>();
843 declareGeneratedDialect<scf::SCFDialect>();
844 registerTransformOps<
846#include "mlir/Dialect/GPU/TransformOps/GPUTransformOps.cpp.inc"
852#define GET_OP_CLASSES
853#include "mlir/Dialect/GPU/TransformOps/GPUTransformOps.cpp.inc"
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be the output argument nBegin is set to its * replacement(set to `begin` if no invalidation happens). Since outgoing *copies could have been inserted at `end`
#define MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(CLASS_NAME)
Attributes are known-constant values of operations.
Block represents an ordered list of Operations.
OpListType::iterator iterator
OpListType & getOperations()
The result of a transform IR operation application.
static DiagnosedSilenceableFailure success()
Constructs a DiagnosedSilenceableFailure in the success state.
bool succeeded() const
Returns true if this is a success.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
void addExtensions()
Add the given extensions to the registry.
This is a utility class for mapping one set of IR entities to another.
auto lookup(T from) const
Lookup a mapped value within the map.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Conversion from types to the LLVM IR dialect.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
RAII guard to reset the insertion point of the builder when destroyed.
Block::iterator getInsertionPoint() const
Returns the current insertion point of the builder.
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Operation is the basic unit of execution within MLIR.
static FailureOr< TargetInfo > get(StringRef arch, unsigned waveSize=0, function_ref< InFlightDiagnostic()> emitError=nullptr)
Resolves a target description.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
This class represents an instance of an SSA value in the MLIR system, representing a computable 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()
static ConstantIndexOp create(OpBuilder &builder, Location location, int64_t value)
Base class for extensions of the Transform dialect that supports injecting operations into the Transf...
void populateCommonGPUTypeAndAttributeConversions(TypeConverter &typeConverter)
Remap common GPU memory spaces (Workgroup, Private, etc) to LLVM address spaces.
void registerTransformDialectExtension(DialectRegistry ®istry)
Include the generated interface declarations.
void populateGpuPromoteShuffleToAMDGPUPatterns(RewritePatternSet &patterns, std::optional< ROCDL::TargetInfo > target)
Tries to promote gpu.shuffles to specialized AMDGPU intrinsics.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
void populateGpuRewritePatterns(RewritePatternSet &patterns)
Collect all patterns to rewrite ops within the GPU dialect.
void populateGpuToROCDLConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, gpu::amd::Runtime runtime, const ROCDL::TargetInfo &target)
Collect a set of patterns to convert from the GPU dialect to ROCDL.
int64_t computeProduct(ArrayRef< int64_t > basis)
Self-explicit.
llvm::SetVector< T, Vector, Set, N > SetVector
DiagnosedDefiniteFailure emitDefiniteFailure(Location loc, const Twine &message={})
Emits a definite failure with the given message.
void configureGpuToNVVMTypeConverter(LLVMTypeConverter &converter)
Configure the LLVM type convert to convert types and address spaces from the GPU dialect to NVVM.
void populateGpuSubgroupReduceOpLoweringPattern(const LLVMTypeConverter &converter, RewritePatternSet &patterns, PatternBenefit benefit=1)
Populate GpuSubgroupReduce pattern to NVVM.
void populateGpuToNVVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, PatternBenefit benefit=1)
Collect a set of patterns to convert from the GPU dialect to NVVM.
llvm::TypeSwitch< T, ResultT > TypeSwitch
std::optional< SmallVector< int64_t > > getConstantIntValues(ArrayRef< OpFoldResult > ofrs)
If all ofrs are constant integers or IntegerAttrs, return the integers.
SmallVector< Value > getValuesSortedByKey(ArrayRef< Attribute > keys, ArrayRef< Value > values, llvm::function_ref< bool(Attribute, Attribute)> compare)
Helper to sort values according to matching keys.
void populateGpuEliminateBarriersPatterns(RewritePatternSet &patterns)
Erase barriers that do not enforce conflicting memory side effects.
void populateGpuWMMAToNVVMConversionPatterns(const LLVMTypeConverter &converter, RewritePatternSet &patterns, PatternBenefit benefit=1)
Collect a set of patterns to convert WMMA ops from GPU dialect to NVVM.
Struct to return the result of the rewrite of a forall operation.
SmallVector< Value > mappingIds
SmallVector< int64_t > mappingSizes