MLIR 24.0.0git
SPIRVConversion.cpp
Go to the documentation of this file.
1//===- SPIRVConversion.cpp - SPIR-V Conversion Utilities ------------------===//
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 utilities used to lower to SPIR-V dialect.
10//
11//===----------------------------------------------------------------------===//
12
26#include "mlir/IR/Operation.h"
28#include "mlir/Support/LLVM.h"
31#include "llvm/ADT/APInt.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/StringExtras.h"
35#include "llvm/Support/CheckedArithmetic.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/MathExtras.h"
38
39#include <optional>
40
41#define DEBUG_TYPE "mlir-spirv-conversion"
42
43using namespace mlir;
44
45namespace {
46
47//===----------------------------------------------------------------------===//
48// Utility functions
49//===----------------------------------------------------------------------===//
50
51static std::optional<SmallVector<int64_t>> getTargetShape(VectorType vecType) {
52 LLVM_DEBUG(llvm::dbgs() << "Get target shape\n");
53 if (vecType.isScalable()) {
54 LLVM_DEBUG(llvm::dbgs()
55 << "--scalable vectors are not supported -> BAIL\n");
56 return std::nullopt;
57 }
58 if (vecType.getRank() == 0) {
59 LLVM_DEBUG(llvm::dbgs() << "--0-D vectors are not supported -> BAIL\n");
60 return std::nullopt;
61 }
62 SmallVector<int64_t> unrollShape = llvm::to_vector<4>(vecType.getShape());
63 std::optional<SmallVector<int64_t>> targetShape = SmallVector<int64_t>(
64 1, mlir::spirv::getComputeVectorSize(vecType.getShape().back()));
65 if (!targetShape) {
66 LLVM_DEBUG(llvm::dbgs() << "--no unrolling target shape defined\n");
67 return std::nullopt;
68 }
69 auto maybeShapeRatio = computeShapeRatio(unrollShape, *targetShape);
70 if (!maybeShapeRatio) {
71 LLVM_DEBUG(llvm::dbgs()
72 << "--could not compute integral shape ratio -> BAIL\n");
73 return std::nullopt;
74 }
75 if (llvm::all_of(*maybeShapeRatio, [](int64_t v) { return v == 1; })) {
76 LLVM_DEBUG(llvm::dbgs() << "--no unrolling needed -> SKIP\n");
77 return std::nullopt;
78 }
79 LLVM_DEBUG(llvm::dbgs()
80 << "--found an integral shape ratio to unroll to -> SUCCESS\n");
81 return targetShape;
82}
83
84/// Checks that `candidates` extension requirements are possible to be satisfied
85/// with the given `targetEnv`.
86///
87/// `candidates` is a vector of vector for extension requirements following
88/// ((Extension::A OR Extension::B) AND (Extension::C OR Extension::D))
89/// convention.
90template <typename LabelT>
91static LogicalResult checkExtensionRequirements(
92 LabelT label, const spirv::TargetEnv &targetEnv,
94 for (const auto &ors : candidates) {
95 if (targetEnv.allows(ors))
96 continue;
97
98 LLVM_DEBUG({
99 SmallVector<StringRef> extStrings;
100 for (spirv::Extension ext : ors)
101 extStrings.push_back(spirv::stringifyExtension(ext));
102
103 llvm::dbgs() << label << " illegal: requires at least one extension in ["
104 << llvm::join(extStrings, ", ")
105 << "] but none allowed in target environment\n";
106 });
107 return failure();
108 }
109 return success();
110}
111
112/// Checks that `candidates`capability requirements are possible to be satisfied
113/// with the given `isAllowedFn`.
114///
115/// `candidates` is a vector of vector for capability requirements following
116/// ((Capability::A OR Capability::B) AND (Capability::C OR Capability::D))
117/// convention.
118template <typename LabelT>
119static LogicalResult checkCapabilityRequirements(
120 LabelT label, const spirv::TargetEnv &targetEnv,
122 for (const auto &ors : candidates) {
123 if (targetEnv.allows(ors))
124 continue;
125
126 LLVM_DEBUG({
127 SmallVector<StringRef> capStrings;
128 for (spirv::Capability cap : ors)
129 capStrings.push_back(spirv::stringifyCapability(cap));
130
131 llvm::dbgs() << label << " illegal: requires at least one capability in ["
132 << llvm::join(capStrings, ", ")
133 << "] but none allowed in target environment\n";
134 });
135 return failure();
136 }
137 return success();
138}
139
140/// Returns true if the given `storageClass` needs explicit layout when used in
141/// Shader environments.
142static bool needsExplicitLayout(spirv::StorageClass storageClass) {
143 switch (storageClass) {
144 case spirv::StorageClass::PhysicalStorageBuffer:
145 case spirv::StorageClass::PushConstant:
146 case spirv::StorageClass::StorageBuffer:
147 case spirv::StorageClass::Uniform:
148 return true;
149 default:
150 return false;
151 }
152}
153
154/// Wraps the given `elementType` in a struct and gets the pointer to the
155/// struct. This is used to satisfy Vulkan interface requirements.
157wrapInStructAndGetPointer(Type elementType, spirv::StorageClass storageClass) {
158 auto structType = needsExplicitLayout(storageClass)
159 ? spirv::StructType::get(elementType, /*offsetInfo=*/0)
160 : spirv::StructType::get(elementType);
161 return spirv::PointerType::get(structType, storageClass);
162}
163
164//===----------------------------------------------------------------------===//
165// Type Conversion
166//===----------------------------------------------------------------------===//
167
168static spirv::ScalarType getIndexType(MLIRContext *ctx,
170 return cast<spirv::ScalarType>(
171 IntegerType::get(ctx, options.use64bitIndex ? 64 : 32));
172}
173
174// TODO: This is a utility function that should probably be exposed by the
175// SPIR-V dialect. Keeping it local till the use case arises.
176static std::optional<int64_t>
177getTypeNumBytes(const SPIRVConversionOptions &options, Type type) {
178 if (isa<spirv::ScalarType>(type)) {
179 auto bitWidth = type.getIntOrFloatBitWidth();
180 // According to the SPIR-V spec:
181 // "There is no physical size or bit pattern defined for values with boolean
182 // type. If they are stored (in conjunction with OpVariable), they can only
183 // be used with logical addressing operations, not physical, and only with
184 // non-externally visible shader Storage Classes: Workgroup, CrossWorkgroup,
185 // Private, Function, Input, and Output."
186 if (bitWidth < 8)
187 return std::nullopt;
188 return bitWidth / 8;
189 }
190
191 // Handle 8-bit floats.
192 if (options.emulateUnsupportedFloatTypes && isa<FloatType>(type)) {
193 auto bitWidth = type.getIntOrFloatBitWidth();
194 if (bitWidth == 8)
195 return bitWidth / 8;
196 return std::nullopt;
197 }
198
199 if (auto complexType = dyn_cast<ComplexType>(type)) {
200 auto elementSize = getTypeNumBytes(options, complexType.getElementType());
201 if (!elementSize)
202 return std::nullopt;
203 return 2 * *elementSize;
204 }
205
206 if (auto vecType = dyn_cast<VectorType>(type)) {
207 auto elementSize = getTypeNumBytes(options, vecType.getElementType());
208 if (!elementSize)
209 return std::nullopt;
210 return vecType.getNumElements() * *elementSize;
211 }
212
213 if (auto memRefType = dyn_cast<MemRefType>(type)) {
214 // TODO: Layout should also be controlled by the ABI attributes. For now
215 // using the layout from MemRef.
216 int64_t offset;
218 if (!memRefType.hasStaticShape() ||
219 failed(memRefType.getStridesAndOffset(strides, offset)))
220 return std::nullopt;
221
222 // To get the size of the memref object in memory, the total size is the
223 // max(stride * dimension-size) computed for all dimensions times the size
224 // of the element.
225 auto elementSize = getTypeNumBytes(options, memRefType.getElementType());
226 if (!elementSize)
227 return std::nullopt;
228
229 if (memRefType.getRank() == 0)
230 return elementSize;
231
232 auto dims = memRefType.getShape();
233 if (llvm::is_contained(dims, ShapedType::kDynamic) ||
234 ShapedType::isDynamic(offset) ||
235 llvm::is_contained(strides, ShapedType::kDynamic))
236 return std::nullopt;
237
238 int64_t memrefSize = -1;
239 for (const auto &shape : enumerate(dims))
240 memrefSize = std::max(memrefSize, shape.value() * strides[shape.index()]);
241
242 return (offset + memrefSize) * *elementSize;
243 }
244
245 if (auto tensorType = dyn_cast<TensorType>(type)) {
246 if (!tensorType.hasStaticShape())
247 return std::nullopt;
248
249 auto elementSize = getTypeNumBytes(options, tensorType.getElementType());
250 if (!elementSize)
251 return std::nullopt;
252
253 int64_t size = *elementSize;
254 for (auto shape : tensorType.getShape())
255 size *= shape;
256
257 return size;
258 }
259
260 // TODO: Add size computation for other types.
261 return std::nullopt;
262}
263
264/// Returns whether the target environment supports a scalar type.
265static bool
266isScalarTypeSupported(const spirv::TargetEnv &targetEnv, spirv::ScalarType type,
267 std::optional<spirv::StorageClass> storageClass = {}) {
268 // Get extension and capability requirements for the given type.
271 type.getExtensions(extensions, storageClass);
272 type.getCapabilities(capabilities, storageClass);
273
274 return succeeded(
275 checkCapabilityRequirements(type, targetEnv, capabilities)) &&
276 succeeded(checkExtensionRequirements(type, targetEnv, extensions));
277}
278
279/// Converts a scalar `type` to a suitable type under the given `targetEnv`.
280static Type
281convertScalarType(const spirv::TargetEnv &targetEnv,
283 std::optional<spirv::StorageClass> storageClass = {}) {
284 if (isScalarTypeSupported(targetEnv, type, storageClass))
285 return type;
286
287 // These formats need explicit encoding or packing to emulate. Widening them
288 // to a 32-bit scalar would change their representation.
289 if (isa<Float4E2M1FNType, Float6E2M3FNType, Float6E3M2FNType>(type))
290 return nullptr;
291
292 // Otherwise we need to adjust the type, which really means adjusting the
293 // bitwidth given this is a scalar type.
294 if (!options.emulateLT32BitScalarTypes)
295 return nullptr;
296
297 // We only emulate narrower scalar types here and do not truncate results.
298 if (type.getIntOrFloatBitWidth() > 32) {
299 LLVM_DEBUG(llvm::dbgs()
300 << type
301 << " not converted to 32-bit for SPIR-V to avoid truncation\n");
302 return nullptr;
303 }
304
305 if (auto floatType = dyn_cast<FloatType>(type)) {
306 LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n");
307 return Builder(targetEnv.getContext()).getF32Type();
308 }
309
310 auto intType = cast<IntegerType>(type);
311 LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n");
312 return IntegerType::get(targetEnv.getContext(), /*width=*/32,
313 intType.getSignedness());
314}
315
316/// Converts a sub-byte integer `type` to i32 regardless of target environment.
317/// Returns a nullptr for unsupported integer types, including non sub-byte
318/// types.
319///
320/// Note that we don't recognize sub-byte types in `spirv::ScalarType` and use
321/// the above given that these sub-byte types are not supported at all in
322/// SPIR-V; there are no compute/storage capability for them like other
323/// supported integer types.
324static Type convertSubByteIntegerType(const SPIRVConversionOptions &options,
325 IntegerType type) {
326 if (type.getWidth() > 8) {
327 LLVM_DEBUG(llvm::dbgs() << "not a subbyte type\n");
328 return nullptr;
329 }
330 if (options.subByteTypeStorage != SPIRVSubByteTypeStorage::Packed) {
331 LLVM_DEBUG(llvm::dbgs() << "unsupported sub-byte storage kind\n");
332 return nullptr;
333 }
334
335 if (!llvm::isPowerOf2_32(type.getWidth())) {
336 LLVM_DEBUG(llvm::dbgs()
337 << "unsupported non-power-of-two bitwidth in sub-byte" << type
338 << "\n");
339 return nullptr;
340 }
341
342 LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n");
343 return IntegerType::get(type.getContext(), /*width=*/32,
344 type.getSignedness());
345}
346
347/// Converts 8-bit float types to integer types with the same bit width.
348/// Returns a nullptr for unsupported 8-bit float types.
349static Type convert8BitFloatType(const SPIRVConversionOptions &options,
350 FloatType type) {
351 if (!options.emulateUnsupportedFloatTypes)
352 return nullptr;
353 // F8 types are converted to integer types with the same bit width.
354 if (isa<Float8E5M2Type, Float8E4M3Type, Float8E4M3FNType, Float8E5M2FNUZType,
355 Float8E4M3FNUZType, Float8E4M3B11FNUZType, Float8E3M4Type,
356 Float8E8M0FNUType>(type))
357 return IntegerType::get(type.getContext(), type.getWidth());
358 LLVM_DEBUG(llvm::dbgs() << "unsupported 8-bit float type: " << type << "\n");
359 return nullptr;
360}
361
362/// Returns a type with the same shape but with any 8-bit float element type
363/// converted to the same bit width integer type. This is a noop when the
364/// element type is not the 8-bit float type or emulation flag is set to false.
365static ShapedType
366convertShaped8BitFloatType(ShapedType type,
368 if (!options.emulateUnsupportedFloatTypes)
369 return type;
370 Type srcElementType = type.getElementType();
371 Type convertedElementType = nullptr;
372 // F8 types are converted to integer types with the same bit width.
373 if (isa<Float8E5M2Type, Float8E4M3Type, Float8E4M3FNType, Float8E5M2FNUZType,
374 Float8E4M3FNUZType, Float8E4M3B11FNUZType, Float8E3M4Type,
375 Float8E8M0FNUType>(srcElementType))
376 convertedElementType = IntegerType::get(
377 type.getContext(), srcElementType.getIntOrFloatBitWidth());
378
379 if (!convertedElementType)
380 return type;
381
382 return type.clone(convertedElementType);
383}
384
385/// Returns a type with the same shape but with any index element type converted
386/// to the matching integer type. This is a noop when the element type is not
387/// the index type.
388static ShapedType
389convertIndexElementType(ShapedType type,
391 Type indexType = dyn_cast<IndexType>(type.getElementType());
392 if (!indexType)
393 return type;
394
395 return type.clone(getIndexType(type.getContext(), options));
396}
397
398/// Converts a vector `type` to a suitable type under the given `targetEnv`.
399static Type
400convertVectorType(const spirv::TargetEnv &targetEnv,
401 const SPIRVConversionOptions &options, VectorType type,
402 std::optional<spirv::StorageClass> storageClass = {}) {
403 type = cast<VectorType>(convertIndexElementType(type, options));
404 type = cast<VectorType>(convertShaped8BitFloatType(type, options));
405 auto scalarType = dyn_cast_or_null<spirv::ScalarType>(type.getElementType());
406 if (!scalarType) {
407 // If this is not a spec allowed scalar type, try to handle sub-byte integer
408 // types.
409 auto intType = dyn_cast<IntegerType>(type.getElementType());
410 if (!intType) {
411 LLVM_DEBUG(llvm::dbgs()
412 << type
413 << " illegal: cannot convert non-scalar element type\n");
414 return nullptr;
415 }
416
417 Type elementType = convertSubByteIntegerType(options, intType);
418 if (!elementType)
419 return nullptr;
420
421 if (type.getRank() <= 1 && type.getNumElements() == 1)
422 return elementType;
423
424 if (type.getNumElements() > 4) {
425 LLVM_DEBUG(llvm::dbgs()
426 << type << " illegal: > 4-element unimplemented\n");
427 return nullptr;
428 }
429
430 return VectorType::get(type.getShape(), elementType);
431 }
432
433 if (type.getRank() <= 1 && type.getNumElements() == 1)
434 return convertScalarType(targetEnv, options, scalarType, storageClass);
435
437 LLVM_DEBUG(llvm::dbgs()
438 << type << " illegal: not a valid composite type\n");
439 return nullptr;
440 }
441
442 // Get extension and capability requirements for the given type.
445 cast<spirv::CompositeType>(type).getExtensions(extensions, storageClass);
446 cast<spirv::CompositeType>(type).getCapabilities(capabilities, storageClass);
447
448 // If all requirements are met, then we can accept this type as-is.
449 if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) &&
450 succeeded(checkExtensionRequirements(type, targetEnv, extensions)))
451 return type;
452
453 auto elementType =
454 convertScalarType(targetEnv, options, scalarType, storageClass);
455 if (elementType)
456 return VectorType::get(type.getShape(), elementType);
457 return nullptr;
458}
459
460static Type
461convertComplexType(const spirv::TargetEnv &targetEnv,
462 const SPIRVConversionOptions &options, ComplexType type,
463 std::optional<spirv::StorageClass> storageClass = {}) {
464 auto scalarType = dyn_cast_or_null<spirv::ScalarType>(type.getElementType());
465 if (!scalarType) {
466 LLVM_DEBUG(llvm::dbgs()
467 << type << " illegal: cannot convert non-scalar element type\n");
468 return nullptr;
469 }
470
471 auto elementType =
472 convertScalarType(targetEnv, options, scalarType, storageClass);
473 if (!elementType)
474 return nullptr;
475 if (elementType != type.getElementType()) {
476 LLVM_DEBUG(llvm::dbgs()
477 << type << " illegal: complex type emulation unsupported\n");
478 return nullptr;
479 }
480
481 return VectorType::get(2, elementType);
482}
483
484/// Converts a tensor `type` to a suitable type under the given `targetEnv`.
485///
486/// Note that this is mainly for lowering constant tensors. In SPIR-V one can
487/// create composite constants with OpConstantComposite to embed relative large
488/// constant values and use OpCompositeExtract and OpCompositeInsert to
489/// manipulate, like what we do for vectors.
490static Type convertTensorType(const spirv::TargetEnv &targetEnv,
492 TensorType type) {
493 // TODO: Handle dynamic shapes.
494 if (!type.hasStaticShape()) {
495 LLVM_DEBUG(llvm::dbgs()
496 << type << " illegal: dynamic shape unimplemented\n");
497 return nullptr;
498 }
499
500 type = cast<TensorType>(convertIndexElementType(type, options));
501 type = cast<TensorType>(convertShaped8BitFloatType(type, options));
502 auto scalarType = dyn_cast_or_null<spirv::ScalarType>(type.getElementType());
503 if (!scalarType) {
504 LLVM_DEBUG(llvm::dbgs()
505 << type << " illegal: cannot convert non-scalar element type\n");
506 return nullptr;
507 }
508
509 std::optional<int64_t> scalarSize = getTypeNumBytes(options, scalarType);
510 std::optional<int64_t> tensorSize = getTypeNumBytes(options, type);
511 if (!scalarSize || !tensorSize) {
512 LLVM_DEBUG(llvm::dbgs()
513 << type << " illegal: cannot deduce element count\n");
514 return nullptr;
515 }
516
517 int64_t arrayElemCount = *tensorSize / *scalarSize;
518 if (arrayElemCount == 0) {
519 LLVM_DEBUG(llvm::dbgs()
520 << type << " illegal: cannot handle zero-element tensors\n");
521 return nullptr;
522 }
523 if (arrayElemCount > std::numeric_limits<unsigned>::max()) {
524 LLVM_DEBUG(llvm::dbgs()
525 << type << " illegal: cannot fit tensor into target type\n");
526 return nullptr;
527 }
528
529 Type arrayElemType = convertScalarType(targetEnv, options, scalarType);
530 if (!arrayElemType)
531 return nullptr;
532 std::optional<int64_t> arrayElemSize =
533 getTypeNumBytes(options, arrayElemType);
534 if (!arrayElemSize) {
535 LLVM_DEBUG(llvm::dbgs()
536 << type << " illegal: cannot deduce converted element size\n");
537 return nullptr;
538 }
539
540 return spirv::ArrayType::get(arrayElemType, arrayElemCount);
541}
542
543static Type convertBoolMemrefType(const spirv::TargetEnv &targetEnv,
545 MemRefType type,
546 spirv::StorageClass storageClass) {
547 unsigned numBoolBits = options.boolNumBits;
548 if (numBoolBits != 8) {
549 LLVM_DEBUG(llvm::dbgs()
550 << "using non-8-bit storage for bool types unimplemented");
551 return nullptr;
552 }
553 auto elementType = dyn_cast<spirv::ScalarType>(
554 IntegerType::get(type.getContext(), numBoolBits));
555 if (!elementType)
556 return nullptr;
557 Type arrayElemType =
558 convertScalarType(targetEnv, options, elementType, storageClass);
559 if (!arrayElemType)
560 return nullptr;
561 std::optional<int64_t> arrayElemSize =
562 getTypeNumBytes(options, arrayElemType);
563 if (!arrayElemSize) {
564 LLVM_DEBUG(llvm::dbgs()
565 << type << " illegal: cannot deduce converted element size\n");
566 return nullptr;
567 }
568
569 if (!type.hasStaticShape()) {
570 // For OpenCL Kernel, dynamic shaped memrefs convert into a pointer pointing
571 // to the element.
572 if (targetEnv.allows(spirv::Capability::Kernel))
573 return spirv::PointerType::get(arrayElemType, storageClass);
574 int64_t stride = needsExplicitLayout(storageClass) ? *arrayElemSize : 0;
575 auto arrayType = spirv::RuntimeArrayType::get(arrayElemType, stride);
576 // For Vulkan we need extra wrapping struct and array to satisfy interface
577 // needs.
578 return wrapInStructAndGetPointer(arrayType, storageClass);
579 }
580
581 if (type.getNumElements() == 0) {
582 LLVM_DEBUG(llvm::dbgs()
583 << type << " illegal: zero-element memrefs are not supported\n");
584 return nullptr;
585 }
586
587 int64_t memrefSize = llvm::divideCeil(type.getNumElements() * numBoolBits, 8);
588 int64_t arrayElemCount = llvm::divideCeil(memrefSize, *arrayElemSize);
589 int64_t stride = needsExplicitLayout(storageClass) ? *arrayElemSize : 0;
590 auto arrayType = spirv::ArrayType::get(arrayElemType, arrayElemCount, stride);
591 if (targetEnv.allows(spirv::Capability::Kernel))
592 return spirv::PointerType::get(arrayType, storageClass);
593 return wrapInStructAndGetPointer(arrayType, storageClass);
594}
595
596static Type convertSubByteMemrefType(const spirv::TargetEnv &targetEnv,
598 MemRefType type,
599 spirv::StorageClass storageClass) {
600 IntegerType elementType = cast<IntegerType>(type.getElementType());
601 Type arrayElemType = convertSubByteIntegerType(options, elementType);
602 if (!arrayElemType)
603 return nullptr;
604 int64_t arrayElemSize = *getTypeNumBytes(options, arrayElemType);
605
606 if (!type.hasStaticShape()) {
607 // For OpenCL Kernel, dynamic shaped memrefs convert into a pointer pointing
608 // to the element.
609 if (targetEnv.allows(spirv::Capability::Kernel))
610 return spirv::PointerType::get(arrayElemType, storageClass);
611 int64_t stride = needsExplicitLayout(storageClass) ? arrayElemSize : 0;
612 auto arrayType = spirv::RuntimeArrayType::get(arrayElemType, stride);
613 // For Vulkan we need extra wrapping struct and array to satisfy interface
614 // needs.
615 return wrapInStructAndGetPointer(arrayType, storageClass);
616 }
617
618 if (type.getNumElements() == 0) {
619 LLVM_DEBUG(llvm::dbgs()
620 << type << " illegal: zero-element memrefs are not supported\n");
621 return nullptr;
622 }
623
624 int64_t memrefSize =
625 llvm::divideCeil(type.getNumElements() * elementType.getWidth(), 8);
626 int64_t arrayElemCount = llvm::divideCeil(memrefSize, arrayElemSize);
627 int64_t stride = needsExplicitLayout(storageClass) ? arrayElemSize : 0;
628 auto arrayType = spirv::ArrayType::get(arrayElemType, arrayElemCount, stride);
629 if (targetEnv.allows(spirv::Capability::Kernel))
630 return spirv::PointerType::get(arrayType, storageClass);
631 return wrapInStructAndGetPointer(arrayType, storageClass);
632}
633
634static spirv::Dim convertRank(int64_t rank) {
635 switch (rank) {
636 case 1:
637 return spirv::Dim::Dim1D;
638 case 2:
639 return spirv::Dim::Dim2D;
640 case 3:
641 return spirv::Dim::Dim3D;
642 default:
643 llvm_unreachable("Invalid memref rank!");
644 }
645}
646
647static spirv::ImageFormat getImageFormat(Type elementType) {
648 return TypeSwitch<Type, spirv::ImageFormat>(elementType)
649 .Case([](Float16Type) { return spirv::ImageFormat::R16f; })
650 .Case([](Float32Type) { return spirv::ImageFormat::R32f; })
651 .Case([](IntegerType intType) {
652 auto const isSigned = intType.isSigned() || intType.isSignless();
653#define BIT_WIDTH_CASE(BIT_WIDTH) \
654 case BIT_WIDTH: \
655 return isSigned ? spirv::ImageFormat::R##BIT_WIDTH##i \
656 : spirv::ImageFormat::R##BIT_WIDTH##ui
657
658 switch (intType.getWidth()) {
659 BIT_WIDTH_CASE(16);
660 BIT_WIDTH_CASE(32);
661 default:
662 llvm_unreachable("Unhandled integer type!");
663 }
664 })
665 .DefaultUnreachable("Unhandled element type!");
666#undef BIT_WIDTH_CASE
667}
668
669static Type convertMemrefType(const spirv::TargetEnv &targetEnv,
671 MemRefType type) {
672 auto attr = dyn_cast_or_null<spirv::StorageClassAttr>(type.getMemorySpace());
673 if (!attr) {
674 LLVM_DEBUG(
675 llvm::dbgs()
676 << type
677 << " illegal: expected memory space to be a SPIR-V storage class "
678 "attribute; please use MemorySpaceToStorageClassConverter to map "
679 "numeric memory spaces beforehand\n");
680 return nullptr;
681 }
682 spirv::StorageClass storageClass = attr.getValue();
683
684 // Images are a special case since they are an opaque type from which elements
685 // may be accessed via image specific ops or directly through a texture
686 // pointer.
687 if (storageClass == spirv::StorageClass::Image) {
688 const int64_t rank = type.getRank();
689 if (rank < 1 || rank > 3) {
690 LLVM_DEBUG(llvm::dbgs()
691 << type << " illegal: cannot lower memref of rank " << rank
692 << " to a SPIR-V Image\n");
693 return nullptr;
694 }
695
696 // Note that we currently only support lowering to single element texels
697 // e.g. R32f. Microscaling types have no corresponding image format.
698 auto elementType = type.getElementType();
699 if (!isa<spirv::ScalarType>(elementType) ||
700 spirv::containsMicroscalingType(elementType)) {
701 LLVM_DEBUG(llvm::dbgs() << type << " illegal: cannot lower memref of "
702 << elementType << " to a SPIR-V Image\n");
703 return nullptr;
704 }
705
706 // Currently every memref in the image storage class is converted to a
707 // sampled image so we can hardcode the NeedSampler field. Future work
708 // will generalize this to support regular non-sampled images.
709 auto spvImageType = spirv::ImageType::get(
710 elementType, convertRank(rank), spirv::ImageDepthInfo::DepthUnknown,
711 spirv::ImageArrayedInfo::NonArrayed,
712 spirv::ImageSamplingInfo::SingleSampled,
713 spirv::ImageSamplerUseInfo::NeedSampler, getImageFormat(elementType));
714 auto spvSampledImageType = spirv::SampledImageType::get(spvImageType);
715 auto imagePtrType = spirv::PointerType::get(
716 spvSampledImageType, spirv::StorageClass::UniformConstant);
717 return imagePtrType;
718 }
719
720 if (isa<IntegerType>(type.getElementType())) {
721 if (type.getElementTypeBitWidth() == 1)
722 return convertBoolMemrefType(targetEnv, options, type, storageClass);
723 if (type.getElementTypeBitWidth() < 8)
724 return convertSubByteMemrefType(targetEnv, options, type, storageClass);
725 }
726
727 Type arrayElemType;
728 Type elementType = type.getElementType();
729 if (auto vecType = dyn_cast<VectorType>(elementType)) {
730 arrayElemType =
731 convertVectorType(targetEnv, options, vecType, storageClass);
732 } else if (auto complexType = dyn_cast<ComplexType>(elementType)) {
733 arrayElemType =
734 convertComplexType(targetEnv, options, complexType, storageClass);
735 } else if (auto scalarType = dyn_cast<spirv::ScalarType>(elementType)) {
736 arrayElemType =
737 convertScalarType(targetEnv, options, scalarType, storageClass);
738 } else if (auto indexType = dyn_cast<IndexType>(elementType)) {
739 type = cast<MemRefType>(convertIndexElementType(type, options));
740 arrayElemType = type.getElementType();
741 } else if (auto floatType = dyn_cast<FloatType>(elementType)) {
742 // Hnadle 8 bit float types.
743 type = cast<MemRefType>(convertShaped8BitFloatType(type, options));
744 arrayElemType = type.getElementType();
745 } else {
746 LLVM_DEBUG(
747 llvm::dbgs()
748 << type
749 << " unhandled: can only convert scalar or vector element type\n");
750 return nullptr;
751 }
752 if (!arrayElemType)
753 return nullptr;
754
755 std::optional<int64_t> arrayElemSize =
756 getTypeNumBytes(options, arrayElemType);
757 if (!arrayElemSize) {
758 LLVM_DEBUG(llvm::dbgs()
759 << type << " illegal: cannot deduce converted element size\n");
760 return nullptr;
761 }
762
763 if (!type.hasStaticShape()) {
764 // For OpenCL Kernel, dynamic shaped memrefs convert into a pointer pointing
765 // to the element.
766 if (targetEnv.allows(spirv::Capability::Kernel))
767 return spirv::PointerType::get(arrayElemType, storageClass);
768 int64_t stride = needsExplicitLayout(storageClass) ? *arrayElemSize : 0;
769 auto arrayType = spirv::RuntimeArrayType::get(arrayElemType, stride);
770 // For Vulkan we need extra wrapping struct and array to satisfy interface
771 // needs.
772 return wrapInStructAndGetPointer(arrayType, storageClass);
773 }
774
775 std::optional<int64_t> memrefSize = getTypeNumBytes(options, type);
776 if (!memrefSize) {
777 LLVM_DEBUG(llvm::dbgs()
778 << type << " illegal: cannot deduce element count\n");
779 return nullptr;
780 }
781
782 if (*memrefSize == 0) {
783 LLVM_DEBUG(llvm::dbgs()
784 << type << " illegal: zero-element memrefs are not supported\n");
785 return nullptr;
786 }
787
788 int64_t arrayElemCount = llvm::divideCeil(*memrefSize, *arrayElemSize);
789 int64_t stride = needsExplicitLayout(storageClass) ? *arrayElemSize : 0;
790 auto arrayType = spirv::ArrayType::get(arrayElemType, arrayElemCount, stride);
791 if (targetEnv.allows(spirv::Capability::Kernel))
792 return spirv::PointerType::get(arrayType, storageClass);
793 return wrapInStructAndGetPointer(arrayType, storageClass);
794}
795
796//===----------------------------------------------------------------------===//
797// Type casting materialization
798//===----------------------------------------------------------------------===//
799
800/// Converts the given `inputs` to the original source `type` considering the
801/// `targetEnv`'s capabilities.
802///
803/// This function is meant to be used for source materialization in type
804/// converters. When the type converter needs to materialize a cast op back
805/// to some original source type, we need to check whether the original source
806/// type is supported in the target environment. If so, we can insert legal
807/// SPIR-V cast ops accordingly.
808///
809/// Note that in SPIR-V the capabilities for storage and compute are separate.
810/// This function is meant to handle the **compute** side; so it does not
811/// involve storage classes in its logic. The storage side is expected to be
812/// handled by MemRef conversion logic.
813static Value castToSourceType(const spirv::TargetEnv &targetEnv,
814 OpBuilder &builder, Type type, ValueRange inputs,
815 Location loc) {
816 // We can only cast one value in SPIR-V.
817 if (inputs.size() != 1) {
818 auto castOp =
819 UnrealizedConversionCastOp::create(builder, loc, type, inputs);
820 return castOp.getResult(0);
821 }
822 Value input = inputs.front();
823
824 // Only support integer types for now. Floating point types to be implemented.
825 if (!isa<IntegerType>(type)) {
826 auto castOp =
827 UnrealizedConversionCastOp::create(builder, loc, type, inputs);
828 return castOp.getResult(0);
829 }
830 auto inputType = cast<IntegerType>(input.getType());
831
832 auto scalarType = dyn_cast<spirv::ScalarType>(type);
833 if (!scalarType) {
834 auto castOp =
835 UnrealizedConversionCastOp::create(builder, loc, type, inputs);
836 return castOp.getResult(0);
837 }
838
839 // Only support source type with a smaller bitwidth. This would mean we are
840 // truncating to go back so we don't need to worry about the signedness.
841 // For extension, we cannot have enough signal here to decide which op to use.
842 if (inputType.getIntOrFloatBitWidth() < scalarType.getIntOrFloatBitWidth()) {
843 auto castOp =
844 UnrealizedConversionCastOp::create(builder, loc, type, inputs);
845 return castOp.getResult(0);
846 }
847
848 // Boolean values would need to use different ops than normal integer values.
849 if (type.isInteger(1)) {
850 Value one = spirv::ConstantOp::getOne(inputType, loc, builder);
851 return spirv::IEqualOp::create(builder, loc, input, one);
852 }
853
854 // Check that the source integer type is supported by the environment.
857 scalarType.getExtensions(exts);
858 scalarType.getCapabilities(caps);
859 if (failed(checkCapabilityRequirements(type, targetEnv, caps)) ||
860 failed(checkExtensionRequirements(type, targetEnv, exts))) {
861 auto castOp =
862 UnrealizedConversionCastOp::create(builder, loc, type, inputs);
863 return castOp.getResult(0);
864 }
865
866 // We've already made sure this is truncating previously, so we don't need to
867 // care about signedness here. Still try to use a corresponding op for better
868 // consistency though.
869 if (type.isSignedInteger()) {
870 return spirv::SConvertOp::create(builder, loc, type, input);
871 }
872 return spirv::UConvertOp::create(builder, loc, type, input);
873}
874
875//===----------------------------------------------------------------------===//
876// Builtin Variables
877//===----------------------------------------------------------------------===//
878
879static spirv::GlobalVariableOp getBuiltinVariable(Block &body,
880 spirv::BuiltIn builtin) {
881 // Look through all global variables in the given `body` block and check if
882 // there is a spirv.GlobalVariable that has the same `builtin` attribute.
883 for (auto varOp : body.getOps<spirv::GlobalVariableOp>()) {
884 if (StringAttr builtinAttr = varOp.getBuiltInAttr()) {
885 auto varBuiltIn = spirv::symbolizeBuiltIn(builtinAttr.getValue());
886 if (varBuiltIn == builtin) {
887 return varOp;
888 }
889 }
890 }
891 return nullptr;
892}
893
894/// Gets name of global variable for a builtin.
895std::string getBuiltinVarName(spirv::BuiltIn builtin, StringRef prefix,
896 StringRef suffix) {
897 return Twine(prefix).concat(stringifyBuiltIn(builtin)).concat(suffix).str();
898}
899
900/// Gets or inserts a global variable for a builtin within `body` block.
901static spirv::GlobalVariableOp
902getOrInsertBuiltinVariable(Block &body, Location loc, spirv::BuiltIn builtin,
903 Type integerType, OpBuilder &builder,
904 StringRef prefix, StringRef suffix) {
905 if (auto varOp = getBuiltinVariable(body, builtin))
906 return varOp;
907
908 OpBuilder::InsertionGuard guard(builder);
909 builder.setInsertionPointToStart(&body);
910
911 spirv::GlobalVariableOp newVarOp;
912 switch (builtin) {
913 case spirv::BuiltIn::NumWorkgroups:
914 case spirv::BuiltIn::WorkgroupSize:
915 case spirv::BuiltIn::WorkgroupId:
916 case spirv::BuiltIn::LocalInvocationId:
917 case spirv::BuiltIn::GlobalInvocationId: {
918 auto ptrType = spirv::PointerType::get(VectorType::get({3}, integerType),
919 spirv::StorageClass::Input);
920 std::string name = getBuiltinVarName(builtin, prefix, suffix);
921 newVarOp =
922 spirv::GlobalVariableOp::create(builder, loc, ptrType, name, builtin);
923 break;
924 }
925 case spirv::BuiltIn::SubgroupId:
926 case spirv::BuiltIn::NumSubgroups:
927 case spirv::BuiltIn::SubgroupSize:
928 case spirv::BuiltIn::SubgroupLocalInvocationId: {
929 auto ptrType =
930 spirv::PointerType::get(integerType, spirv::StorageClass::Input);
931 std::string name = getBuiltinVarName(builtin, prefix, suffix);
932 newVarOp =
933 spirv::GlobalVariableOp::create(builder, loc, ptrType, name, builtin);
934 break;
935 }
936 default:
937 emitError(loc, "unimplemented builtin variable generation for ")
938 << stringifyBuiltIn(builtin);
939 }
940 return newVarOp;
941}
942
943//===----------------------------------------------------------------------===//
944// Push constant storage
945//===----------------------------------------------------------------------===//
946
947/// Returns the pointer type for the push constant storage containing
948/// `elementCount` 32-bit integer values.
949static spirv::PointerType getPushConstantStorageType(unsigned elementCount,
950 Builder &builder,
951 Type indexType) {
952 auto arrayType = spirv::ArrayType::get(indexType, elementCount,
953 /*stride=*/4);
954 auto structType = spirv::StructType::get({arrayType}, /*offsetInfo=*/0);
955 return spirv::PointerType::get(structType, spirv::StorageClass::PushConstant);
956}
957
958/// Returns the push constant varible containing `elementCount` 32-bit integer
959/// values in `body`. Returns null op if such an op does not exit.
960static spirv::GlobalVariableOp getPushConstantVariable(Block &body,
961 unsigned elementCount) {
962 for (auto varOp : body.getOps<spirv::GlobalVariableOp>()) {
963 auto ptrType = dyn_cast<spirv::PointerType>(varOp.getType());
964 if (!ptrType)
965 continue;
966
967 // Note that Vulkan requires "There must be no more than one push constant
968 // block statically used per shader entry point." So we should always reuse
969 // the existing one.
970 if (ptrType.getStorageClass() == spirv::StorageClass::PushConstant) {
971 auto numElements = cast<spirv::ArrayType>(
972 cast<spirv::StructType>(ptrType.getPointeeType())
973 .getElementType(0))
974 .getNumElements();
975 if (numElements == elementCount)
976 return varOp;
977 }
978 }
979 return nullptr;
980}
981
982/// Gets or inserts a global variable for push constant storage containing
983/// `elementCount` 32-bit integer values in `block`.
984static spirv::GlobalVariableOp
985getOrInsertPushConstantVariable(Location loc, Block &block,
986 unsigned elementCount, OpBuilder &b,
987 Type indexType) {
988 if (auto varOp = getPushConstantVariable(block, elementCount))
989 return varOp;
990
991 auto builder = OpBuilder::atBlockBegin(&block, b.getListener());
992 auto type = getPushConstantStorageType(elementCount, builder, indexType);
993 const char *name = "__push_constant_var__";
994 return spirv::GlobalVariableOp::create(builder, loc, type, name,
995 /*initializer=*/nullptr);
996}
997
998//===----------------------------------------------------------------------===//
999// func::FuncOp Conversion Patterns
1000//===----------------------------------------------------------------------===//
1001
1002/// A pattern for rewriting function signature to convert arguments of functions
1003/// to be of valid SPIR-V types.
1004struct FuncOpConversion final : OpConversionPattern<func::FuncOp> {
1005 using Base::Base;
1006
1007 LogicalResult
1008 matchAndRewrite(func::FuncOp funcOp, OpAdaptor adaptor,
1009 ConversionPatternRewriter &rewriter) const override {
1010 FunctionType fnType = funcOp.getFunctionType();
1011 if (fnType.getNumResults() > 1)
1012 return failure();
1013
1014 TypeConverter::SignatureConversion signatureConverter(
1015 fnType.getNumInputs());
1016 for (const auto &argType : enumerate(fnType.getInputs())) {
1017 auto convertedType = getTypeConverter()->convertType(argType.value());
1018 if (!convertedType)
1019 return failure();
1020 signatureConverter.addInputs(argType.index(), convertedType);
1021 }
1022
1023 Type resultType;
1024 if (fnType.getNumResults() == 1) {
1025 resultType = getTypeConverter()->convertType(fnType.getResult(0));
1026 if (!resultType)
1027 return failure();
1028 }
1029
1030 // Create the converted spirv.func op.
1031 auto newFuncOp = spirv::FuncOp::create(
1032 rewriter, funcOp.getLoc(), funcOp.getName(),
1033 rewriter.getFunctionType(signatureConverter.getConvertedTypes(),
1034 resultType ? TypeRange(resultType)
1035 : TypeRange()));
1036
1037 newFuncOp.setArgAttrsAttr(funcOp.getArgAttrsAttr());
1038 newFuncOp.setResAttrsAttr(funcOp.getResAttrsAttr());
1039 cast<SymbolOpInterface>(newFuncOp.getOperation())
1040 .setVisibility(
1041 cast<SymbolOpInterface>(funcOp.getOperation()).getVisibility());
1042
1043 // Copy over the discardable attributes.
1044 for (NamedAttribute namedAttr :
1045 funcOp->getDiscardableAttrDictionary().getValue())
1046 newFuncOp->setDiscardableAttr(namedAttr.getName(), namedAttr.getValue());
1047
1048 rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(),
1049 newFuncOp.end());
1050 if (failed(rewriter.convertRegionTypes(
1051 &newFuncOp.getBody(), *getTypeConverter(), &signatureConverter)))
1052 return failure();
1053 rewriter.eraseOp(funcOp);
1054 return success();
1055 }
1056};
1057
1058/// A pattern for rewriting function signature to convert vector arguments of
1059/// functions to be of valid types
1060struct FuncOpVectorUnroll final : OpRewritePattern<func::FuncOp> {
1061 using Base::Base;
1062
1063 LogicalResult matchAndRewrite(func::FuncOp funcOp,
1064 PatternRewriter &rewriter) const override {
1065 FunctionType fnType = funcOp.getFunctionType();
1066
1067 // TODO: Handle declarations.
1068 if (funcOp.isDeclaration()) {
1069 LLVM_DEBUG(llvm::dbgs()
1070 << fnType << " illegal: declarations are unsupported\n");
1071 return failure();
1072 }
1073
1074 // Bail out early for dynamically-shaped argument types: getZeroAttr
1075 // requires a statically-shaped type. VectorType is always statically
1076 // shaped, so this correctly skips it without a special-case guard.
1077 if (llvm::any_of(fnType.getInputs(), [](Type argType) {
1078 auto shapedType = dyn_cast<ShapedType>(argType);
1079 return shapedType && !shapedType.hasStaticShape();
1080 }))
1081 return failure();
1082
1083 // Create a new func op with the original type and copy the function body.
1084 auto newFuncOp = func::FuncOp::create(rewriter, funcOp.getLoc(),
1085 funcOp.getName(), fnType);
1086 rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(),
1087 newFuncOp.end());
1088
1089 Location loc = newFuncOp.getBody().getLoc();
1090
1091 Block &entryBlock = newFuncOp.getBlocks().front();
1092 OpBuilder::InsertionGuard guard(rewriter);
1093 rewriter.setInsertionPointToStart(&entryBlock);
1094
1095 TypeConverter::SignatureConversion oneToNTypeMapping(
1096 fnType.getInputs().size());
1097
1098 // For arguments that are of illegal types and require unrolling.
1099 // `unrolledInputNums` stores the indices of arguments that result from
1100 // unrolling in the new function signature. `newInputNo` is a counter.
1101 SmallVector<size_t> unrolledInputNums;
1102 size_t newInputNo = 0;
1103
1104 // For arguments that are of legal types and do not require unrolling.
1105 // `tmpOps` stores a mapping from temporary operations that serve as
1106 // placeholders for new arguments that will be added later. These operations
1107 // will be erased once the entry block's argument list is updated.
1108 llvm::SmallDenseMap<Operation *, size_t> tmpOps;
1109
1110 // This counts the number of new operations created.
1111 size_t newOpCount = 0;
1112
1113 // Enumerate through the arguments.
1114 for (auto [origInputNo, origType] : enumerate(fnType.getInputs())) {
1115 // Check whether the argument is of vector type.
1116 auto origVecType = dyn_cast<VectorType>(origType);
1117 if (!origVecType) {
1118 // We need a placeholder for the old argument that will be erased later.
1119 auto castOp = UnrealizedConversionCastOp::create(
1120 rewriter, loc, origType, ValueRange());
1121 Value result = castOp.getResult(0);
1122 rewriter.replaceAllUsesWith(newFuncOp.getArgument(origInputNo), result);
1123 tmpOps.insert({result.getDefiningOp(), newInputNo});
1124 oneToNTypeMapping.addInputs(origInputNo, origType);
1125 ++newInputNo;
1126 ++newOpCount;
1127 continue;
1128 }
1129 // Check whether the vector needs unrolling.
1130 auto targetShape = getTargetShape(origVecType);
1131 if (!targetShape) {
1132 // We need a placeholder for the old argument that will be erased later.
1133 auto castOp = UnrealizedConversionCastOp::create(
1134 rewriter, loc, origType, ValueRange());
1135 Value result = castOp.getResult(0);
1136 rewriter.replaceAllUsesWith(newFuncOp.getArgument(origInputNo), result);
1137 tmpOps.insert({result.getDefiningOp(), newInputNo});
1138 oneToNTypeMapping.addInputs(origInputNo, origType);
1139 ++newInputNo;
1140 ++newOpCount;
1141 continue;
1142 }
1143 VectorType unrolledType =
1144 VectorType::get(*targetShape, origVecType.getElementType());
1145 auto originalShape =
1146 llvm::to_vector_of<int64_t, 4>(origVecType.getShape());
1147
1148 // Prepare the result vector.
1149 Value result = arith::ConstantOp::create(
1150 rewriter, loc, origVecType, rewriter.getZeroAttr(origVecType));
1151 ++newOpCount;
1152 // Prepare the placeholder for the new arguments that will be added later.
1153 Value dummy = arith::ConstantOp::create(
1154 rewriter, loc, unrolledType, rewriter.getZeroAttr(unrolledType));
1155 ++newOpCount;
1156
1157 // Create the `vector.insert_strided_slice` ops.
1158 SmallVector<int64_t> strides(targetShape->size(), 1);
1159 SmallVector<Type> newTypes;
1160 for (SmallVector<int64_t> offsets :
1161 StaticTileOffsetRange(originalShape, *targetShape)) {
1162 result = vector::InsertStridedSliceOp::create(rewriter, loc, dummy,
1163 result, offsets, strides);
1164 newTypes.push_back(unrolledType);
1165 unrolledInputNums.push_back(newInputNo);
1166 ++newInputNo;
1167 ++newOpCount;
1168 }
1169 rewriter.replaceAllUsesWith(newFuncOp.getArgument(origInputNo), result);
1170 oneToNTypeMapping.addInputs(origInputNo, newTypes);
1171 }
1172
1173 // Change the function signature.
1174 auto convertedTypes = oneToNTypeMapping.getConvertedTypes();
1175 auto newFnType = fnType.clone(convertedTypes, fnType.getResults());
1176 rewriter.modifyOpInPlace(newFuncOp,
1177 [&] { newFuncOp.setFunctionType(newFnType); });
1178
1179 // Update the arguments in the entry block.
1180 entryBlock.eraseArguments(0, fnType.getNumInputs());
1181 SmallVector<Location> locs(convertedTypes.size(), newFuncOp.getLoc());
1182 entryBlock.addArguments(convertedTypes, locs);
1183
1184 // Replace all uses of placeholders for initially legal arguments with their
1185 // original function arguments (that were added to `newFuncOp`).
1186 for (auto &[placeholderOp, argIdx] : tmpOps) {
1187 if (!placeholderOp)
1188 continue;
1189 Value replacement = newFuncOp.getArgument(argIdx);
1190 rewriter.replaceAllUsesWith(placeholderOp->getResult(0), replacement);
1191 }
1192
1193 // Replace dummy operands of new `vector.insert_strided_slice` ops with
1194 // their corresponding new function arguments. The new
1195 // `vector.insert_strided_slice` ops are inserted only into the entry block,
1196 // so iterating over that block is sufficient.
1197 size_t unrolledInputIdx = 0;
1198 for (auto [count, op] : enumerate(entryBlock.getOperations())) {
1199 Operation &curOp = op;
1200 // Since all newly created operations are in the beginning, reaching the
1201 // end of them means that any later `vector.insert_strided_slice` should
1202 // not be touched.
1203 if (count >= newOpCount)
1204 continue;
1205 if (auto vecOp = dyn_cast<vector::InsertStridedSliceOp>(op)) {
1206 size_t unrolledInputNo = unrolledInputNums[unrolledInputIdx];
1207 rewriter.modifyOpInPlace(&curOp, [&] {
1208 curOp.setOperand(0, newFuncOp.getArgument(unrolledInputNo));
1209 });
1210 ++unrolledInputIdx;
1211 }
1212 }
1213
1214 // Erase the original funcOp. The `tmpOps` do not need to be erased since
1215 // they have no uses and will be handled by dead-code elimination.
1216 rewriter.eraseOp(funcOp);
1217 return success();
1218 }
1219};
1220
1221//===----------------------------------------------------------------------===//
1222// func::ReturnOp Conversion Patterns
1223//===----------------------------------------------------------------------===//
1224
1225/// A pattern for rewriting function signature and the return op to convert
1226/// vectors to be of valid types.
1227struct ReturnOpVectorUnroll final : OpRewritePattern<func::ReturnOp> {
1228 using Base::Base;
1229
1230 LogicalResult matchAndRewrite(func::ReturnOp returnOp,
1231 PatternRewriter &rewriter) const override {
1232 // Check whether the parent funcOp is valid.
1233 auto funcOp = dyn_cast<func::FuncOp>(returnOp->getParentOp());
1234 if (!funcOp)
1235 return failure();
1236
1237 FunctionType fnType = funcOp.getFunctionType();
1238 TypeConverter::SignatureConversion oneToNTypeMapping(
1239 fnType.getResults().size());
1240 Location loc = returnOp.getLoc();
1241
1242 // For the new return op.
1243 SmallVector<Value> newOperands;
1244
1245 // Enumerate through the results.
1246 for (auto [origResultNo, origType] : enumerate(fnType.getResults())) {
1247 // Check whether the argument is of vector type.
1248 auto origVecType = dyn_cast<VectorType>(origType);
1249 if (!origVecType) {
1250 oneToNTypeMapping.addInputs(origResultNo, origType);
1251 newOperands.push_back(returnOp.getOperand(origResultNo));
1252 continue;
1253 }
1254 // Check whether the vector needs unrolling.
1255 auto targetShape = getTargetShape(origVecType);
1256 if (!targetShape) {
1257 // The original argument can be used.
1258 oneToNTypeMapping.addInputs(origResultNo, origType);
1259 newOperands.push_back(returnOp.getOperand(origResultNo));
1260 continue;
1261 }
1262 VectorType unrolledType =
1263 VectorType::get(*targetShape, origVecType.getElementType());
1264
1265 // Create `vector.extract_strided_slice` ops to form legal vectors from
1266 // the original operand of illegal type.
1267 auto originalShape =
1268 llvm::to_vector_of<int64_t, 4>(origVecType.getShape());
1269 SmallVector<int64_t> strides(originalShape.size(), 1);
1270 SmallVector<int64_t> extractShape(originalShape.size(), 1);
1271 extractShape.back() = targetShape->back();
1272 SmallVector<Type> newTypes;
1273 Value returnValue = returnOp.getOperand(origResultNo);
1274 for (SmallVector<int64_t> offsets :
1275 StaticTileOffsetRange(originalShape, *targetShape)) {
1276 Value result = vector::ExtractStridedSliceOp::create(
1277 rewriter, loc, returnValue, offsets, extractShape, strides);
1278 if (originalShape.size() > 1) {
1279 SmallVector<int64_t> extractIndices(originalShape.size() - 1, 0);
1280 result =
1281 vector::ExtractOp::create(rewriter, loc, result, extractIndices);
1282 }
1283 newOperands.push_back(result);
1284 newTypes.push_back(unrolledType);
1285 }
1286 oneToNTypeMapping.addInputs(origResultNo, newTypes);
1287 }
1288
1289 // Change the function signature.
1290 auto newFnType =
1291 FunctionType::get(rewriter.getContext(), TypeRange(fnType.getInputs()),
1292 TypeRange(oneToNTypeMapping.getConvertedTypes()));
1293 rewriter.modifyOpInPlace(funcOp,
1294 [&] { funcOp.setFunctionType(newFnType); });
1295
1296 // Replace the return op using the new operands. This will automatically
1297 // update the entry block as well.
1298 rewriter.replaceOp(returnOp,
1299 func::ReturnOp::create(rewriter, loc, newOperands));
1300
1301 return success();
1302 }
1303};
1304
1305static void addNoWrapDecorations(Operation *op,
1307 OpBuilder &builder) {
1308 if (flags.noSignedWrap)
1310 spirv::getDecorationString(spirv::Decoration::NoSignedWrap),
1311 builder.getUnitAttr());
1312 if (flags.noUnsignedWrap)
1314 spirv::getDecorationString(spirv::Decoration::NoUnsignedWrap),
1315 builder.getUnitAttr());
1316}
1317
1318static std::optional<uint64_t> getMaxLinearizedIndex(ArrayRef<int64_t> shape,
1319 ArrayRef<int64_t> strides,
1320 int64_t offset) {
1321 if (shape.size() != strides.size() || offset < 0)
1322 return std::nullopt;
1323
1324 uint64_t maxLinearIndex = offset;
1325 for (auto [dimension, stride] : llvm::zip(shape, strides)) {
1326 if (dimension <= 0 || stride < 0)
1327 return std::nullopt;
1328 std::optional<uint64_t> nextMaxLinearIndex = llvm::checkedMulAddUnsigned(
1329 static_cast<uint64_t>(dimension - 1), static_cast<uint64_t>(stride),
1330 maxLinearIndex);
1331 if (!nextMaxLinearIndex)
1332 return std::nullopt;
1333 maxLinearIndex = *nextMaxLinearIndex;
1334 }
1335 return maxLinearIndex;
1336}
1337
1338static spirv::ArrayType getStorageBufferArrayType(Value basePtr) {
1339 auto pointerType = dyn_cast<spirv::PointerType>(basePtr.getType());
1340 if (!pointerType ||
1341 pointerType.getStorageClass() != spirv::StorageClass::StorageBuffer)
1342 return {};
1343
1344 Type pointeeType = pointerType.getPointeeType();
1345 if (auto structType = dyn_cast<spirv::StructType>(pointeeType)) {
1346 if (structType.getNumElements() != 1)
1347 return {};
1348 pointeeType = structType.getElementType(0);
1349 }
1350 return dyn_cast<spirv::ArrayType>(pointeeType);
1351}
1352
1353static bool shouldEmitInBoundsAccessChain(MemRefType baseType, Value basePtr,
1354 ArrayRef<int64_t> strides,
1355 int64_t offset,
1356 uint64_t accessElementCount) {
1357 std::optional<uint64_t> maxSourceElementIndex =
1358 getMaxLinearizedIndex(baseType.getShape(), strides, offset);
1359 spirv::ArrayType storageArrayType = getStorageBufferArrayType(basePtr);
1360 if (!maxSourceElementIndex || !storageArrayType)
1361 return false;
1362
1363 // Source indices and storage element counts use the same units only when
1364 // each source element maps to one SPIR-V array element. An i16 or a narrower
1365 // memref source may be stored using a wider SPIR-V array element than that
1366 // of the source. Keep a plain access chain so later bitwidth emulation can
1367 // adjust the final index in storage-element units.
1368 if (baseType.getElementType() != storageArrayType.getElementType())
1369 return false;
1370
1371 uint64_t storageElementCount = storageArrayType.getNumElements();
1372 if (accessElementCount == 0 || accessElementCount > storageElementCount)
1373 return false;
1374
1375 // `InBoundsAccessChain` requires the computed pointer to stay within the
1376 // SPIR-V base object. Dynamic index validity is assumed from the source
1377 // operation/caller contract; for vector accesses, `accessElementCount` only
1378 // rejects widths that cannot fit in the fixed StorageBuffer object at all.
1379 // The static proof here is that the memref layout's linear index space maps
1380 // into that same object.
1381 return *maxSourceElementIndex < storageElementCount;
1382}
1383
1384} // namespace
1385
1386//===----------------------------------------------------------------------===//
1387// Public function for builtin variables
1388//===----------------------------------------------------------------------===//
1389
1391 spirv::BuiltIn builtin,
1392 Type integerType, OpBuilder &builder,
1393 StringRef prefix, StringRef suffix) {
1395 if (!parent) {
1396 op->emitError("expected operation to be within a module-like op");
1397 return nullptr;
1398 }
1399
1400 spirv::GlobalVariableOp varOp =
1401 getOrInsertBuiltinVariable(*parent->getRegion(0).begin(), op->getLoc(),
1402 builtin, integerType, builder, prefix, suffix);
1403 Value ptr = spirv::AddressOfOp::create(builder, op->getLoc(), varOp);
1404 return spirv::LoadOp::create(builder, op->getLoc(), ptr);
1405}
1406
1407//===----------------------------------------------------------------------===//
1408// Public function for pushing constant storage
1409//===----------------------------------------------------------------------===//
1410
1412 unsigned offset, Type integerType,
1413 OpBuilder &builder) {
1414 Location loc = op->getLoc();
1416 if (!parent) {
1417 op->emitError("expected operation to be within a module-like op");
1418 return nullptr;
1419 }
1420
1421 spirv::GlobalVariableOp varOp = getOrInsertPushConstantVariable(
1422 loc, parent->getRegion(0).front(), elementCount, builder, integerType);
1423
1424 Value zeroOp = spirv::ConstantOp::getZero(integerType, loc, builder);
1425 Value offsetOp = spirv::ConstantOp::create(builder, loc, integerType,
1426 builder.getI32IntegerAttr(offset));
1427 auto addrOp = spirv::AddressOfOp::create(builder, loc, varOp);
1428 auto acOp = spirv::AccessChainOp::create(builder, loc, addrOp,
1429 llvm::ArrayRef({zeroOp, offsetOp}));
1430 return spirv::LoadOp::create(builder, loc, acOp);
1431}
1432
1433//===----------------------------------------------------------------------===//
1434// Public functions for index calculation
1435//===----------------------------------------------------------------------===//
1436
1440 ArrayRef<int64_t> strides,
1441 int64_t offset, Type integerType) {
1443 if (!targetEnv.allows(Extension::SPV_KHR_no_integer_wrap_decoration))
1444 return flags;
1445
1446 auto integer = dyn_cast<IntegerType>(integerType);
1447 if (!integer)
1448 return flags;
1449
1450 std::optional<uint64_t> maxLinearIndex =
1451 getMaxLinearizedIndex(shape, strides, offset);
1452 if (!maxLinearIndex)
1453 return flags;
1454
1455 flags.noSignedWrap =
1456 *maxLinearIndex <=
1457 APInt::getSignedMaxValue(integer.getWidth()).getZExtValue();
1458 flags.noUnsignedWrap =
1459 *maxLinearIndex <= APInt::getMaxValue(integer.getWidth()).getZExtValue();
1460 return flags;
1461}
1462
1464 int64_t offset, Type integerType,
1465 Location loc, OpBuilder &builder,
1466 LinearizedIndexNoWrapFlags noWrapFlags) {
1467 assert(indices.size() == strides.size() &&
1468 "must provide indices for all dimensions");
1469
1470 // TODO: Consider moving to use affine.apply and patterns converting
1471 // affine.apply to standard ops. This needs converting to SPIR-V passes to be
1472 // broken down into progressive small steps so we can have intermediate steps
1473 // using other dialects. At the moment SPIR-V is the final sink.
1474
1475 Value linearizedIndex = builder.createOrFold<spirv::ConstantOp>(
1476 loc, integerType, IntegerAttr::get(integerType, offset));
1477 for (const auto &index : llvm::enumerate(indices)) {
1478 Value strideVal = builder.createOrFold<spirv::ConstantOp>(
1479 loc, integerType,
1480 IntegerAttr::get(integerType, strides[index.index()]));
1481 Value update =
1482 builder.createOrFold<spirv::IMulOp>(loc, index.value(), strideVal);
1483 if (noWrapFlags.noSignedWrap || noWrapFlags.noUnsignedWrap)
1484 if (auto mul = update.getDefiningOp<spirv::IMulOp>())
1485 addNoWrapDecorations(mul, noWrapFlags, builder);
1486
1487 linearizedIndex =
1488 builder.createOrFold<spirv::IAddOp>(loc, update, linearizedIndex);
1489 if (noWrapFlags.noSignedWrap || noWrapFlags.noUnsignedWrap)
1490 if (auto add = linearizedIndex.getDefiningOp<spirv::IAddOp>())
1491 addNoWrapDecorations(add, noWrapFlags, builder);
1492 }
1493 return linearizedIndex;
1494}
1495
1497 MemRefType baseType, Value basePtr,
1499 OpBuilder &builder,
1500 uint64_t accessElementCount) {
1501 // Get base and offset of the MemRefType and verify they are static.
1502
1503 int64_t offset;
1505 if (failed(baseType.getStridesAndOffset(strides, offset)) ||
1506 llvm::is_contained(strides, ShapedType::kDynamic) ||
1507 ShapedType::isDynamic(offset)) {
1508 return nullptr;
1509 }
1510
1511 auto indexType = typeConverter.getIndexType();
1513 typeConverter.getTargetEnv(), baseType.getShape(), strides, offset,
1514 indexType);
1515
1516 SmallVector<Value, 2> linearizedIndices;
1517 auto zero = spirv::ConstantOp::getZero(indexType, loc, builder);
1518
1519 if (baseType.getRank() == 0) {
1520 linearizedIndices.push_back(zero);
1521 } else {
1522 linearizedIndices.push_back(linearizeIndex(
1523 indices, strides, offset, indexType, loc, builder, noWrapFlags));
1524 }
1525
1526 const Type pointeeType =
1527 cast<spirv::PointerType>(basePtr.getType()).getPointeeType();
1528 // Interface memrefs are wrapped in a struct: index to its first elem.
1529 if (isa<spirv::StructType>(pointeeType))
1530 linearizedIndices.insert(linearizedIndices.begin(), zero);
1531 if (shouldEmitInBoundsAccessChain(baseType, basePtr, strides, offset,
1532 accessElementCount))
1533 return spirv::InBoundsAccessChainOp::create(builder, loc, basePtr,
1534 linearizedIndices);
1535 return spirv::AccessChainOp::create(builder, loc, basePtr, linearizedIndices);
1536}
1537
1539 MemRefType baseType, Value basePtr,
1541 OpBuilder &builder) {
1542 return getVulkanElementPtr(typeConverter, baseType, basePtr, indices, loc,
1543 builder, /*accessElementCount=*/1);
1544}
1545
1547 MemRefType baseType, Value basePtr,
1549 OpBuilder &builder) {
1550 // Get base and offset of the MemRefType and verify they are static.
1551
1552 int64_t offset;
1554 if (failed(baseType.getStridesAndOffset(strides, offset)) ||
1555 llvm::is_contained(strides, ShapedType::kDynamic) ||
1556 ShapedType::isDynamic(offset)) {
1557 return nullptr;
1558 }
1559
1560 auto indexType = typeConverter.getIndexType();
1562 typeConverter.getTargetEnv(), baseType.getShape(), strides, offset,
1563 indexType);
1564
1565 SmallVector<Value, 2> linearizedIndices;
1566 Value linearIndex;
1567 if (baseType.getRank() == 0) {
1568 linearIndex = spirv::ConstantOp::getZero(indexType, loc, builder);
1569 } else {
1570 linearIndex = linearizeIndex(indices, strides, offset, indexType, loc,
1571 builder, noWrapFlags);
1572 }
1573 Type pointeeType =
1574 cast<spirv::PointerType>(basePtr.getType()).getPointeeType();
1575 if (isa<spirv::ArrayType>(pointeeType)) {
1576 linearizedIndices.push_back(linearIndex);
1577 return spirv::AccessChainOp::create(builder, loc, basePtr,
1578 linearizedIndices);
1579 }
1580 return spirv::PtrAccessChainOp::create(builder, loc, basePtr, linearIndex,
1581 linearizedIndices);
1582}
1583
1585 MemRefType baseType, Value basePtr,
1587 OpBuilder &builder,
1588 uint64_t accessElementCount) {
1589
1590 if (typeConverter.allows(spirv::Capability::Kernel)) {
1591 return getOpenCLElementPtr(typeConverter, baseType, basePtr, indices, loc,
1592 builder);
1593 }
1594
1595 return getVulkanElementPtr(typeConverter, baseType, basePtr, indices, loc,
1596 builder, accessElementCount);
1597}
1598
1600 MemRefType baseType, Value basePtr,
1602 OpBuilder &builder) {
1603 return getElementPtr(typeConverter, baseType, basePtr, indices, loc, builder,
1604 /*accessElementCount=*/1);
1605}
1606
1607//===----------------------------------------------------------------------===//
1608// Public functions for vector unrolling
1609//===----------------------------------------------------------------------===//
1610
1612 for (int i : {4, 3, 2}) {
1613 if (size % i == 0)
1614 return i;
1615 }
1616 return 1;
1617}
1618
1621 VectorType srcVectorType = op.getSourceVectorType();
1622 assert(srcVectorType.getRank() == 1); // Guaranteed by semantics
1623 int64_t vectorSize =
1624 mlir::spirv::getComputeVectorSize(srcVectorType.getDimSize(0));
1625 return {vectorSize};
1626}
1627
1630 VectorType vectorType = op.getResultVectorType();
1631 SmallVector<int64_t> nativeSize(vectorType.getRank(), 1);
1632 nativeSize.back() =
1633 mlir::spirv::getComputeVectorSize(vectorType.getShape().back());
1634 return nativeSize;
1635}
1636
1637std::optional<SmallVector<int64_t>>
1640 if (auto vecType = dyn_cast<VectorType>(op->getResultTypes()[0])) {
1641 if (vecType.getRank() == 0)
1642 return std::nullopt;
1643 SmallVector<int64_t> nativeSize(vecType.getRank(), 1);
1644 nativeSize.back() =
1645 mlir::spirv::getComputeVectorSize(vecType.getShape().back());
1646 return nativeSize;
1647 }
1648 }
1649
1651 .Case<vector::ReductionOp, vector::TransposeOp>(
1652 [](auto typedOp) { return getNativeVectorShapeImpl(typedOp); })
1653 .Default(std::nullopt);
1654}
1655
1657 MLIRContext *context = op->getContext();
1658 RewritePatternSet patterns(context);
1661 // We only want to apply signature conversion once to the existing func ops.
1662 // Without specifying strictMode, the greedy pattern rewriter will keep
1663 // looking for newly created func ops.
1664 return applyPatternsGreedily(op, std::move(patterns),
1665 GreedyRewriteConfig().setStrictness(
1667}
1668
1670 MLIRContext *context = op->getContext();
1671
1672 // Unroll vectors in function bodies to native vector size.
1673 {
1674 RewritePatternSet patterns(context);
1676 [](auto op) { return mlir::spirv::getNativeVectorShape(op); });
1677 populateVectorUnrollPatterns(patterns, options);
1678 if (failed(applyPatternsGreedily(op, std::move(patterns))))
1679 return failure();
1680 }
1681
1682 // Convert transpose ops into extract and insert pairs, in preparation of
1683 // further transformations to canonicalize/cancel.
1684 {
1685 RewritePatternSet patterns(context);
1687 patterns, vector::VectorTransposeLowering::EltWise);
1689 if (failed(applyPatternsGreedily(op, std::move(patterns))))
1690 return failure();
1691 }
1692
1693 // Run canonicalization to cast away leading size-1 dimensions.
1694 {
1695 RewritePatternSet patterns(context);
1696
1697 // We need to pull in casting way leading one dims.
1698 vector::populateCastAwayVectorLeadingOneDimPatterns(patterns);
1699 vector::ReductionOp::getCanonicalizationPatterns(patterns, context);
1700 vector::TransposeOp::getCanonicalizationPatterns(patterns, context);
1701
1702 // Decompose different rank insert_strided_slice and n-D
1703 // extract_slided_slice.
1704 vector::populateVectorInsertExtractStridedSliceDecompositionPatterns(
1705 patterns);
1706 vector::InsertOp::getCanonicalizationPatterns(patterns, context);
1707 vector::ExtractOp::getCanonicalizationPatterns(patterns, context);
1708
1709 // Trimming leading unit dims may generate broadcast/shape_cast ops. Clean
1710 // them up.
1711 vector::BroadcastOp::getCanonicalizationPatterns(patterns, context);
1712 vector::ShapeCastOp::getCanonicalizationPatterns(patterns, context);
1713
1714 if (failed(applyPatternsGreedily(op, std::move(patterns))))
1715 return failure();
1716 }
1717 return success();
1718}
1719
1720//===----------------------------------------------------------------------===//
1721// SPIR-V TypeConverter
1722//===----------------------------------------------------------------------===//
1723
1725 const SPIRVConversionOptions &options)
1726 : targetEnv(targetAttr), options(options) {
1727 // Add conversions. The order matters here: later ones will be tried earlier.
1728
1729 // Allow all SPIR-V dialect specific types. This assumes all builtin types
1730 // adopted in the SPIR-V dialect (i.e., IntegerType, FloatType, VectorType)
1731 // were tried before.
1732 //
1733 // TODO: This assumes that the SPIR-V types are valid to use in the given
1734 // target environment, which should be the case if the whole pipeline is
1735 // driven by the same target environment. Still, we probably still want to
1736 // validate and convert to be safe.
1737 addConversion([](spirv::SPIRVType type) { return type; });
1738
1739 addConversion([this](IndexType /*indexType*/) { return getIndexType(); });
1740
1741 addConversion([this](IntegerType intType) -> std::optional<Type> {
1742 if (auto scalarType = dyn_cast<spirv::ScalarType>(intType))
1743 return convertScalarType(this->targetEnv, this->options, scalarType);
1744 if (intType.getWidth() < 8)
1745 return convertSubByteIntegerType(this->options, intType);
1746 return Type();
1747 });
1748
1749 addConversion([this](FloatType floatType) -> std::optional<Type> {
1750 if (floatType.getWidth() == 8) {
1751 if (auto scalarType = dyn_cast<spirv::ScalarType>(floatType);
1752 scalarType && isScalarTypeSupported(this->targetEnv, scalarType))
1753 return floatType;
1754 return convert8BitFloatType(this->options, floatType);
1755 }
1756 if (auto scalarType = dyn_cast<spirv::ScalarType>(floatType))
1757 return convertScalarType(this->targetEnv, this->options, scalarType);
1758 return Type();
1759 });
1760
1761 addConversion([this](ComplexType complexType) {
1762 return convertComplexType(this->targetEnv, this->options, complexType);
1763 });
1764
1765 addConversion([this](VectorType vectorType) {
1766 return convertVectorType(this->targetEnv, this->options, vectorType);
1767 });
1768
1769 addConversion([this](TensorType tensorType) {
1770 return convertTensorType(this->targetEnv, this->options, tensorType);
1771 });
1772
1773 addConversion([this](MemRefType memRefType) {
1774 return convertMemrefType(this->targetEnv, this->options, memRefType);
1775 });
1776
1777 // Register some last line of defense casting logic.
1778 addSourceMaterialization(
1779 [this](OpBuilder &builder, Type type, ValueRange inputs, Location loc) {
1780 return castToSourceType(this->targetEnv, builder, type, inputs, loc);
1781 });
1782 addTargetMaterialization([](OpBuilder &builder, Type type, ValueRange inputs,
1783 Location loc) {
1784 auto cast = UnrealizedConversionCastOp::create(builder, loc, type, inputs);
1785 return cast.getResult(0);
1786 });
1787}
1788
1790 return ::getIndexType(getContext(), options);
1791}
1792
1793MLIRContext *SPIRVTypeConverter::getContext() const {
1794 return targetEnv.getAttr().getContext();
1795}
1796
1797bool SPIRVTypeConverter::allows(spirv::Capability capability) const {
1798 return targetEnv.allows(capability);
1799}
1800
1801//===----------------------------------------------------------------------===//
1802// SPIR-V ConversionTarget
1803//===----------------------------------------------------------------------===//
1804
1805std::unique_ptr<SPIRVConversionTarget>
1807 std::unique_ptr<SPIRVConversionTarget> target(
1808 // std::make_unique does not work here because the constructor is private.
1809 new SPIRVConversionTarget(targetAttr));
1810 SPIRVConversionTarget *targetPtr = target.get();
1811 target->addDynamicallyLegalDialect<spirv::SPIRVDialect>(
1812 // We need to capture the raw pointer here because it is stable:
1813 // target will be destroyed once this function is returned.
1814 [targetPtr](Operation *op) { return targetPtr->isLegalOp(op); });
1815 return target;
1816}
1817
1818SPIRVConversionTarget::SPIRVConversionTarget(spirv::TargetEnvAttr targetAttr)
1819 : ConversionTarget(*targetAttr.getContext()), targetEnv(targetAttr) {}
1820
1821bool SPIRVConversionTarget::isLegalOp(Operation *op) {
1822 // Make sure this op is available at the given version. Ops not implementing
1823 // QueryMinVersionInterface/QueryMaxVersionInterface are available to all
1824 // SPIR-V versions.
1825 if (auto minVersionIfx = dyn_cast<spirv::QueryMinVersionInterface>(op)) {
1826 std::optional<spirv::Version> minVersion = minVersionIfx.getMinVersion();
1827 if (minVersion && *minVersion > this->targetEnv.getVersion()) {
1828 LLVM_DEBUG(llvm::dbgs()
1829 << op->getName() << " illegal: requiring min version "
1830 << spirv::stringifyVersion(*minVersion) << "\n");
1831 return false;
1832 }
1833 }
1834 if (auto maxVersionIfx = dyn_cast<spirv::QueryMaxVersionInterface>(op)) {
1835 std::optional<spirv::Version> maxVersion = maxVersionIfx.getMaxVersion();
1836 if (maxVersion && *maxVersion < this->targetEnv.getVersion()) {
1837 LLVM_DEBUG(llvm::dbgs()
1838 << op->getName() << " illegal: requiring max version "
1839 << spirv::stringifyVersion(*maxVersion) << "\n");
1840 return false;
1841 }
1842 }
1843
1844 // Make sure this op's required extensions are allowed to use. Ops not
1845 // implementing QueryExtensionInterface do not require extensions to be
1846 // available.
1847 if (auto extensions = dyn_cast<spirv::QueryExtensionInterface>(op))
1848 if (failed(checkExtensionRequirements(op->getName(), this->targetEnv,
1849 extensions.getExtensions())))
1850 return false;
1851
1852 // Make sure this op's required extensions are allowed to use. Ops not
1853 // implementing QueryCapabilityInterface do not require capabilities to be
1854 // available.
1855 if (auto capabilities = dyn_cast<spirv::QueryCapabilityInterface>(op))
1856 if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv,
1857 capabilities.getCapabilities())))
1858 return false;
1859
1860 SmallVector<Type, 4> valueTypes;
1861 valueTypes.append(op->operand_type_begin(), op->operand_type_end());
1862 valueTypes.append(op->result_type_begin(), op->result_type_end());
1863
1864 // Ensure that all types have been converted to SPIRV types.
1865 if (llvm::any_of(valueTypes,
1866 [](Type t) { return !isa<spirv::SPIRVType>(t); }))
1867 return false;
1868
1869 // Special treatment for global variables, whose type requirements are
1870 // conveyed by type attributes.
1871 if (auto globalVar = dyn_cast<spirv::GlobalVariableOp>(op)) {
1872 valueTypes.push_back(globalVar.getType());
1873
1874 // Data type requirements depend on the variable storage class.
1875 if (std::optional<Type> dataType = globalVar.getDataType()) {
1876 auto spirvDataType = cast<spirv::SPIRVType>(*dataType);
1877 SmallVector<ArrayRef<spirv::Extension>, 4> exts;
1878 spirvDataType.getExtensions(exts, globalVar.storageClass());
1879 if (failed(
1880 checkExtensionRequirements(op->getName(), this->targetEnv, exts)))
1881 return false;
1882 SmallVector<ArrayRef<spirv::Capability>, 8> caps;
1883 spirvDataType.getCapabilities(caps, globalVar.storageClass());
1884 if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv,
1885 caps)))
1886 return false;
1887 }
1888 }
1889
1890 // Make sure the op's operands/results use types that are allowed by the
1891 // target environment.
1892 SmallVector<ArrayRef<spirv::Extension>, 4> typeExtensions;
1893 SmallVector<ArrayRef<spirv::Capability>, 8> typeCapabilities;
1894 for (Type valueType : valueTypes) {
1895 typeExtensions.clear();
1896 cast<spirv::SPIRVType>(valueType).getExtensions(typeExtensions);
1897 if (failed(checkExtensionRequirements(op->getName(), this->targetEnv,
1898 typeExtensions)))
1899 return false;
1900
1901 typeCapabilities.clear();
1902 cast<spirv::SPIRVType>(valueType).getCapabilities(typeCapabilities);
1903 if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv,
1904 typeCapabilities)))
1905 return false;
1906 }
1907
1908 return true;
1909}
1910
1911//===----------------------------------------------------------------------===//
1912// Public functions for populating patterns
1913//===----------------------------------------------------------------------===//
1914
1916 const SPIRVTypeConverter &typeConverter, RewritePatternSet &patterns) {
1917 patterns.add<FuncOpConversion>(typeConverter, patterns.getContext());
1918}
1919
1921 patterns.add<FuncOpVectorUnroll>(patterns.getContext());
1922}
1923
1925 patterns.add<ReturnOpVectorUnroll>(patterns.getContext());
1926}
return success()
return MutableOperandRange * this
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
b getContext())
*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`
static llvm::ManagedStatic< PassManagerOptions > options
#define BIT_WIDTH_CASE(BIT_WIDTH)
static std::optional< SmallVector< int64_t > > getTargetShape(const vector::UnrollVectorOptions &options, VectorUnrollOpInterface &iface, bool allowMasked=false)
Return the target shape for unrolling for the given op, provided through its VectorUnrollOpInterface ...
#define mul(a, b)
#define add(a, b)
Block represents an ordered list of Operations.
Definition Block.h:34
iterator_range< args_iterator > addArguments(TypeRange types, ArrayRef< Location > locs)
Add one argument to the argument list for each type specified in the list.
Definition Block.cpp:165
OpListType & getOperations()
Definition Block.h:162
Operation & front()
Definition Block.h:178
void eraseArguments(unsigned start, unsigned num)
Erases 'num' arguments from the index 'start'.
Definition Block.cpp:206
auto getOps()
Return an iterator range over the operations within this block that are of 'OpT'.
Definition Block.h:213
This class is a general helper class for creating context-global objects like types,...
Definition Builders.h:51
UnitAttr getUnitAttr()
Definition Builders.cpp:106
IntegerAttr getI32IntegerAttr(int32_t value)
Definition Builders.cpp:208
FloatType getF32Type()
Definition Builders.cpp:51
TypedAttr getZeroAttr(Type type)
Definition Builders.cpp:333
MLIRContext * getContext() const
Definition Builders.h:56
This class allows control over how the GreedyPatternRewriteDriver works.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
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
Attribute getValue() const
Return the value of the attribute.
Definition Attributes.h:181
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
static OpBuilder atBlockBegin(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the first operation in the block but still ins...
Definition Builders.h:243
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
void createOrFold(SmallVectorImpl< Value > &results, Location location, Args &&...args)
Create an operation of specific op type at the current insertion point, and immediately try to fold i...
Definition Builders.h:528
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Region & getRegion(unsigned index)
Returns the region held by this operation at position 'index'.
Definition Operation.h:740
void setOperand(unsigned idx, Value value)
Definition Operation.h:378
void setDiscardableAttr(StringAttr name, Attribute value)
Set a discardable attribute by name.
Definition Operation.h:514
operand_type_iterator operand_type_end()
Definition Operation.h:423
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
result_type_iterator result_type_end()
Definition Operation.h:454
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
result_type_iterator result_type_begin()
Definition Operation.h:453
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
result_type_range getResultTypes()
Definition Operation.h:455
MLIRContext * getContext()
Return the context this operation is associated with.
Definition Operation.h:233
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
operand_type_iterator operand_type_begin()
Definition Operation.h:422
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
Block & front()
Definition Region.h:65
iterator begin()
Definition Region.h:55
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
void inlineRegionBefore(Region &region, Region &parent, Region::iterator before)
Move the blocks that belong to "region" before the given position in another region "parent".
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
static std::unique_ptr< SPIRVConversionTarget > get(spirv::TargetEnvAttr targetAttr)
Creates a SPIR-V conversion target for the given target environment.
Type conversion from builtin types to SPIR-V types for shader interface.
Type getIndexType() const
Gets the SPIR-V correspondence for the standard index type.
const spirv::TargetEnv & getTargetEnv() const
SPIRVTypeConverter(spirv::TargetEnvAttr targetAttr, const SPIRVConversionOptions &options={})
bool allows(spirv::Capability capability) const
Checks if the SPIR-V capability inquired is supported.
A range-style iterator that allows for iterating over the offsets of all potential tiles of size tile...
static Operation * getNearestSymbolTable(Operation *from)
Returns the nearest symbol table from a given operation from.
Tensor types represent multi-dimensional arrays, and have two variants: RankedTensorType and Unranked...
Type getElementType() const
Returns the element type of this tensor type.
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
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
bool isSignedInteger() const
Return true if this is a signed integer type (with the specified width).
Definition Types.cpp:78
bool isInteger() const
Return true if this is an integer type (with the specified width).
Definition Types.cpp:58
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
Type getElementType() const
unsigned getNumElements() const
static ArrayType get(Type elementType, unsigned elementCount)
static bool isValid(VectorType)
Returns true if the given vector type is valid for the SPIR-V dialect.
static ImageType get(Type elementType, Dim dim, ImageDepthInfo depth=ImageDepthInfo::DepthUnknown, ImageArrayedInfo arrayed=ImageArrayedInfo::NonArrayed, ImageSamplingInfo samplingInfo=ImageSamplingInfo::SingleSampled, ImageSamplerUseInfo samplerUse=ImageSamplerUseInfo::SamplerUnknown, ImageFormat format=ImageFormat::Unknown)
Definition SPIRVTypes.h:165
static PointerType get(Type pointeeType, StorageClass storageClass)
static RuntimeArrayType get(Type elementType)
SmallVectorImpl< ArrayRef< Capability > > CapabilityArrayRefVector
The capability requirements for each type are following the ((Capability::A OR Extension::B) AND (Cap...
Definition SPIRVTypes.h:66
SmallVectorImpl< ArrayRef< Extension > > ExtensionArrayRefVector
The extension requirements for each type are following the ((Extension::A OR Extension::B) AND (Exten...
Definition SPIRVTypes.h:55
static SampledImageType get(Type imageType)
static StructType get(ArrayRef< Type > memberTypes, ArrayRef< OffsetInfo > offsetInfo={}, ArrayRef< MemberDecorationInfo > memberDecorations={}, ArrayRef< StructDecorationInfo > structDecorations={})
Construct a literal StructType with at least one member.
An attribute that specifies the target version, allowed extensions and capabilities,...
A wrapper class around a spirv::TargetEnvAttr to provide query methods for allowed version/capabiliti...
Version getVersion() const
bool allows(Capability) const
Returns true if the given capability is allowed.
TargetEnvAttr getAttr() const
MLIRContext * getContext() const
Returns the MLIRContext.
bool hasElementwiseMappableTraits(Operation *op)
Together, Elementwise, Scalarizable, Vectorizable, and Tensorizable provide an easy way for scalar op...
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Value getBuiltinVariableValue(Operation *op, BuiltIn builtin, Type integerType, OpBuilder &builder, StringRef prefix="__builtin__", StringRef suffix="__")
Returns the value for the given builtin variable.
Value getElementPtr(const SPIRVTypeConverter &typeConverter, MemRefType baseType, Value basePtr, ValueRange indices, Location loc, OpBuilder &builder)
Performs the index computation to get to the element at indices of the memory pointed to by basePtr,...
Value getOpenCLElementPtr(const SPIRVTypeConverter &typeConverter, MemRefType baseType, Value basePtr, ValueRange indices, Location loc, OpBuilder &builder)
Value getPushConstantValue(Operation *op, unsigned elementCount, unsigned offset, Type integerType, OpBuilder &builder)
Gets the value at the given offset of the push constant storage with a total of elementCount integerT...
std::optional< SmallVector< int64_t > > getNativeVectorShape(Operation *op)
LinearizedIndexNoWrapFlags getLinearizedIndexNoWrapFlags(const TargetEnv &targetEnv, ArrayRef< int64_t > shape, ArrayRef< int64_t > strides, int64_t offset, Type integerType)
Returns no-wrap guarantees for an in-bounds index into the static layout described by shape,...
bool containsMicroscalingType(Type type, bool subByteOnly=false)
Returns whether a type contains a microscaling element, including through composite types and pointer...
LogicalResult unrollVectorsInFuncBodies(Operation *op)
Value getVulkanElementPtr(const SPIRVTypeConverter &typeConverter, MemRefType baseType, Value basePtr, ValueRange indices, Location loc, OpBuilder &builder)
SmallVector< int64_t > getNativeVectorShapeImpl(vector::ReductionOp op)
std::string getDecorationString(Decoration decoration)
Converts a SPIR-V Decoration enum value to its snake_case string representation for use in MLIR attri...
int getComputeVectorSize(int64_t size)
LogicalResult unrollVectorsInSignatures(Operation *op)
Value linearizeIndex(ValueRange indices, ArrayRef< int64_t > strides, int64_t offset, Type integerType, Location loc, OpBuilder &builder, LinearizedIndexNoWrapFlags noWrapFlags={})
Generates IR to perform index linearization with the given indices and their corresponding strides,...
void populateVectorShapeCastLoweringPatterns(RewritePatternSet &patterns, PatternBenefit benefit=1)
Populate the pattern set with the following patterns:
void populateVectorTransposeLoweringPatterns(RewritePatternSet &patterns, VectorTransposeLowering vectorTransposeLowering, PatternBenefit benefit=1)
Populate the pattern set with the following patterns:
Include the generated interface declarations.
void populateFuncOpVectorRewritePatterns(RewritePatternSet &patterns)
void populateReturnOpVectorRewritePatterns(RewritePatternSet &patterns)
@ Packed
Sub-byte values are tightly packed without any padding, e.g., 4xi2 -> i8.
LogicalResult applyPatternsGreedily(Region &region, 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...
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
void populateBuiltinFuncToSPIRVPatterns(const SPIRVTypeConverter &typeConverter, RewritePatternSet &patterns)
Appends to a pattern list additional patterns for translating the builtin func op to the SPIR-V diale...
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147
@ ExistingOps
Only pre-existing ops are processed.
std::optional< SmallVector< int64_t > > computeShapeRatio(ArrayRef< int64_t > shape, ArrayRef< int64_t > subShape)
Return the multi-dimensional integral ratio of subShape to the trailing dimensions of shape.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
No-wrap guarantees proven for a linearized index calculation.
Options that control the vector unrolling.
UnrollVectorOptions & setNativeShapeFn(NativeShapeFnType fn)