25#include "llvm/ADT/DenseMap.h"
26#include "llvm/ADT/STLExtras.h"
27#include "llvm/Support/Alignment.h"
32#define GEN_PASS_DEF_SPIRVUNIFYALIASEDRESOURCEPASS
33#include "mlir/Dialect/SPIRV/Transforms/Passes.h.inc"
50 moduleOp->walk([&aliasedResources](spirv::GlobalVariableOp varOp) {
51 if (varOp->getDiscardableAttrOfType<UnitAttr>(
"aliased")) {
52 std::optional<uint32_t> set = varOp.getDescriptorSet();
53 std::optional<uint32_t> binding = varOp.getBinding();
55 aliasedResources[{*set, *binding}].push_back(varOp);
58 return aliasedResources;
65 auto ptrType = dyn_cast<spirv::PointerType>(type);
69 auto structType = dyn_cast<spirv::StructType>(ptrType.getPointeeType());
70 if (!structType || structType.getNumElements() != 1)
74 dyn_cast<spirv::RuntimeArrayType>(structType.getElementType(0));
78 return rtArrayType.getElementType();
84static std::optional<int>
90 scalarNumBits.reserve(types.size());
91 vectorNumBits.reserve(types.size());
92 vectorIndices.reserve(types.size());
94 for (
const auto &indexedTypes : llvm::enumerate(types)) {
97 if (
auto vectorType = dyn_cast<VectorType>(type)) {
98 if (vectorType.getNumElements() % 2 != 0)
106 scalarNumBits.push_back(
107 vectorType.getElementType().getIntOrFloatBitWidth());
108 vectorNumBits.push_back(*numBytes * 8);
109 vectorIndices.push_back(indexedTypes.index());
115 if (!vectorNumBits.empty()) {
119 auto *minVal = llvm::min_element(vectorNumBits);
122 if (llvm::any_of(vectorNumBits,
123 [&](
int bits) {
return bits % *minVal != 0; }))
128 int index = vectorIndices[std::distance(vectorNumBits.begin(), minVal)];
129 int baseNumBits = scalarNumBits[
index];
130 if (llvm::any_of(scalarNumBits,
131 [&](
int bits) {
return bits % baseNumBits != 0; }))
139 auto *minVal = llvm::min_element(scalarNumBits);
140 if (llvm::any_of(scalarNumBits,
141 [minVal](
int64_t bit) {
return bit % *minVal != 0; }))
143 return std::distance(scalarNumBits.begin(), minVal);
147 if (
auto va = dyn_cast<VectorType>(a)) {
148 auto vb = dyn_cast<VectorType>(
b);
149 return vb && va.getNumElements() * va.getElementTypeBitWidth() ==
150 vb.getNumElements() * vb.getElementTypeBitWidth();
169class ResourceAliasAnalysis {
173 explicit ResourceAliasAnalysis(Operation *);
177 bool shouldUnify(Operation *op)
const;
183 spirv::GlobalVariableOp
184 getCanonicalResource(
const Descriptor &descriptor)
const;
185 spirv::GlobalVariableOp
186 getCanonicalResource(spirv::GlobalVariableOp varOp)
const;
189 spirv::SPIRVType
getElementType(spirv::GlobalVariableOp varOp)
const;
194 void recordIfUnifiable(
const Descriptor &descriptor,
195 ArrayRef<spirv::GlobalVariableOp> resources);
211ResourceAliasAnalysis::ResourceAliasAnalysis(
Operation *root) {
219 for (
const auto &descriptorResource : aliasedResources) {
220 recordIfUnifiable(descriptorResource.first, descriptorResource.second);
224bool ResourceAliasAnalysis::shouldUnify(Operation *op)
const {
228 if (
auto varOp = dyn_cast<spirv::GlobalVariableOp>(op)) {
229 auto canonicalOp = getCanonicalResource(varOp);
230 return canonicalOp && varOp != canonicalOp;
232 if (
auto addressOp = dyn_cast<spirv::AddressOfOp>(op)) {
233 auto moduleOp = addressOp->getParentOfType<spirv::ModuleOp>();
236 return shouldUnify(varOp);
239 if (
auto acOp = dyn_cast<spirv::AccessChainOp>(op))
240 return shouldUnify(acOp.getBasePtr().getDefiningOp());
241 if (
auto loadOp = dyn_cast<spirv::LoadOp>(op))
242 return shouldUnify(loadOp.getPtr().getDefiningOp());
243 if (
auto storeOp = dyn_cast<spirv::StoreOp>(op))
244 return shouldUnify(storeOp.getPtr().getDefiningOp());
249spirv::GlobalVariableOp ResourceAliasAnalysis::getCanonicalResource(
251 auto varIt = canonicalResourceMap.find(descriptor);
252 if (varIt == canonicalResourceMap.end())
254 return varIt->second;
257spirv::GlobalVariableOp ResourceAliasAnalysis::getCanonicalResource(
258 spirv::GlobalVariableOp varOp)
const {
259 auto descriptorIt = descriptorMap.find(varOp);
260 if (descriptorIt == descriptorMap.end())
262 return getCanonicalResource(descriptorIt->second);
266ResourceAliasAnalysis::getElementType(spirv::GlobalVariableOp varOp)
const {
267 auto it = elementTypeMap.find(varOp);
268 if (it == elementTypeMap.end())
273void ResourceAliasAnalysis::recordIfUnifiable(
274 const Descriptor &descriptor, ArrayRef<spirv::GlobalVariableOp> resources) {
276 SmallVector<spirv::SPIRVType> elementTypes;
277 for (spirv::GlobalVariableOp resource : resources) {
282 auto type = cast<spirv::SPIRVType>(elementType);
283 if (!type.isScalarOrVector())
286 elementTypes.push_back(type);
294 resourceMap[descriptor].assign(resources.begin(), resources.end());
295 canonicalResourceMap[descriptor] = resources[*index];
296 for (
const auto &resource : llvm::enumerate(resources)) {
297 descriptorMap[resource.value()] = descriptor;
298 elementTypeMap[resource.value()] = elementTypes[resource.index()];
306template <
typename OpTy>
322 ConversionPatternRewriter &rewriter)
const override {
325 rewriter.eraseOp(varOp);
335 ConversionPatternRewriter &rewriter)
const override {
337 auto moduleOp = addressOp->getParentOfType<spirv::ModuleOp>();
338 auto srcVarOp = cast<spirv::GlobalVariableOp>(
340 auto dstVarOp =
analysis.getCanonicalResource(srcVarOp);
341 rewriter.replaceOpWithNewOp<spirv::AddressOfOp>(addressOp, dstVarOp);
351 ConversionPatternRewriter &rewriter)
const override {
352 auto addressOp = acOp.getBasePtr().getDefiningOp<spirv::AddressOfOp>();
354 return rewriter.notifyMatchFailure(acOp,
"base ptr not addressof op");
356 auto moduleOp = acOp->getParentOfType<spirv::ModuleOp>();
357 auto srcVarOp = cast<spirv::GlobalVariableOp>(
359 auto dstVarOp =
analysis.getCanonicalResource(srcVarOp);
364 if (srcElemType == dstElemType ||
368 rewriter.replaceOpWithNewOp<spirv::AccessChainOp>(
369 acOp, adaptor.getBasePtr(), adaptor.getIndices());
375 if (srcElemType.
isIntOrFloat() && isa<VectorType>(dstElemType)) {
382 if (!srcBytes || !dstBytes)
383 return rewriter.notifyMatchFailure(acOp,
"unknown element byte size");
384 int srcNumBytes = *srcBytes;
385 int dstNumBytes = *dstBytes;
386 assert(dstNumBytes >= srcNumBytes && dstNumBytes % srcNumBytes == 0);
388 auto indices = llvm::to_vector<4>(acOp.getIndices());
392 int ratio = dstNumBytes / srcNumBytes;
393 auto ratioValue = spirv::ConstantOp::create(
394 rewriter, loc, indexType, rewriter.getIntegerAttr(indexType, ratio));
397 spirv::SDivOp::create(rewriter, loc, indexType, oldIndex, ratioValue);
398 indices.push_back(spirv::SModOp::create(rewriter, loc, indexType,
399 oldIndex, ratioValue));
401 rewriter.replaceOpWithNewOp<spirv::AccessChainOp>(
402 acOp, adaptor.getBasePtr(),
indices);
407 (isa<VectorType>(srcElemType) && isa<VectorType>(dstElemType))) {
413 if (!srcBytes || !dstBytes)
414 return rewriter.notifyMatchFailure(acOp,
"unknown element byte size");
415 int srcNumBytes = *srcBytes;
416 int dstNumBytes = *dstBytes;
417 assert(srcNumBytes >= dstNumBytes && srcNumBytes % dstNumBytes == 0);
419 auto indices = llvm::to_vector<4>(acOp.getIndices());
423 int ratio = srcNumBytes / dstNumBytes;
424 auto ratioValue = spirv::ConstantOp::create(
425 rewriter, loc, indexType, rewriter.getIntegerAttr(indexType, ratio));
428 spirv::IMulOp::create(rewriter, loc, indexType, oldIndex, ratioValue);
430 rewriter.replaceOpWithNewOp<spirv::AccessChainOp>(
431 acOp, adaptor.getBasePtr(),
indices);
435 return rewriter.notifyMatchFailure(
436 acOp,
"unsupported src/dst types for spirv.AccessChain");
445 ConversionPatternRewriter &rewriter)
const override {
446 auto srcPtrType = cast<spirv::PointerType>(loadOp.getPtr().getType());
447 auto srcElemType = cast<spirv::SPIRVType>(srcPtrType.getPointeeType());
448 auto dstPtrType = cast<spirv::PointerType>(adaptor.getPtr().getType());
449 auto dstElemType = cast<spirv::SPIRVType>(dstPtrType.getPointeeType());
452 auto newLoadOp = spirv::LoadOp::create(rewriter, loc, adaptor.getPtr());
453 if (srcElemType == dstElemType) {
454 rewriter.replaceOp(loadOp, newLoadOp->getResults());
459 auto castOp = spirv::BitcastOp::create(rewriter, loc, srcElemType,
460 newLoadOp.getValue());
461 rewriter.replaceOp(loadOp, castOp->getResults());
466 if ((srcElemType.isIntOrFloat() && dstElemType.isIntOrFloat()) ||
467 (isa<VectorType>(srcElemType) && isa<VectorType>(dstElemType))) {
472 std::optional<int64_t> srcBytes = srcElemType.getSizeInBytes();
473 std::optional<int64_t> dstBytes = dstElemType.getSizeInBytes();
474 if (!srcBytes || !dstBytes)
475 return rewriter.notifyMatchFailure(loadOp,
"unknown element byte size");
476 int srcNumBytes = *srcBytes;
477 int dstNumBytes = *dstBytes;
478 assert(srcNumBytes > dstNumBytes && srcNumBytes % dstNumBytes == 0);
479 int ratio = srcNumBytes / dstNumBytes;
481 return rewriter.notifyMatchFailure(loadOp,
"more than 4 components");
484 components.reserve(ratio);
485 components.push_back(newLoadOp);
487 auto acOp = adaptor.getPtr().getDefiningOp<spirv::AccessChainOp>();
489 return rewriter.notifyMatchFailure(loadOp,
"ptr not spirv.AccessChain");
491 auto i32Type = rewriter.getI32Type();
492 Value oneValue = spirv::ConstantOp::getOne(i32Type, loc, rewriter);
493 auto indices = llvm::to_vector<4>(acOp.getIndices());
494 for (
int i = 1; i < ratio; ++i) {
496 indices.back() = spirv::IAddOp::create(rewriter, loc, i32Type,
498 auto componentAcOp = spirv::AccessChainOp::create(
499 rewriter, loc, acOp.getBasePtr(),
indices);
502 components.push_back(
503 spirv::LoadOp::create(rewriter, loc, componentAcOp));
511 Type vectorType = srcElemType;
512 if (!isa<VectorType>(srcElemType))
513 vectorType = VectorType::get({ratio}, dstElemType);
517 if (
auto srcElemVecType = dyn_cast<VectorType>(srcElemType))
518 if (
auto dstElemVecType = dyn_cast<VectorType>(dstElemType)) {
519 if (srcElemVecType.getElementType() !=
520 dstElemVecType.getElementType()) {
522 dstNumBytes / (srcElemVecType.getElementTypeBitWidth() / 8);
526 Type castType = srcElemVecType.getElementType();
528 castType = VectorType::get({count}, castType);
530 for (
Value &c : components)
531 c = spirv::BitcastOp::create(rewriter, loc, castType, c);
534 Value vectorValue = spirv::CompositeConstructOp::create(
535 rewriter, loc, vectorType, components);
537 if (!isa<VectorType>(srcElemType))
539 spirv::BitcastOp::create(rewriter, loc, srcElemType, vectorValue);
540 rewriter.replaceOp(loadOp, vectorValue);
544 return rewriter.notifyMatchFailure(
545 loadOp,
"unsupported src/dst types for spirv.Load");
554 ConversionPatternRewriter &rewriter)
const override {
556 cast<spirv::PointerType>(storeOp.getPtr().getType()).getPointeeType();
558 cast<spirv::PointerType>(adaptor.getPtr().getType()).getPointeeType();
560 Value value = adaptor.getValue();
561 auto srcVector = dyn_cast<VectorType>(srcElemType);
562 auto dstVector = dyn_cast<VectorType>(dstElemType);
563 if (srcVector && dstVector && srcVector != dstVector) {
564 if (srcVector.getElementTypeBitWidth() !=
565 dstVector.getElementTypeBitWidth() ||
566 srcVector.getNumElements() % dstVector.getNumElements() != 0)
567 return rewriter.notifyMatchFailure(storeOp,
568 "incompatible vector types");
569 auto acOp = adaptor.getPtr().getDefiningOp<spirv::AccessChainOp>();
571 return rewriter.notifyMatchFailure(storeOp,
572 "ptr not spirv.AccessChain");
573 if (srcVector.getElementType() != dstVector.getElementType())
574 value = spirv::BitcastOp::create(
576 VectorType::get(srcVector.getShape(), dstVector.getElementType()),
578 unsigned count = dstVector.getNumElements();
579 unsigned ratio = srcVector.getNumElements() / count;
580 unsigned bytes = count * dstVector.getElementTypeBitWidth() / 8;
585 auto getPart = [&](
unsigned i) ->
Value {
589 for (
unsigned j = 0;
j < count; ++
j)
590 components.push_back(i * count +
j);
591 return spirv::VectorShuffleOp::create(
592 rewriter, loc, dstVector, value, value,
593 rewriter.getI32ArrayAttr(components));
595 auto firstStore = spirv::StoreOp::create(
596 rewriter, loc, adaptor.getPtr(), getPart(0),
597 storeOp.getMemoryAccessAttr(), storeOp.getAlignmentAttr());
598 firstStore->setDiscardableAttrs(storeOp->getDiscardableAttrDictionary());
599 for (
unsigned i = 1; i < ratio; ++i) {
600 Value part = getPart(i);
603 auto offset = spirv::ConstantOp::create(
604 rewriter, loc, indexType, rewriter.getIntegerAttr(indexType, i));
605 indices.back() = spirv::IAddOp::create(rewriter, loc, indexType,
607 Value ptr = spirv::AccessChainOp::create(rewriter, loc,
609 IntegerAttr alignment = storeOp.getAlignmentAttr();
611 alignment = rewriter.getI32IntegerAttr(
612 llvm::commonAlignment(llvm::Align(alignment.getInt()), i * bytes)
614 auto store = spirv::StoreOp::create(
615 rewriter, loc,
ptr, part, storeOp.getMemoryAccessAttr(), alignment);
616 store->setDiscardableAttrs(storeOp->getDiscardableAttrDictionary());
618 rewriter.eraseOp(storeOp);
621 if (srcElemType != dstElemType) {
622 if (!srcElemType.isIntOrFloat() || !dstElemType.isIntOrFloat())
623 return rewriter.notifyMatchFailure(storeOp,
"not scalar type");
625 return rewriter.notifyMatchFailure(storeOp,
"different bitwidth");
626 value = spirv::BitcastOp::create(rewriter, loc, dstElemType, value);
628 auto newStore = rewriter.replaceOpWithNewOp<spirv::StoreOp>(
629 storeOp, adaptor.getPtr(), value, storeOp.getMemoryAccessAttr(),
630 storeOp.getAlignmentAttr());
631 newStore->setDiscardableAttrs(storeOp->getDiscardableAttrDictionary());
641class UnifyAliasedResourcePass final
642 :
public spirv::impl::SPIRVUnifyAliasedResourcePassBase<
643 UnifyAliasedResourcePass> {
646 : getTargetEnvFn(std::move(getTargetEnv)) {}
648 void runOnOperation()
override;
654void UnifyAliasedResourcePass::runOnOperation() {
655 spirv::ModuleOp moduleOp = getOperation();
658 if (getTargetEnvFn) {
662 spirv::TargetEnvAttr targetEnv = getTargetEnvFn(moduleOp);
664 bool isVulkanOnAppleDevices =
665 clientAPI == spirv::ClientAPI::Vulkan &&
667 if (clientAPI != spirv::ClientAPI::WebGPU &&
668 clientAPI != spirv::ClientAPI::Metal && !isVulkanOnAppleDevices)
673 ResourceAliasAnalysis &
analysis = getAnalysis<ResourceAliasAnalysis>();
675 ConversionTarget
target(*context);
676 target.addDynamicallyLegalOp<spirv::GlobalVariableOp, spirv::AddressOfOp,
677 spirv::AccessChainOp, spirv::LoadOp,
680 target.addLegalDialect<spirv::SPIRVDialect>();
683 RewritePatternSet patterns(context);
684 patterns.add<ConvertVariable, ConvertAddressOf, ConvertAccessChain,
685 ConvertLoad, ConvertStore>(
analysis, context);
686 if (
failed(applyPartialConversion(moduleOp,
target, std::move(patterns))))
687 return signalPassFailure();
694 for (
const auto &dr : resourceMap) {
695 const auto &resources = dr.second;
696 if (resources.size() == 1)
697 resources.front()->removeDiscardableAttr(
"aliased");
702std::unique_ptr<mlir::OperationPass<spirv::ModuleOp>>
704 return std::make_unique<UnifyAliasedResourcePass>(std::move(getTargetEnv));
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
#define MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(CLASS_NAME)
static std::optional< int > deduceCanonicalResource(ArrayRef< spirv::SPIRVType > types)
Given a list of resource element types, returns the index of the canonical resource that all resource...
DenseMap< Descriptor, SmallVector< spirv::GlobalVariableOp > > AliasedResourceMap
static AliasedResourceMap collectAliasedResources(spirv::ModuleOp moduleOp)
Collects all aliased resources in the given SPIR-V moduleOp.
static Type getRuntimeArrayElementType(Type type)
Returns the element type if the given type is a runtime array resource: !spirv.ptr<!...
static bool areSameBitwidthScalarOrVectorType(Type a, Type b)
std::pair< uint32_t, uint32_t > Descriptor
ConvertAliasResource(const ResourceAliasAnalysis &analysis, MLIRContext *context, PatternBenefit benefit=1)
const ResourceAliasAnalysis & analysis
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.
Operation is the basic unit of execution within MLIR.
This class represents the benefit of a pattern match in a unitless scheme that ranges from 0 (very li...
static Operation * lookupSymbolIn(Operation *op, StringAttr symbol)
Returns the operation registered with the given symbol name with the regions of 'symbolTableOp'.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
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.
std::optional< int64_t > getSizeInBytes()
Returns the size in bytes for each type.
Vendor getVendorID() const
Returns the vendor ID.
ClientAPI getClientAPI() const
Returns the client API.
std::unique_ptr< OperationPass< spirv::ModuleOp > > createUnifyAliasedResourcePass(GetTargetEnvFn getTargetEnv=nullptr)
std::function< spirv::TargetEnvAttr(spirv::ModuleOp)> GetTargetEnvFn
Creates an operation pass that unifies access of multiple aliased resources into access of one single...
Include the generated interface declarations.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
ConvertAliasResource(const ResourceAliasAnalysis &analysis, MLIRContext *context, PatternBenefit benefit=1)
LogicalResult matchAndRewrite(spirv::AccessChainOp acOp, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override
ConvertAliasResource(const ResourceAliasAnalysis &analysis, MLIRContext *context, PatternBenefit benefit=1)
LogicalResult matchAndRewrite(spirv::AddressOfOp addressOp, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override
ConvertAliasResource(const ResourceAliasAnalysis &analysis, MLIRContext *context, PatternBenefit benefit=1)
LogicalResult matchAndRewrite(spirv::LoadOp loadOp, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override
ConvertAliasResource(const ResourceAliasAnalysis &analysis, MLIRContext *context, PatternBenefit benefit=1)
LogicalResult matchAndRewrite(spirv::StoreOp storeOp, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override
ConvertAliasResource(const ResourceAliasAnalysis &analysis, MLIRContext *context, PatternBenefit benefit=1)
LogicalResult matchAndRewrite(spirv::GlobalVariableOp varOp, OpAdaptor adaptor, ConversionPatternRewriter &rewriter) const override
Eliminates variable at the specified position using Fourier-Motzkin variable elimination.