MLIR 24.0.0git
MapMemRefStorageClassPass.cpp
Go to the documentation of this file.
1//===- MapMemRefStorageCLassPass.cpp --------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements a pass to map numeric MemRef memory spaces to
10// symbolic ones defined in the SPIR-V specification.
11//
12//===----------------------------------------------------------------------===//
13
15
21#include "mlir/IR/Attributes.h"
24#include "mlir/IR/Operation.h"
25#include "mlir/IR/Visitors.h"
27#include "llvm/ADT/SmallVectorExtras.h"
28#include "llvm/ADT/StringExtras.h"
29#include "llvm/Support/Debug.h"
30#include <optional>
31
32namespace mlir {
33#define GEN_PASS_DEF_MAPMEMREFSTORAGECLASS
34#include "mlir/Conversion/Passes.h.inc"
35} // namespace mlir
36
37#define DEBUG_TYPE "mlir-map-memref-storage-class"
38
39using namespace mlir;
40
41//===----------------------------------------------------------------------===//
42// Mappings
43//===----------------------------------------------------------------------===//
44
45/// Mapping between SPIR-V storage classes to memref memory spaces.
46///
47/// Note: memref does not have a defined semantics for each memory space; it
48/// depends on the context where it is used. There are no particular reasons
49/// behind the number assignments; we try to follow NVVM conventions and largely
50/// give common storage classes a smaller number.
51#define VULKAN_STORAGE_SPACE_MAP_LIST(MAP_FN) \
52 MAP_FN(spirv::StorageClass::StorageBuffer, 0) \
53 MAP_FN(spirv::StorageClass::Generic, 1) \
54 MAP_FN(spirv::StorageClass::Workgroup, 3) \
55 MAP_FN(spirv::StorageClass::Uniform, 4) \
56 MAP_FN(spirv::StorageClass::Private, 5) \
57 MAP_FN(spirv::StorageClass::Function, 6) \
58 MAP_FN(spirv::StorageClass::PushConstant, 7) \
59 MAP_FN(spirv::StorageClass::UniformConstant, 8) \
60 MAP_FN(spirv::StorageClass::Input, 9) \
61 MAP_FN(spirv::StorageClass::Output, 10) \
62 MAP_FN(spirv::StorageClass::PhysicalStorageBuffer, 11) \
63 MAP_FN(spirv::StorageClass::Image, 12)
64
65std::optional<spirv::StorageClass>
67 // Handle null memory space attribute specially.
68 if (!memorySpaceAttr)
69 return spirv::StorageClass::StorageBuffer;
70
71 // Unknown dialect custom attributes are not supported by default.
72 // Downstream callers should plug in more specialized ones.
73 auto intAttr = dyn_cast<IntegerAttr>(memorySpaceAttr);
74 if (!intAttr)
75 return std::nullopt;
76 // The integer may be signless, signed or unsigned and of any width; read
77 // the raw value instead of a typed accessor that asserts on a mismatch.
78 std::optional<uint64_t> memorySpace = intAttr.getValue().tryZExtValue();
79 if (!memorySpace)
80 return std::nullopt;
81
82#define STORAGE_SPACE_MAP_FN(storage, space) \
83 case space: \
84 return storage;
85
86 switch (*memorySpace) {
88 default:
89 break;
90 }
91 return std::nullopt;
92
93#undef STORAGE_SPACE_MAP_FN
94}
95
96std::optional<unsigned>
97spirv::mapVulkanStorageClassToMemorySpace(spirv::StorageClass storageClass) {
98#define STORAGE_SPACE_MAP_FN(storage, space) \
99 case storage: \
100 return space;
101
102 switch (storageClass) {
104 default:
105 break;
106 }
107 return std::nullopt;
108
109#undef STORAGE_SPACE_MAP_FN
110}
111
112#undef VULKAN_STORAGE_SPACE_MAP_LIST
113
114#define OPENCL_STORAGE_SPACE_MAP_LIST(MAP_FN) \
115 MAP_FN(spirv::StorageClass::CrossWorkgroup, 0) \
116 MAP_FN(spirv::StorageClass::Generic, 1) \
117 MAP_FN(spirv::StorageClass::Workgroup, 3) \
118 MAP_FN(spirv::StorageClass::UniformConstant, 4) \
119 MAP_FN(spirv::StorageClass::Private, 5) \
120 MAP_FN(spirv::StorageClass::Function, 6) \
121 MAP_FN(spirv::StorageClass::Image, 7)
122
123std::optional<spirv::StorageClass>
125 // Handle null memory space attribute specially.
126 if (!memorySpaceAttr)
127 return spirv::StorageClass::CrossWorkgroup;
128
129 // Unknown dialect custom attributes are not supported by default.
130 // Downstream callers should plug in more specialized ones.
131 auto intAttr = dyn_cast<IntegerAttr>(memorySpaceAttr);
132 if (!intAttr)
133 return std::nullopt;
134 // The integer may be signless, signed or unsigned and of any width; read
135 // the raw value instead of a typed accessor that asserts on a mismatch.
136 std::optional<uint64_t> memorySpace = intAttr.getValue().tryZExtValue();
137 if (!memorySpace)
138 return std::nullopt;
139
140#define STORAGE_SPACE_MAP_FN(storage, space) \
141 case space: \
142 return storage;
143
144 switch (*memorySpace) {
146 default:
147 break;
148 }
149 return std::nullopt;
150
151#undef STORAGE_SPACE_MAP_FN
152}
153
154std::optional<unsigned>
155spirv::mapOpenCLStorageClassToMemorySpace(spirv::StorageClass storageClass) {
156#define STORAGE_SPACE_MAP_FN(storage, space) \
157 case storage: \
158 return space;
159
160 switch (storageClass) {
162 default:
163 break;
164 }
165 return std::nullopt;
166
167#undef STORAGE_SPACE_MAP_FN
168}
169
170#undef OPENCL_STORAGE_SPACE_MAP_LIST
171
172//===----------------------------------------------------------------------===//
173// Type Converter
174//===----------------------------------------------------------------------===//
175
177 const spirv::MemorySpaceToStorageClassMap &memorySpaceMap)
178 : memorySpaceMap(memorySpaceMap) {
179 // Pass through for all other types.
180 addConversion([](Type type) { return type; });
181
182 addConversion([this](BaseMemRefType memRefType) -> std::optional<Type> {
183 std::optional<spirv::StorageClass> storage =
184 this->memorySpaceMap(memRefType.getMemorySpace());
185 if (!storage) {
186 LLVM_DEBUG(llvm::dbgs()
187 << "cannot convert " << memRefType
188 << " due to being unable to find memory space in map\n");
189 return std::nullopt;
190 }
191
192 auto storageAttr =
193 spirv::StorageClassAttr::get(memRefType.getContext(), *storage);
194 if (auto rankedType = dyn_cast<MemRefType>(memRefType)) {
195 return MemRefType::get(memRefType.getShape(), memRefType.getElementType(),
196 rankedType.getLayout(), storageAttr);
197 }
198 return UnrankedMemRefType::get(memRefType.getElementType(), storageAttr);
199 });
200
201 addConversion([this](FunctionType type) {
202 auto inputs = llvm::map_to_vector(
203 type.getInputs(), [this](Type ty) { return convertType(ty); });
204 auto results = llvm::map_to_vector(
205 type.getResults(), [this](Type ty) { return convertType(ty); });
206 return FunctionType::get(type.getContext(), inputs, results);
207 });
208}
209
210//===----------------------------------------------------------------------===//
211// Conversion Target
212//===----------------------------------------------------------------------===//
213
214/// Returns true if the given `type` is considered as legal for SPIR-V
215/// conversion.
216static bool isLegalType(Type type) {
217 if (auto memRefType = dyn_cast<BaseMemRefType>(type)) {
218 Attribute spaceAttr = memRefType.getMemorySpace();
219 return isa_and_nonnull<spirv::StorageClassAttr>(spaceAttr);
220 }
221 return true;
222}
223
224/// Returns true if the given `attr` is considered as legal for SPIR-V
225/// conversion.
226static bool isLegalAttr(Attribute attr) {
227 if (auto typeAttr = dyn_cast<TypeAttr>(attr))
228 return isLegalType(typeAttr.getValue());
229 return true;
230}
231
232/// Returns true if the given `op` is considered as legal for SPIR-V conversion.
233static bool isLegalOp(Operation *op) {
234 if (auto funcOp = dyn_cast<FunctionOpInterface>(op)) {
235 return llvm::all_of(funcOp.getArgumentTypes(), isLegalType) &&
236 llvm::all_of(funcOp.getResultTypes(), isLegalType) &&
237 llvm::all_of(funcOp.getFunctionBody().getArgumentTypes(),
239 }
240
241 auto attrs = llvm::map_range(
242 op->getDiscardableAttrDictionary().getValue(),
243 [](const NamedAttribute &attr) { return attr.getValue(); });
244
245 return llvm::all_of(op->getOperandTypes(), isLegalType) &&
246 llvm::all_of(op->getResultTypes(), isLegalType) &&
247 llvm::all_of(attrs, isLegalAttr);
248}
249
250std::unique_ptr<ConversionTarget>
252 auto target = std::make_unique<ConversionTarget>(context);
253 target->markUnknownOpDynamicallyLegal(isLegalOp);
254 return target;
255}
256
258 Operation *op, MemorySpaceToStorageClassConverter &typeConverter) {
259 AttrTypeReplacer replacer;
260 replacer.addReplacement([&typeConverter](BaseMemRefType origType)
261 -> std::optional<BaseMemRefType> {
262 return typeConverter.convertType<BaseMemRefType>(origType);
263 });
264
265 replacer.recursivelyReplaceElementsIn(op, /*replaceAttrs=*/true,
266 /*replaceLocs=*/false,
267 /*replaceTypes=*/true);
268}
269
270//===----------------------------------------------------------------------===//
271// Conversion Pass
272//===----------------------------------------------------------------------===//
273
274namespace {
275class MapMemRefStorageClassPass final
276 : public impl::MapMemRefStorageClassBase<MapMemRefStorageClassPass> {
277public:
278 MapMemRefStorageClassPass() = default;
279
280 explicit MapMemRefStorageClassPass(
281 const spirv::MemorySpaceToStorageClassMap &memorySpaceMap)
282 : memorySpaceMap(memorySpaceMap) {}
283
284 LogicalResult initializeOptions(
285 StringRef options,
286 function_ref<LogicalResult(const Twine &)> errorHandler) override {
287 if (failed(Pass::initializeOptions(options, errorHandler)))
288 return failure();
289
290 if (clientAPI == "opencl")
292 else if (clientAPI != "vulkan")
293 return errorHandler(llvm::Twine("Invalid clienAPI: ") + clientAPI);
294
295 return success();
296 }
297
298 void runOnOperation() override {
299 MLIRContext *context = &getContext();
300 Operation *op = getOperation();
301
302 spirv::MemorySpaceToStorageClassMap spaceToStorage = memorySpaceMap;
303 if (spirv::TargetEnvAttr attr = spirv::lookupTargetEnv(op)) {
304 spirv::TargetEnv targetEnv(attr);
305 if (targetEnv.allows(spirv::Capability::Kernel)) {
307 } else if (targetEnv.allows(spirv::Capability::Shader)) {
309 }
310 }
311
312 spirv::MemorySpaceToStorageClassConverter converter(spaceToStorage);
313 // Perform the replacement.
315
316 // Check if there are any illegal ops remaining.
317 std::unique_ptr<ConversionTarget> target =
319 op->walk([&target, this](Operation *childOp) {
320 if (target->isIllegal(childOp)) {
321 childOp->emitOpError("failed to legalize memory space");
322 signalPassFailure();
323 return WalkResult::interrupt();
324 }
325 return WalkResult::advance();
326 });
327 }
328
329private:
332};
333} // namespace
334
335std::unique_ptr<OperationPass<>> mlir::createMapMemRefStorageClassPass() {
336 return std::make_unique<MapMemRefStorageClassPass>();
337}
return success()
b getContext())
static bool isLegalType(Type type)
Returns true if the given type is considered as legal for SPIR-V conversion.
#define STORAGE_SPACE_MAP_FN(storage, space)
static bool isLegalAttr(Attribute attr)
Returns true if the given attr is considered as legal for SPIR-V conversion.
#define OPENCL_STORAGE_SPACE_MAP_LIST(MAP_FN)
#define VULKAN_STORAGE_SPACE_MAP_LIST(MAP_FN)
Mapping between SPIR-V storage classes to memref memory spaces.
static bool isLegalOp(Operation *op)
Returns true if the given op is considered as legal for SPIR-V conversion.
static llvm::ManagedStatic< PassManagerOptions > options
This is an attribute/type replacer that is naively cached.
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class provides a shared interface for ranked and unranked memref types.
ArrayRef< int64_t > getShape() const
Returns the shape of this memref type.
Attribute getMemorySpace() const
Returns the memory space in which data referred to by this memref resides.
Type getElementType() const
Returns the element type of this memref type.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
NamedAttribute represents a combination of a name and an Attribute value.
Definition Attributes.h:166
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
Definition Operation.h:555
operand_type_range getOperandTypes()
Definition Operation.h:424
result_type_range getResultTypes()
Definition Operation.h:455
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Definition Operation.h:851
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
virtual LogicalResult initializeOptions(StringRef options, function_ref< LogicalResult(const Twine &)> errorHandler)
Attempt to initialize the options of this pass from the given string.
Definition Pass.cpp:66
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
static WalkResult advance()
Definition WalkResult.h:47
static WalkResult interrupt()
Definition WalkResult.h:46
void recursivelyReplaceElementsIn(Operation *op, bool replaceAttrs=true, bool replaceLocs=false, bool replaceTypes=false)
Replace the elements within the given operation, and all nested operations.
void addReplacement(ReplaceFn< Attribute > fn)
AttrTypeReplacerBase.
Type converter for converting numeric MemRef memory spaces into SPIR-V symbolic ones.
MemorySpaceToStorageClassConverter(const MemorySpaceToStorageClassMap &memorySpaceMap)
std::unique_ptr< ConversionTarget > getMemorySpaceToStorageClassTarget(MLIRContext &)
Creates the target that populates legality of ops with MemRef types.
TargetEnvAttr lookupTargetEnv(Operation *op)
Queries the target environment recursively from enclosing symbol table ops containing the given op.
void convertMemRefTypesAndAttrs(Operation *op, MemorySpaceToStorageClassConverter &typeConverter)
Converts all MemRef types and attributes in the op, as decided by the typeConverter.
std::optional< spirv::StorageClass > mapMemorySpaceToOpenCLStorageClass(Attribute)
Maps MemRef memory spaces to storage classes for OpenCL-flavored SPIR-V using the default rule.
std::optional< unsigned > mapVulkanStorageClassToMemorySpace(spirv::StorageClass)
Maps storage classes for Vulkan-flavored SPIR-V to MemRef memory spaces using the default rule.
std::function< std::optional< spirv::StorageClass >(Attribute)> MemorySpaceToStorageClassMap
Mapping from numeric MemRef memory spaces into SPIR-V symbolic ones.
std::optional< unsigned > mapOpenCLStorageClassToMemorySpace(spirv::StorageClass)
Maps storage classes for OpenCL-flavored SPIR-V to MemRef memory spaces using the default rule.
std::optional< spirv::StorageClass > mapMemorySpaceToVulkanStorageClass(Attribute)
Maps MemRef memory spaces to storage classes for Vulkan-flavored SPIR-V using the default rule.
Include the generated interface declarations.
std::unique_ptr< OperationPass<> > createMapMemRefStorageClassPass()
Creates a pass to map numeric MemRef memory spaces to symbolic SPIR-V storage classes.
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155