MLIR 24.0.0git
SPIRVTypes.cpp
Go to the documentation of this file.
1//===- SPIRVTypes.cpp - MLIR SPIR-V Types ---------------------------------===//
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 defines the types in the SPIR-V dialect.
10//
11//===----------------------------------------------------------------------===//
12
17#include "mlir/Support/LLVM.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/TypeSwitch.h"
21#include "llvm/Support/ErrorHandling.h"
22
23#include <cstdint>
24#include <optional>
25
26using namespace mlir;
27using namespace mlir::spirv;
28
29/// Find microscaling elements in composite types, including recursive structs.
30/// Storage restrictions only apply to the sub-byte formats.
31static bool
32containsMicroscalingTypeImpl(Type type, bool subByteOnly,
33 llvm::SmallDenseSet<Type, 8> &visited) {
34 if (!visited.insert(type).second)
35 return false;
36 if (isa<Float4E2M1FNType, Float6E2M3FNType, Float6E3M2FNType>(type) ||
37 (!subByteOnly && isa<Float8E8M0FNUType>(type)))
38 return true;
39 if (auto composite = dyn_cast<spirv::CompositeType>(type)) {
40 if (auto structType = dyn_cast<spirv::StructType>(composite))
41 return llvm::any_of(structType.getElementTypes(), [&](Type element) {
42 return containsMicroscalingTypeImpl(element, subByteOnly, visited);
43 });
44 return containsMicroscalingTypeImpl(composite.getElementType(0),
45 subByteOnly, visited);
46 }
47 if (auto pointer = dyn_cast<spirv::PointerType>(type))
48 return containsMicroscalingTypeImpl(pointer.getPointeeType(), subByteOnly,
49 visited);
50 return false;
51}
52
53bool spirv::containsMicroscalingType(Type type, bool subByteOnly) {
54 llvm::SmallDenseSet<Type, 8> visited;
55 return containsMicroscalingTypeImpl(type, subByteOnly, visited);
56}
57
58namespace {
59// Helper function to collect extensions implied by a type by visiting all its
60// subtypes. Maintains a set of `seen` types to avoid recursion in structs.
61//
62// Serves as the source-of-truth for type extension information. All extension
63// logic should be added to this class, while the
64// `SPIRVType::getExtensions` function should not handle extension-related logic
65// directly and only invoke `TypeExtensionVisitor::add(Type *)`.
66class TypeExtensionVisitor {
67public:
68 TypeExtensionVisitor(SPIRVType::ExtensionArrayRefVector &extensions,
69 std::optional<StorageClass> storage)
70 : extensions(extensions), storage(storage) {}
71
72 // Main visitor entry point. Adds all extensions to the vector. Saves `type`
73 // as seen and dispatches to the right concrete `.add` function.
74 void add(SPIRVType type) {
75 if (auto [_it, inserted] = seen.insert({type, storage}); !inserted)
76 return;
77
81 [this](auto concreteType) { addConcrete(concreteType); })
82 .Case<ArrayType, MatrixType, RuntimeArrayType, VectorType>(
83 [this](auto concreteType) { add(concreteType.getElementType()); })
84 .Case([this](SampledImageType concreteType) {
85 add(concreteType.getImageType());
86 })
87 .Case([this](StructType concreteType) {
88 for (Type elementType : concreteType.getElementTypes())
89 add(elementType);
90 })
91 .Case<SamplerType, NamedBarrierType>([](auto) { /* no extensions */ })
92 .DefaultUnreachable("Unhandled type");
93 }
94
95 void add(Type type) {
96 if (auto functionType = dyn_cast<FunctionType>(type)) {
97 for (Type t : llvm::concat<const Type>(functionType.getInputs(),
98 functionType.getResults()))
99 add(t);
100 return;
101 }
102 add(cast<SPIRVType>(type));
103 }
104
105private:
106 // Types that add unique extensions.
107 void addConcrete(CooperativeMatrixType type);
108 void addConcrete(ImageType type);
109 void addConcrete(PointerType type);
110 void addConcrete(ScalarType type);
111 void addConcrete(TensorArmType type);
112 void addConcrete(UntypedPointerType type);
113
114 template <Extension... Es>
115 void pushExts() {
116 static constexpr Extension exts[] = {Es...};
117 extensions.push_back(exts);
118 }
119
121 std::optional<StorageClass> storage;
122 llvm::SmallDenseSet<std::pair<Type, std::optional<StorageClass>>> seen;
123};
124
125// Helper function to collect capabilities implied by a type by visiting all its
126// subtypes. Maintains a set of `seen` types to avoid recursion in structs.
127//
128// Serves as the source-of-truth for type capability information. All capability
129// logic should be added to this class, while the
130// `SPIRVType::getCapabilities` function should not handle capability-related
131// logic directly and only invoke `TypeCapabilityVisitor::add(Type *)`.
132class TypeCapabilityVisitor {
133public:
134 TypeCapabilityVisitor(SPIRVType::CapabilityArrayRefVector &capabilities,
135 std::optional<StorageClass> storage)
136 : capabilities(capabilities), storage(storage) {}
137
138 // Main visitor entry point. Adds all extensions to the vector. Saves `type`
139 // as seen and dispatches to the right concrete `.add` function.
140 void add(SPIRVType type) {
141 if (auto [_it, inserted] = seen.insert({type, storage}); !inserted)
142 return;
143
145 .Case<CooperativeMatrixType, ImageType, MatrixType, PointerType,
146 RuntimeArrayType, ScalarType, TensorArmType, UntypedPointerType,
147 VectorType>(
148 [this](auto concreteType) { addConcrete(concreteType); })
149 .Case([this](ArrayType concreteType) {
150 add(concreteType.getElementType());
151 })
152 .Case([this](SampledImageType concreteType) {
153 add(concreteType.getImageType());
154 })
155 .Case([this](StructType concreteType) {
156 for (Type elementType : concreteType.getElementTypes())
157 add(elementType);
158 })
159 .Case([](SamplerType) { /* no capabilities */ })
160 .Case(
161 [this](NamedBarrierType) { pushCaps<Capability::NamedBarrier>(); })
162 .DefaultUnreachable("Unhandled type");
163 }
164
165 void add(Type type) {
166 if (auto functionType = dyn_cast<FunctionType>(type)) {
167 for (Type t : llvm::concat<const Type>(functionType.getInputs(),
168 functionType.getResults()))
169 add(t);
170 return;
171 }
172 add(cast<SPIRVType>(type));
173 }
174
175private:
176 // Types that add unique extensions.
177 void addConcrete(CooperativeMatrixType type);
178 void addConcrete(ImageType type);
179 void addConcrete(MatrixType type);
180 void addConcrete(PointerType type);
181 void addConcrete(RuntimeArrayType type);
182 void addConcrete(ScalarType type);
183 void addConcrete(TensorArmType type);
184 void addConcrete(UntypedPointerType type);
185 void addConcrete(VectorType type);
186
187 template <Capability... Cs>
188 void pushCaps() {
189 static constexpr Capability caps[] = {Cs...};
190 capabilities.push_back(caps);
191 }
192
194 std::optional<StorageClass> storage;
195 llvm::SmallDenseSet<std::pair<Type, std::optional<StorageClass>>> seen;
196};
197
198} // namespace
199
200//===----------------------------------------------------------------------===//
201// ArrayType
202//===----------------------------------------------------------------------===//
203
205 using KeyTy = std::tuple<Type, unsigned, unsigned>;
206
208 const KeyTy &key) {
209 return new (allocator.allocate<ArrayTypeStorage>()) ArrayTypeStorage(key);
210 }
211
212 bool operator==(const KeyTy &key) const {
213 return key == KeyTy(elementType, elementCount, stride);
214 }
215
217 : elementType(std::get<0>(key)), elementCount(std::get<1>(key)),
218 stride(std::get<2>(key)) {}
219
221 unsigned elementCount;
222 unsigned stride;
223};
224
225ArrayType ArrayType::get(Type elementType, unsigned elementCount) {
226 assert(elementCount && "ArrayType needs at least one element");
227 return Base::get(elementType.getContext(), elementType, elementCount,
228 /*stride=*/0);
229}
230
231ArrayType ArrayType::get(Type elementType, unsigned elementCount,
232 unsigned stride) {
233 assert(elementCount && "ArrayType needs at least one element");
234 return Base::get(elementType.getContext(), elementType, elementCount, stride);
235}
236
237unsigned ArrayType::getNumElements() const { return getImpl()->elementCount; }
238
239Type ArrayType::getElementType() const { return getImpl()->elementType; }
240
241unsigned ArrayType::getArrayStride() const { return getImpl()->stride; }
242
243//===----------------------------------------------------------------------===//
244// CompositeType
245//===----------------------------------------------------------------------===//
246
248 if (auto vectorType = dyn_cast<VectorType>(type))
249 return isValid(vectorType);
252 type);
253}
254
255bool CompositeType::isValid(VectorType type) {
256 return type.getRank() == 1 &&
257 llvm::is_contained({2, 3, 4, 8, 16}, type.getNumElements()) &&
258 (isa<ScalarType>(type.getElementType()) ||
259 isa<PointerType>(type.getElementType()));
260}
261
263 return TypeSwitch<Type, Type>(*this)
265 TensorArmType>([](auto type) { return type.getElementType(); })
266 .Case([](MatrixType type) { return type.getColumnType(); })
267 .Case([index](StructType type) { return type.getElementType(index); })
268 .DefaultUnreachable("Invalid composite type");
269}
270
273 .Case<ArrayType, StructType, TensorArmType, VectorType>(
274 [](auto type) { return type.getNumElements(); })
275 .Case([](MatrixType type) { return type.getNumColumns(); })
276 .DefaultUnreachable("Invalid type for number of elements query");
277}
278
280 return !isa<CooperativeMatrixType, RuntimeArrayType>(*this);
281}
282
283void TypeCapabilityVisitor::addConcrete(VectorType type) {
284 add(type.getElementType());
285
286 int64_t vecSize = type.getNumElements();
287 if (vecSize == 8 || vecSize == 16)
288 pushCaps<Capability::Vector16>();
289}
290
291//===----------------------------------------------------------------------===//
292// CooperativeMatrixType
293//===----------------------------------------------------------------------===//
294
296 // In the specification dimensions of the Cooperative Matrix are 32-bit
297 // integers --- the initial implementation kept those values as such. However,
298 // the `ShapedType` expects the shape to be `int64_t`. We could keep the shape
299 // as 32-bits and expose it as int64_t through `getShape`, however, this
300 // method returns an `ArrayRef`, so returning `ArrayRef<int64_t>` having two
301 // 32-bits integers would require an extra logic and storage. So, we diverge
302 // from the spec and internally represent the dimensions as 64-bit integers,
303 // so we can easily return an `ArrayRef` from `getShape` without any extra
304 // logic. Alternatively, we could store both rows and columns (both 32-bits)
305 // and shape (64-bits), assigning rows and columns to shape whenever
306 // `getShape` is called. This would be at the cost of extra logic and storage.
307 // Note: Because `ArrayRef` is returned we cannot construct an object in
308 // `getShape` on the fly.
309 using KeyTy =
310 std::tuple<Type, int64_t, int64_t, Scope, CooperativeMatrixUseKHR>;
311
313 construct(TypeStorageAllocator &allocator, const KeyTy &key) {
314 return new (allocator.allocate<CooperativeMatrixTypeStorage>())
316 }
317
318 bool operator==(const KeyTy &key) const {
319 return key == KeyTy(elementType, shape[0], shape[1], scope, use);
320 }
321
323 : elementType(std::get<0>(key)),
324 shape({std::get<1>(key), std::get<2>(key)}), scope(std::get<3>(key)),
325 use(std::get<4>(key)) {}
326
328 // [#rows, #columns]
329 std::array<int64_t, 2> shape;
330 Scope scope;
331 CooperativeMatrixUseKHR use;
332};
333
336 MLIRContext *context, Type elementType,
337 uint32_t rows, uint32_t columns, Scope scope,
338 CooperativeMatrixUseKHR use) {
339 return Base::getChecked(emitError, context, elementType, rows, columns, scope,
340 use);
341}
342
345 uint32_t rows, uint32_t columns, Scope scope, CooperativeMatrixUseKHR use) {
346 if (containsMicroscalingType(elementType))
347 return emitError()
348 << "microscaling types are not supported in cooperative matrices";
349 return success();
350}
351
353 uint32_t rows,
354 uint32_t columns, Scope scope,
355 CooperativeMatrixUseKHR use) {
356 return Base::get(elementType.getContext(), elementType, rows, columns, scope,
357 use);
358}
359
361 return getImpl()->elementType;
362}
363
365 assert(getImpl()->shape[0] != ShapedType::kDynamic);
366 return static_cast<uint32_t>(getImpl()->shape[0]);
367}
368
370 assert(getImpl()->shape[1] != ShapedType::kDynamic);
371 return static_cast<uint32_t>(getImpl()->shape[1]);
372}
373
377
378Scope CooperativeMatrixType::getScope() const { return getImpl()->scope; }
379
380CooperativeMatrixUseKHR CooperativeMatrixType::getUse() const {
381 return getImpl()->use;
382}
383
384void TypeExtensionVisitor::addConcrete(CooperativeMatrixType type) {
385 add(type.getElementType());
386 pushExts<Extension::SPV_KHR_cooperative_matrix>();
387}
388
389void TypeCapabilityVisitor::addConcrete(CooperativeMatrixType type) {
390 Type elementType = type.getElementType();
391 add(elementType);
392 pushCaps<Capability::CooperativeMatrixKHR>();
393 if (elementType.isBF16())
394 pushCaps<Capability::BFloat16CooperativeMatrixKHR>();
395 if (elementType.isF8E4M3FN() || elementType.isF8E5M2())
396 pushCaps<Capability::Float8CooperativeMatrixEXT>();
397}
398
399//===----------------------------------------------------------------------===//
400// ImageType
401//===----------------------------------------------------------------------===//
402
403template <typename T>
404static constexpr unsigned getNumBits() {
405 return 0;
406}
407template <>
408constexpr unsigned getNumBits<Dim>() {
409 static_assert((1 << 3) > getMaxEnumValForDim(),
410 "Not enough bits to encode Dim value");
411 return 3;
412}
413template <>
414constexpr unsigned getNumBits<ImageDepthInfo>() {
415 static_assert((1 << 2) > getMaxEnumValForImageDepthInfo(),
416 "Not enough bits to encode ImageDepthInfo value");
417 return 2;
418}
419template <>
420constexpr unsigned getNumBits<ImageArrayedInfo>() {
421 static_assert((1 << 1) > getMaxEnumValForImageArrayedInfo(),
422 "Not enough bits to encode ImageArrayedInfo value");
423 return 1;
424}
425template <>
426constexpr unsigned getNumBits<ImageSamplingInfo>() {
427 static_assert((1 << 1) > getMaxEnumValForImageSamplingInfo(),
428 "Not enough bits to encode ImageSamplingInfo value");
429 return 1;
430}
431template <>
433 static_assert((1 << 2) > getMaxEnumValForImageSamplerUseInfo(),
434 "Not enough bits to encode ImageSamplerUseInfo value");
435 return 2;
436}
437template <>
438constexpr unsigned getNumBits<ImageFormat>() {
439 static_assert((1 << 6) > getMaxEnumValForImageFormat(),
440 "Not enough bits to encode ImageFormat value");
441 return 6;
442}
443
445public:
446 using KeyTy = std::tuple<Type, Dim, ImageDepthInfo, ImageArrayedInfo,
447 ImageSamplingInfo, ImageSamplerUseInfo, ImageFormat>;
448
450 const KeyTy &key) {
451 return new (allocator.allocate<ImageTypeStorage>()) ImageTypeStorage(key);
452 }
453
454 bool operator==(const KeyTy &key) const {
457 }
458
460 : elementType(std::get<0>(key)), dim(std::get<1>(key)),
461 depthInfo(std::get<2>(key)), arrayedInfo(std::get<3>(key)),
462 samplingInfo(std::get<4>(key)), samplerUseInfo(std::get<5>(key)),
463 format(std::get<6>(key)) {}
464
472};
473
476 std::tuple<Type, Dim, ImageDepthInfo, ImageArrayedInfo, ImageSamplingInfo,
477 ImageSamplerUseInfo, ImageFormat>
478 value) {
479 return Base::getChecked(emitError, context, value);
480}
481
484 std::tuple<Type, Dim, ImageDepthInfo, ImageArrayedInfo, ImageSamplingInfo,
485 ImageSamplerUseInfo, ImageFormat>
486 value) {
487 if (containsMicroscalingType(std::get<0>(value)))
488 return emitError() << "microscaling types are not supported in images";
489 return success();
490}
491
493ImageType::get(std::tuple<Type, Dim, ImageDepthInfo, ImageArrayedInfo,
494 ImageSamplingInfo, ImageSamplerUseInfo, ImageFormat>
495 value) {
496 return Base::get(std::get<0>(value).getContext(), value);
497}
498
499Type ImageType::getElementType() const { return getImpl()->elementType; }
500
501Dim ImageType::getDim() const { return getImpl()->dim; }
502
503ImageDepthInfo ImageType::getDepthInfo() const { return getImpl()->depthInfo; }
504
505ImageArrayedInfo ImageType::getArrayedInfo() const {
506 return getImpl()->arrayedInfo;
507}
508
509ImageSamplingInfo ImageType::getSamplingInfo() const {
510 return getImpl()->samplingInfo;
511}
512
513ImageSamplerUseInfo ImageType::getSamplerUseInfo() const {
514 return getImpl()->samplerUseInfo;
515}
516
517ImageFormat ImageType::getImageFormat() const { return getImpl()->format; }
518
519void TypeExtensionVisitor::addConcrete(ImageType type) {
520 // OpTypeImage with a 64-bit integer Sampled Type requires the
521 // SPV_EXT_shader_image_int64 extension (companion to Int64ImageEXT).
522 if (auto intTy = dyn_cast<IntegerType>(type.getElementType());
523 intTy && intTy.getWidth() == 64)
524 pushExts<Extension::SPV_EXT_shader_image_int64>();
525 add(type.getElementType());
526}
527
528void TypeCapabilityVisitor::addConcrete(ImageType type) {
529 // Capability requirements for OpTypeImage are determined jointly by Dim,
530 // Sampled, MS, and Arrayed - see the SPIR-V spec's "Capabilities" column on
531 // OpTypeImage.
532 Dim dim = type.getDim();
533 bool isMultisampled =
534 type.getSamplingInfo() == ImageSamplingInfo::MultiSampled;
535 bool isArrayed = type.getArrayedInfo() == ImageArrayedInfo::Arrayed;
536 ImageSamplerUseInfo sampler = type.getSamplerUseInfo();
537 bool noSampler = sampler == ImageSamplerUseInfo::NoSampler;
538 bool needSampler = sampler == ImageSamplerUseInfo::NeedSampler;
539
540 switch (dim) {
541 case Dim::Dim1D:
542 if (needSampler)
543 pushCaps<Capability::Sampled1D>();
544 else if (noSampler)
545 pushCaps<Capability::Image1D>();
546 else
547 pushCaps<Capability::Image1D, Capability::Sampled1D>();
548 break;
549 case Dim::Dim2D:
550 if (isMultisampled && noSampler)
551 pushCaps<Capability::StorageImageMultisample>();
552 if (isMultisampled && isArrayed)
553 pushCaps<Capability::ImageMSArray>();
554 break;
555 case Dim::Dim3D:
556 break;
557 case Dim::Cube:
558 pushCaps<Capability::Shader>();
559 if (isArrayed)
560 pushCaps<Capability::ImageCubeArray>();
561 break;
562 case Dim::Rect:
563 pushCaps<Capability::ImageRect, Capability::SampledRect>();
564 break;
565 case Dim::Buffer:
566 if (needSampler)
567 pushCaps<Capability::SampledBuffer>();
568 else if (noSampler)
569 pushCaps<Capability::ImageBuffer>();
570 else
571 pushCaps<Capability::ImageBuffer, Capability::SampledBuffer>();
572 break;
573 case Dim::SubpassData:
574 pushCaps<Capability::InputAttachment>();
575 break;
576 }
577
578 if (auto fmtCaps = spirv::getCapabilities(type.getImageFormat()))
579 capabilities.push_back(*fmtCaps);
580
581 // OpTypeImage with a 64-bit integer Sampled Type requires Int64ImageEXT.
582 if (auto intTy = dyn_cast<IntegerType>(type.getElementType());
583 intTy && intTy.getWidth() == 64)
584 pushCaps<Capability::Int64ImageEXT>();
585
586 add(type.getElementType());
587}
588
589//===----------------------------------------------------------------------===//
590// PointerType
591//===----------------------------------------------------------------------===//
592
594 // (Type, StorageClass) as the key: Type stored in this struct, and
595 // StorageClass stored as TypeStorage's subclass data.
596 using KeyTy = std::pair<Type, StorageClass>;
597
599 const KeyTy &key) {
600 return new (allocator.allocate<PointerTypeStorage>())
602 }
603
604 bool operator==(const KeyTy &key) const {
605 return key == KeyTy(pointeeType, storageClass);
606 }
607
609 : pointeeType(key.first), storageClass(key.second) {}
610
612 StorageClass storageClass;
613};
614
617 MLIRContext *context, Type pointeeType,
618 StorageClass storageClass) {
619 return Base::getChecked(emitError, context, pointeeType, storageClass);
620}
621
622LogicalResult
624 Type pointeeType, StorageClass storageClass) {
625 if (storageClass != StorageClass::Function &&
626 storageClass != StorageClass::Private &&
627 containsMicroscalingType(pointeeType, /*subByteOnly=*/true))
628 return emitError()
629 << "FP4 and FP6 types require Function or Private storage";
630 return success();
631}
632
633PointerType PointerType::get(Type pointeeType, StorageClass storageClass) {
634 return Base::get(pointeeType.getContext(), pointeeType, storageClass);
635}
636
637Type PointerType::getPointeeType() const { return getImpl()->pointeeType; }
638
639StorageClass PointerType::getStorageClass() const {
640 return getImpl()->storageClass;
641}
642
643void TypeExtensionVisitor::addConcrete(PointerType type) {
644 // Use this pointer type's storage class because this pointer indicates we are
645 // using the pointee type in that specific storage class.
646 std::optional<StorageClass> oldStorageClass = storage;
647 storage = type.getStorageClass();
648 add(type.getPointeeType());
649 storage = oldStorageClass;
650
651 if (auto scExts = spirv::getExtensions(type.getStorageClass()))
652 extensions.push_back(*scExts);
653}
654
655void TypeCapabilityVisitor::addConcrete(PointerType type) {
656 // Use this pointer type's storage class because this pointer indicates we are
657 // using the pointee type in that specific storage class.
658 std::optional<StorageClass> oldStorageClass = storage;
659 storage = type.getStorageClass();
660 add(type.getPointeeType());
661 storage = oldStorageClass;
662
663 if (auto scCaps = spirv::getCapabilities(type.getStorageClass()))
664 capabilities.push_back(*scCaps);
665}
666
667//===----------------------------------------------------------------------===//
668// UntypedPointerType
669//===----------------------------------------------------------------------===//
670
672 using KeyTy = StorageClass;
673
675 const KeyTy &key) {
676 return new (allocator.allocate<UntypedPointerTypeStorage>())
678 }
679
680 bool operator==(const KeyTy &key) const { return key == storageClass; }
681
683
684 StorageClass storageClass;
685};
686
688 StorageClass storageClass) {
689 return Base::get(context, storageClass);
690}
691
693 return getImpl()->storageClass;
694}
695
696void TypeExtensionVisitor::addConcrete(UntypedPointerType type) {
697 pushExts<Extension::SPV_KHR_untyped_pointers>();
698 if (auto scExts = spirv::getExtensions(type.getStorageClass()))
699 extensions.push_back(*scExts);
700}
701
702void TypeCapabilityVisitor::addConcrete(UntypedPointerType type) {
703 pushCaps<Capability::UntypedPointersKHR>();
704 if (auto scCaps = spirv::getCapabilities(type.getStorageClass()))
705 capabilities.push_back(*scCaps);
706}
707
708//===----------------------------------------------------------------------===//
709// RuntimeArrayType
710//===----------------------------------------------------------------------===//
711
713 using KeyTy = std::pair<Type, unsigned>;
714
716 const KeyTy &key) {
717 return new (allocator.allocate<RuntimeArrayTypeStorage>())
719 }
720
721 bool operator==(const KeyTy &key) const {
722 return key == KeyTy(elementType, stride);
723 }
724
726 : elementType(key.first), stride(key.second) {}
727
729 unsigned stride;
730};
731
733 return Base::get(elementType.getContext(), elementType, /*stride=*/0);
734}
735
736RuntimeArrayType RuntimeArrayType::get(Type elementType, unsigned stride) {
737 return Base::get(elementType.getContext(), elementType, stride);
738}
739
740Type RuntimeArrayType::getElementType() const { return getImpl()->elementType; }
741
742unsigned RuntimeArrayType::getArrayStride() const { return getImpl()->stride; }
743
744void TypeCapabilityVisitor::addConcrete(RuntimeArrayType type) {
745 add(type.getElementType());
746 pushCaps<Capability::Shader>();
747}
748
749//===----------------------------------------------------------------------===//
750// ScalarType
751//===----------------------------------------------------------------------===//
752
754 if (auto floatType = dyn_cast<FloatType>(type)) {
755 return isValid(floatType);
756 }
757 if (auto intType = dyn_cast<IntegerType>(type)) {
758 return isValid(intType);
759 }
760 return false;
761}
762
763bool ScalarType::isValid(FloatType type) {
764 if (llvm::is_contained({16u, 32u, 64u}, type.getWidth()))
765 return true;
766 return isa<Float8E4M3FNType, Float8E5M2Type, Float4E2M1FNType,
767 Float6E2M3FNType, Float6E3M2FNType, Float8E8M0FNUType>(type);
768}
769
770bool ScalarType::isValid(IntegerType type) {
771 return llvm::is_contained({1u, 8u, 16u, 32u, 64u}, type.getWidth());
772}
773
774void TypeExtensionVisitor::addConcrete(ScalarType type) {
775 if (type.isBF16())
776 pushExts<Extension::SPV_KHR_bfloat16>();
777
778 if (type.isF8E4M3FN() || type.isF8E5M2())
779 pushExts<Extension::SPV_EXT_float8>();
780
781 if (isa<Float4E2M1FNType, Float6E2M3FNType, Float6E3M2FNType,
782 Float8E8M0FNUType>(type)) {
783 pushExts<Extension::SPV_EXT_ocp_microscaling_types>();
784 pushExts<Extension::SPV_EXT_float8>();
785 }
786
787 // 8- or 16-bit integer/floating-point numbers will require extra extensions
788 // to appear in interface storage classes. See SPV_KHR_16bit_storage and
789 // SPV_KHR_8bit_storage for more details.
790 if (!storage)
791 return;
792
793 switch (*storage) {
794 case StorageClass::PushConstant:
795 case StorageClass::StorageBuffer:
796 case StorageClass::Uniform:
797 if (type.getIntOrFloatBitWidth() == 8)
798 pushExts<Extension::SPV_KHR_8bit_storage>();
799 [[fallthrough]];
800 case StorageClass::Input:
801 case StorageClass::Output:
802 if (type.getIntOrFloatBitWidth() == 16)
803 pushExts<Extension::SPV_KHR_16bit_storage>();
804 break;
805 default:
806 break;
807 }
808}
809
810void TypeCapabilityVisitor::addConcrete(ScalarType type) {
811 unsigned bitwidth = type.getIntOrFloatBitWidth();
812
813 // Interface storage capabilities may return before the scalar capability
814 // dispatch below.
815 if (isa<Float8E8M0FNUType>(type))
816 pushCaps<Capability::Float8UnsignedE8M0EXT>();
817
818 // 8- or 16-bit integer/floating-point numbers will require extra capabilities
819 // to appear in interface storage classes. See SPV_KHR_16bit_storage and
820 // SPV_KHR_8bit_storage for more details.
821
822#define STORAGE_CASE(storage, cap8, cap16) \
823 case StorageClass::storage: { \
824 if (bitwidth == 8) { \
825 pushCaps<Capability::cap8>(); \
826 return; \
827 } \
828 if (bitwidth == 16) { \
829 pushCaps<Capability::cap16>(); \
830 return; \
831 } \
832 /* For 64-bit integers/floats, Int64/Float64 enables support for all */ \
833 /* storage classes. Fall through to the next section. */ \
834 } break
835
836 // This part only handles the cases where special bitwidths appearing in
837 // interface storage classes.
838 if (storage) {
839 switch (*storage) {
840 STORAGE_CASE(PushConstant, StoragePushConstant8, StoragePushConstant16);
841 STORAGE_CASE(StorageBuffer, StorageBuffer8BitAccess,
842 StorageBuffer16BitAccess);
843 STORAGE_CASE(Uniform, UniformAndStorageBuffer8BitAccess,
844 StorageUniform16);
845 case StorageClass::Input:
846 case StorageClass::Output: {
847 if (bitwidth == 16) {
848 pushCaps<Capability::StorageInputOutput16>();
849 return;
850 }
851 break;
852 }
853 default:
854 break;
855 }
856 }
857#undef STORAGE_CASE
858
859 // For other non-interface storage classes, require a different set of
860 // capabilities for special bitwidths.
861
862#define WIDTH_CASE(type, width) \
863 case width: \
864 pushCaps<Capability::type##width>(); \
865 break
866
867 if (auto intType = dyn_cast<IntegerType>(type)) {
868 switch (bitwidth) {
869 WIDTH_CASE(Int, 8);
870 WIDTH_CASE(Int, 16);
871 WIDTH_CASE(Int, 64);
872 case 1:
873 case 32:
874 break;
875 default:
876 llvm_unreachable("invalid bitwidth to getCapabilities");
877 }
878 } else {
879 assert(isa<FloatType>(type));
880 switch (bitwidth) {
881 case 4:
882 pushCaps<Capability::Float4EXT>();
883 break;
884 case 6:
885 pushCaps<Capability::Float6EXT>();
886 break;
887 case 8: {
888 if (type.isF8E4M3FN() || type.isF8E5M2())
889 pushCaps<Capability::Float8EXT>();
890 else if (!isa<Float8E8M0FNUType>(type))
891 llvm_unreachable("invalid 8-bit float type to getCapabilities");
892 break;
893 }
894 case 16: {
895 if (type.isBF16())
896 pushCaps<Capability::BFloat16TypeKHR>();
897 else
898 pushCaps<Capability::Float16>();
899 break;
900 }
901 WIDTH_CASE(Float, 64);
902 case 32:
903 break;
904 default:
905 llvm_unreachable("invalid bitwidth to getCapabilities");
906 }
907 }
908
909#undef WIDTH_CASE
910}
911
912//===----------------------------------------------------------------------===//
913// SPIRVType
914//===----------------------------------------------------------------------===//
915
917 // Allow SPIR-V dialect types
918 if (isa<SPIRVDialect>(type.getDialect()))
919 return true;
920 if (isa<ScalarType>(type))
921 return true;
922 if (auto vectorType = dyn_cast<VectorType>(type))
923 return CompositeType::isValid(vectorType);
924 if (auto tensorArmType = dyn_cast<TensorArmType>(type))
925 return isa<ScalarType>(tensorArmType.getElementType());
926 return false;
927}
928
930 return isIntOrFloat() || isa<VectorType>(*this);
931}
932
934 std::optional<StorageClass> storage) {
935 TypeExtensionVisitor{extensions, storage}.add(*this);
936}
937
940 std::optional<StorageClass> storage) {
941 TypeCapabilityVisitor{capabilities, storage}.add(*this);
942}
943
944std::optional<int64_t> SPIRVType::getSizeInBytes() {
946 .Case([](ScalarType type) -> std::optional<int64_t> {
947 // According to the SPIR-V spec:
948 // "There is no physical size or bit pattern defined for values with
949 // boolean type. If they are stored (in conjunction with OpVariable),
950 // they can only be used with logical addressing operations, not
951 // physical, and only with non-externally visible shader Storage
952 // Classes: Workgroup, CrossWorkgroup, Private, Function, Input, and
953 // Output."
954 //
955 // FP4 and FP6 have sub-byte widths. This helper has no storage-layout
956 // rule for these formats, so their size in whole bytes cannot be
957 // inferred from their bit width. Return std::nullopt for them as well
958 // to avoid reporting zero bytes after integer division by eight.
959 int64_t bitWidth = type.getIntOrFloatBitWidth();
960 if (bitWidth % 8 != 0)
961 return std::nullopt;
962 return bitWidth / 8;
963 })
964 .Case([](ArrayType type) -> std::optional<int64_t> {
965 // The stride, if set, is the per-element byte distance and already
966 // includes the element size; otherwise the array is tightly packed.
967 auto elementType = cast<SPIRVType>(type.getElementType());
968 if (unsigned stride = type.getArrayStride())
969 return stride * type.getNumElements();
970 if (std::optional<int64_t> size = elementType.getSizeInBytes())
971 return *size * type.getNumElements();
972 return std::nullopt;
973 })
974 .Case<VectorType, TensorArmType>([](auto type) -> std::optional<int64_t> {
975 if (std::optional<int64_t> elementSize =
976 cast<ScalarType>(type.getElementType()).getSizeInBytes())
977 return *elementSize * type.getNumElements();
978 return std::nullopt;
979 })
980 .Default(std::nullopt);
981}
982
983//===----------------------------------------------------------------------===//
984// SampledImageType
985//===----------------------------------------------------------------------===//
987 using KeyTy = Type;
988
990
991 bool operator==(const KeyTy &key) const { return key == KeyTy(imageType); }
992
994 const KeyTy &key) {
995 return new (allocator.allocate<SampledImageTypeStorage>())
997 }
998
1000};
1001
1003 return Base::get(imageType.getContext(), imageType);
1004}
1005
1008 Type imageType) {
1009 return Base::getChecked(emitError, imageType.getContext(), imageType);
1010}
1011
1012Type SampledImageType::getImageType() const { return getImpl()->imageType; }
1013
1014LogicalResult
1016 Type imageType) {
1017 auto image = dyn_cast<ImageType>(imageType);
1018 if (!image)
1019 return emitError() << "expected image type";
1020
1021 // As per SPIR-V spec: "It [ImageType] must not have a Dim of SubpassData.
1022 // Additionally, starting with version 1.6, it must not have a Dim of Buffer.
1023 // ("3.3.6. Type-Declaration Instructions")
1024 if (llvm::is_contained({Dim::SubpassData, Dim::Buffer}, image.getDim()))
1025 return emitError() << "Dim must not be SubpassData or Buffer";
1026
1027 return success();
1028}
1029
1030//===----------------------------------------------------------------------===//
1031// SamplerType
1032//===----------------------------------------------------------------------===//
1033
1035 return Base::get(context);
1036}
1037
1038//===----------------------------------------------------------------------===//
1039// NamedBarrierType
1040//===----------------------------------------------------------------------===//
1041
1043 return Base::get(context);
1044}
1045
1046//===----------------------------------------------------------------------===//
1047// StructType
1048//===----------------------------------------------------------------------===//
1049
1050/// Type storage for SPIR-V structure types:
1051///
1052/// Structures are uniqued using:
1053/// - for identified structs:
1054/// - a string identifier;
1055/// - for literal structs:
1056/// - a list of member types;
1057/// - a list of member offset info;
1058/// - a list of member decoration info;
1059/// - a list of struct decoration info.
1060///
1061/// Identified structures only have a mutable component consisting of:
1062/// - a list of member types;
1063/// - a list of member offset info;
1064/// - a list of member decoration info;
1065/// - a list of struct decoration info.
1067 /// Construct a storage object for an identified struct type. A struct type
1068 /// associated with such storage must call StructType::trySetBody(...) later
1069 /// in order to mutate the storage object providing the actual content.
1075
1076 /// Construct a storage object for a literal struct type. A struct type
1077 /// associated with such storage is immutable.
1089
1090 /// A storage key is divided into 2 parts:
1091 /// - for identified structs:
1092 /// - a StringRef representing the struct identifier;
1093 /// - for literal structs:
1094 /// - an ArrayRef<Type> for member types;
1095 /// - an ArrayRef<StructType::OffsetInfo> for member offset info;
1096 /// - an ArrayRef<StructType::MemberDecorationInfo> for member decoration
1097 /// info;
1098 /// - an ArrayRef<StructType::StructDecorationInfo> for struct decoration
1099 /// info.
1100 ///
1101 /// An identified struct type is uniqued only by the first part (field 0)
1102 /// of the key.
1103 ///
1104 /// A literal struct type is uniqued only by the second part (fields 1, 2, 3
1105 /// and 4) of the key. The identifier field (field 0) must be empty.
1106 using KeyTy =
1107 std::tuple<StringRef, ArrayRef<Type>, ArrayRef<StructType::OffsetInfo>,
1110
1111 /// For identified structs, return true if the given key contains the same
1112 /// identifier.
1113 ///
1114 /// For literal structs, return true if the given key contains a matching list
1115 /// of member types + offset info + decoration info.
1116 bool operator==(const KeyTy &key) const {
1117 if (isIdentified()) {
1118 // Identified types are uniqued by their identifier.
1119 return getIdentifier() == std::get<0>(key);
1120 }
1121
1122 return key == KeyTy(StringRef(), getMemberTypes(), getOffsetInfo(),
1124 }
1125
1126 /// If the given key contains a non-empty identifier, this method constructs
1127 /// an identified struct and leaves the rest of the struct type data to be set
1128 /// through a later call to StructType::trySetBody(...).
1129 ///
1130 /// If, on the other hand, the key contains an empty identifier, a literal
1131 /// struct is constructed using the other fields of the key.
1133 const KeyTy &key) {
1134 StringRef keyIdentifier = std::get<0>(key);
1135
1136 if (!keyIdentifier.empty()) {
1137 StringRef identifier = allocator.copyInto(keyIdentifier);
1138
1139 // Identified StructType body/members will be set through trySetBody(...)
1140 // later.
1141 return new (allocator.allocate<StructTypeStorage>())
1143 }
1144
1145 ArrayRef<Type> keyTypes = std::get<1>(key);
1146
1147 // Copy the member type and layout information into the bump pointer
1148 const Type *typesList = nullptr;
1149 if (!keyTypes.empty()) {
1150 typesList = allocator.copyInto(keyTypes).data();
1151 }
1152
1153 const StructType::OffsetInfo *offsetInfoList = nullptr;
1154 if (!std::get<2>(key).empty()) {
1155 ArrayRef<StructType::OffsetInfo> keyOffsetInfo = std::get<2>(key);
1156 assert(keyOffsetInfo.size() == keyTypes.size() &&
1157 "size of offset information must be same as the size of number of "
1158 "elements");
1159 offsetInfoList = allocator.copyInto(keyOffsetInfo).data();
1160 }
1161
1162 const StructType::MemberDecorationInfo *memberDecorationList = nullptr;
1163 unsigned numMemberDecorations = 0;
1164 if (!std::get<3>(key).empty()) {
1165 auto keyMemberDecorations = std::get<3>(key);
1166 numMemberDecorations = keyMemberDecorations.size();
1167 memberDecorationList = allocator.copyInto(keyMemberDecorations).data();
1168 }
1169
1170 const StructType::StructDecorationInfo *structDecorationList = nullptr;
1171 unsigned numStructDecorations = 0;
1172 if (!std::get<4>(key).empty()) {
1173 auto keyStructDecorations = std::get<4>(key);
1174 numStructDecorations = keyStructDecorations.size();
1175 structDecorationList = allocator.copyInto(keyStructDecorations).data();
1176 }
1177
1178 return new (allocator.allocate<StructTypeStorage>()) StructTypeStorage(
1179 keyTypes.size(), typesList, offsetInfoList, numMemberDecorations,
1180 memberDecorationList, numStructDecorations, structDecorationList);
1181 }
1182
1186
1193
1201
1208
1209 StringRef getIdentifier() const { return identifier; }
1210
1211 bool isIdentified() const { return !identifier.empty(); }
1212
1213 /// Sets the struct type content for identified structs. Calling this method
1214 /// is only valid for identified structs.
1215 ///
1216 /// Fails under the following conditions:
1217 /// - If called for a literal struct;
1218 /// - If called for an identified struct whose body was set before (through a
1219 /// call to this method) but with different contents from the passed
1220 /// arguments.
1221 LogicalResult
1222 mutate(TypeStorageAllocator &allocator, ArrayRef<Type> structMemberTypes,
1223 ArrayRef<StructType::OffsetInfo> structOffsetInfo,
1224 ArrayRef<StructType::MemberDecorationInfo> structMemberDecorationInfo,
1225 ArrayRef<StructType::StructDecorationInfo> structDecorationInfo) {
1226 if (!isIdentified())
1227 return failure();
1228
1229 if (memberTypesAndIsBodySet.getInt() &&
1230 (getMemberTypes() != structMemberTypes ||
1231 getOffsetInfo() != structOffsetInfo ||
1232 getMemberDecorationsInfo() != structMemberDecorationInfo ||
1233 getStructDecorationsInfo() != structDecorationInfo))
1234 return failure();
1235
1236 memberTypesAndIsBodySet.setInt(true);
1237 numMembers = structMemberTypes.size();
1238
1239 // Copy the member type and layout information into the bump pointer.
1240 if (!structMemberTypes.empty())
1241 memberTypesAndIsBodySet.setPointer(
1242 allocator.copyInto(structMemberTypes).data());
1243
1244 if (!structOffsetInfo.empty()) {
1245 assert(structOffsetInfo.size() == structMemberTypes.size() &&
1246 "size of offset information must be same as the size of number of "
1247 "elements");
1248 offsetInfo = allocator.copyInto(structOffsetInfo).data();
1249 }
1250
1251 if (!structMemberDecorationInfo.empty()) {
1252 numMemberDecorations = structMemberDecorationInfo.size();
1254 allocator.copyInto(structMemberDecorationInfo).data();
1255 }
1256
1257 if (!structDecorationInfo.empty()) {
1258 numStructDecorations = structDecorationInfo.size();
1259 structDecorationsInfo = allocator.copyInto(structDecorationInfo).data();
1260 }
1261
1262 return success();
1263 }
1264
1265 llvm::PointerIntPair<Type const *, 1, bool> memberTypesAndIsBodySet;
1267 unsigned numMembers;
1272 StringRef identifier;
1273};
1274
1280 assert(!memberTypes.empty() && "Struct needs at least one member type");
1281 // Sort the decorations.
1283 memberDecorations);
1284 llvm::array_pod_sort(sortedMemberDecorations.begin(),
1285 sortedMemberDecorations.end());
1287 structDecorations);
1288 llvm::array_pod_sort(sortedStructDecorations.begin(),
1289 sortedStructDecorations.end());
1290
1291 return Base::get(memberTypes.vec().front().getContext(),
1292 /*identifier=*/StringRef(), memberTypes, offsetInfo,
1293 sortedMemberDecorations, sortedStructDecorations);
1294}
1295
1297 StringRef identifier) {
1298 assert(!identifier.empty() &&
1299 "StructType identifier must be non-empty string");
1300
1301 return Base::get(context, identifier, ArrayRef<Type>(),
1305}
1306
1307StructType StructType::getEmpty(MLIRContext *context, StringRef identifier) {
1308 StructType newStructType = Base::get(
1309 context, identifier, ArrayRef<Type>(), ArrayRef<StructType::OffsetInfo>(),
1312 // Set an empty body in case this is a identified struct.
1313 if (newStructType.isIdentified() &&
1314 failed(newStructType.trySetBody(
1318 return StructType();
1319
1320 return newStructType;
1321}
1322
1323StringRef StructType::getIdentifier() const { return getImpl()->identifier; }
1324
1325bool StructType::isIdentified() const { return getImpl()->isIdentified(); }
1326
1327unsigned StructType::getNumElements() const { return getImpl()->numMembers; }
1328
1330 assert(getNumElements() > index && "member index out of range");
1331 return getImpl()->memberTypesAndIsBodySet.getPointer()[index];
1332}
1333
1335 return TypeRange(getImpl()->memberTypesAndIsBodySet.getPointer(),
1336 getNumElements());
1337}
1338
1339bool StructType::hasOffset() const { return getImpl()->offsetInfo; }
1340
1341bool StructType::hasDecoration(spirv::Decoration decoration) const {
1343 getImpl()->getStructDecorationsInfo())
1344 if (info.decoration == decoration)
1345 return true;
1346
1347 return false;
1348}
1349
1350uint64_t StructType::getMemberOffset(unsigned index) const {
1351 assert(getNumElements() > index && "member index out of range");
1352 return getImpl()->offsetInfo[index];
1353}
1354
1357 const {
1358 memberDecorations.clear();
1359 auto implMemberDecorations = getImpl()->getMemberDecorationsInfo();
1360 memberDecorations.append(implMemberDecorations.begin(),
1361 implMemberDecorations.end());
1362}
1363
1365 unsigned index,
1367 assert(getNumElements() > index && "member index out of range");
1368 auto memberDecorations = getImpl()->getMemberDecorationsInfo();
1369 decorationsInfo.clear();
1370 for (const auto &memberDecoration : memberDecorations) {
1371 if (memberDecoration.memberIndex == index) {
1372 decorationsInfo.push_back(memberDecoration);
1373 }
1374 if (memberDecoration.memberIndex > index) {
1375 // Early exit since the decorations are stored sorted.
1376 return;
1377 }
1378 }
1379}
1380
1383 const {
1384 structDecorations.clear();
1385 auto implDecorations = getImpl()->getStructDecorationsInfo();
1386 structDecorations.append(implDecorations.begin(), implDecorations.end());
1387}
1388
1389LogicalResult
1391 ArrayRef<OffsetInfo> offsetInfo,
1392 ArrayRef<MemberDecorationInfo> memberDecorations,
1393 ArrayRef<StructDecorationInfo> structDecorations) {
1394 return Base::mutate(memberTypes, offsetInfo, memberDecorations,
1395 structDecorations);
1396}
1397
1398llvm::hash_code spirv::hash_value(
1399 const StructType::MemberDecorationInfo &memberDecorationInfo) {
1400 return llvm::hash_combine(memberDecorationInfo.memberIndex,
1401 memberDecorationInfo.decoration);
1402}
1403
1404llvm::hash_code spirv::hash_value(
1405 const StructType::StructDecorationInfo &structDecorationInfo) {
1406 return llvm::hash_value(structDecorationInfo.decoration);
1407}
1408
1409//===----------------------------------------------------------------------===//
1410// MatrixType
1411//===----------------------------------------------------------------------===//
1412
1414 // Use a 64-bit integer as a column count internally to better support a
1415 // `ShapedType` interface. See comment in `CooperativeMatrixType` for more
1416 // context.
1417 using KeyTy = std::tuple<Type, int64_t>;
1418
1420 : columnType(std::get<0>(key)),
1421 shape({cast<VectorType>(std::get<0>(key)).getShape()[0],
1422 std::get<1>(key)}) {}
1423
1425 const KeyTy &key) {
1426
1427 // Initialize the memory using placement new.
1428 return new (allocator.allocate<MatrixTypeStorage>()) MatrixTypeStorage(key);
1429 }
1430
1431 bool operator==(const KeyTy &key) const {
1432 return key == KeyTy(columnType, shape[1]);
1433 }
1434
1436 // [#rows, #columns]
1437 std::array<int64_t, 2> shape;
1438};
1439
1440MatrixType MatrixType::get(Type columnType, uint32_t columnCount) {
1441 return Base::get(columnType.getContext(), columnType, columnCount);
1442}
1443
1445 Type columnType, uint32_t columnCount) {
1446 return Base::getChecked(emitError, columnType.getContext(), columnType,
1447 columnCount);
1448}
1449
1450LogicalResult
1452 Type columnType, uint32_t columnCount) {
1453 if (columnCount < 2 || columnCount > 4)
1454 return emitError() << "matrix can have 2, 3, or 4 columns only";
1455
1456 if (!isValidColumnType(columnType))
1457 return emitError() << "matrix columns must be vectors of floats";
1458
1459 if (containsMicroscalingType(columnType))
1460 return emitError() << "microscaling types are not supported in matrices";
1461
1462 /// The underlying vectors (columns) must be of size 2, 3, or 4
1463 ArrayRef<int64_t> columnShape = cast<VectorType>(columnType).getShape();
1464 if (columnShape.size() != 1)
1465 return emitError() << "matrix columns must be 1D vectors";
1466
1467 if (columnShape[0] < 2 || columnShape[0] > 4)
1468 return emitError() << "matrix columns must be of size 2, 3, or 4";
1469
1470 return success();
1471}
1472
1473/// Returns true if the matrix elements are vectors of float elements
1475 if (auto vectorType = dyn_cast<VectorType>(columnType)) {
1476 if (isa<FloatType>(vectorType.getElementType()))
1477 return true;
1478 }
1479 return false;
1480}
1481
1482Type MatrixType::getColumnType() const { return getImpl()->columnType; }
1483
1485 return cast<VectorType>(getImpl()->columnType).getElementType();
1486}
1487
1489 assert(getImpl()->shape[1] >= 0); // Also includes ShapedType::kDynamic.
1490 assert(getImpl()->shape[1] <= std::numeric_limits<unsigned>::max());
1491 return static_cast<uint32_t>(getImpl()->shape[1]);
1492}
1493
1494unsigned MatrixType::getNumRows() const {
1495 assert(getImpl()->shape[0] >= 0); // Also includes ShapedType::kDynamic.
1496 assert(getImpl()->shape[0] <= std::numeric_limits<unsigned>::max());
1497 return static_cast<uint32_t>(getImpl()->shape[0]);
1498}
1499
1501 return getNumColumns() * getNumRows();
1502}
1503
1505
1506void TypeCapabilityVisitor::addConcrete(MatrixType type) {
1507 add(type.getColumnType());
1508 pushCaps<Capability::Matrix>();
1509}
1510
1511//===----------------------------------------------------------------------===//
1512// TensorArmType
1513//===----------------------------------------------------------------------===//
1514
1516 using KeyTy = std::tuple<ArrayRef<int64_t>, Type>;
1517
1519 const KeyTy &key) {
1520 auto [shape, elementType] = key;
1521 shape = allocator.copyInto(shape);
1522 return new (allocator.allocate<TensorArmTypeStorage>())
1524 }
1525
1526 static llvm::hash_code hashKey(const KeyTy &key) {
1527 auto [shape, elementType] = key;
1528 return llvm::hash_combine(shape, elementType);
1529 }
1530
1531 bool operator==(const KeyTy &key) const {
1532 return key == KeyTy(shape, elementType);
1533 }
1534
1537
1540};
1541
1543 return Base::get(elementType.getContext(), shape, elementType);
1544}
1545
1547 Type elementType) const {
1548 return TensorArmType::get(shape.value_or(getShape()), elementType);
1549}
1550
1551Type TensorArmType::getElementType() const { return getImpl()->elementType; }
1553
1554void TypeExtensionVisitor::addConcrete(TensorArmType type) {
1555 add(type.getElementType());
1556 pushExts<Extension::SPV_ARM_tensors>();
1557}
1558
1559void TypeCapabilityVisitor::addConcrete(TensorArmType type) {
1560 add(type.getElementType());
1561 pushCaps<Capability::TensorsARM>();
1562}
1563
1564LogicalResult
1566 ArrayRef<int64_t> shape, Type elementType) {
1567 if (llvm::is_contained(shape, 0))
1568 return emitError() << "arm.tensor do not support dimensions = 0";
1569 if (llvm::any_of(shape, [](int64_t dim) { return dim < 0; }) &&
1570 llvm::any_of(shape, [](int64_t dim) { return dim > 0; }))
1571 return emitError()
1572 << "arm.tensor shape dimensions must be either fully dynamic or "
1573 "completed shaped";
1574 return success();
1575}
1576
1577//===----------------------------------------------------------------------===//
1578// SPIR-V Dialect
1579//===----------------------------------------------------------------------===//
1580
1581void SPIRVDialect::registerTypes() {
1585}
return success()
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 inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
false
Parses a map_entries map type from a string format back into its numeric value.
constexpr unsigned getNumBits< ImageSamplerUseInfo >()
#define STORAGE_CASE(storage, cap8, cap16)
constexpr unsigned getNumBits< ImageFormat >()
static constexpr unsigned getNumBits()
#define WIDTH_CASE(type, width)
constexpr unsigned getNumBits< ImageArrayedInfo >()
constexpr unsigned getNumBits< ImageSamplingInfo >()
static bool containsMicroscalingTypeImpl(Type type, bool subByteOnly, llvm::SmallDenseSet< Type, 8 > &visited)
Find microscaling elements in composite types, including recursive structs.
constexpr unsigned getNumBits< Dim >()
constexpr unsigned getNumBits< ImageDepthInfo >()
#define add(a, b)
This class represents a diagnostic that is inflight and set to be reported.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
ArrayRef< T > copyInto(ArrayRef< T > elements)
Copy the specified array of elements into memory managed by our bump pointer allocator.
T * allocate()
Allocate an instance of the provided type.
This class provides an abstraction over the various different ranges of value types.
Definition TypeRange.h:40
TypeStorage()
This constructor is used by derived classes as part of the TypeUniquer.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
Dialect & getDialect() const
Get the dialect this type is registered to.
Definition Types.h:107
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
bool isF8E5M2() const
Definition Types.cpp:45
bool isF8E4M3FN() const
Definition Types.cpp:44
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
bool isBF16() const
Definition Types.cpp:37
Type getElementType() const
unsigned getArrayStride() const
Returns the array stride in bytes.
unsigned getNumElements() const
static ArrayType get(Type elementType, unsigned elementCount)
bool hasCompileTimeKnownNumElements() const
Return true if the number of elements is known at compile time and is not implementation dependent.
unsigned getNumElements() const
Return the number of elements of the type.
static bool isValid(VectorType)
Returns true if the given vector type is valid for the SPIR-V dialect.
Type getElementType(unsigned) const
static bool classof(Type type)
static LogicalResult verifyInvariants(function_ref< InFlightDiagnostic()> emitError, Type elementType, uint32_t rows, uint32_t columns, Scope scope, CooperativeMatrixUseKHR use)
Scope getScope() const
Returns the scope of the matrix.
uint32_t getRows() const
Returns the number of rows of the matrix.
uint32_t getColumns() const
Returns the number of columns of the matrix.
static CooperativeMatrixType get(Type elementType, uint32_t rows, uint32_t columns, Scope scope, CooperativeMatrixUseKHR use)
ArrayRef< int64_t > getShape() const
static CooperativeMatrixType getChecked(function_ref< InFlightDiagnostic()> emitError, MLIRContext *context, Type elementType, uint32_t rows, uint32_t columns, Scope scope, CooperativeMatrixUseKHR use)
CooperativeMatrixUseKHR getUse() const
Returns the use parameter of the cooperative matrix.
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
ImageDepthInfo getDepthInfo() const
ImageArrayedInfo getArrayedInfo() const
ImageFormat getImageFormat() const
ImageSamplerUseInfo getSamplerUseInfo() const
static ImageType getChecked(function_ref< InFlightDiagnostic()> emitError, MLIRContext *context, std::tuple< Type, Dim, ImageDepthInfo, ImageArrayedInfo, ImageSamplingInfo, ImageSamplerUseInfo, ImageFormat > value)
static LogicalResult verifyInvariants(function_ref< InFlightDiagnostic()> emitError, std::tuple< Type, Dim, ImageDepthInfo, ImageArrayedInfo, ImageSamplingInfo, ImageSamplerUseInfo, ImageFormat > value)
Type getElementType() const
ImageSamplingInfo getSamplingInfo() const
static MatrixType getChecked(function_ref< InFlightDiagnostic()> emitError, Type columnType, uint32_t columnCount)
unsigned getNumElements() const
Returns total number of elements (rows*columns).
static MatrixType get(Type columnType, uint32_t columnCount)
static LogicalResult verifyInvariants(function_ref< InFlightDiagnostic()> emitError, Type columnType, uint32_t columnCount)
unsigned getNumColumns() const
Returns the number of columns.
static bool isValidColumnType(Type columnType)
Returns true if the matrix elements are vectors of float elements.
Type getElementType() const
Returns the elements' type (i.e, single element type).
ArrayRef< int64_t > getShape() const
unsigned getNumRows() const
Returns the number of rows.
static NamedBarrierType get(MLIRContext *context)
StorageClass getStorageClass() const
static PointerType getChecked(function_ref< InFlightDiagnostic()> emitError, MLIRContext *context, Type pointeeType, StorageClass storageClass)
static PointerType get(Type pointeeType, StorageClass storageClass)
static LogicalResult verifyInvariants(function_ref< InFlightDiagnostic()> emitError, Type pointeeType, StorageClass storageClass)
unsigned getArrayStride() const
Returns the array stride in bytes.
static RuntimeArrayType get(Type elementType)
constexpr Type()=default
std::optional< int64_t > getSizeInBytes()
Returns the size in bytes for each type.
static bool classof(Type type)
void getCapabilities(CapabilityArrayRefVector &capabilities, std::optional< StorageClass > storage=std::nullopt)
Appends to capabilities the capabilities needed for this type to appear in the given storage class.
SmallVectorImpl< ArrayRef< Capability > > CapabilityArrayRefVector
The capability requirements for each type are following the ((Capability::A OR Extension::B) AND (Cap...
Definition SPIRVTypes.h:66
void getExtensions(ExtensionArrayRefVector &extensions, std::optional< StorageClass > storage=std::nullopt)
Appends to extensions the extensions needed for this type to appear in the given storage class.
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 LogicalResult verifyInvariants(function_ref< InFlightDiagnostic()> emitError, Type imageType)
static SampledImageType getChecked(function_ref< InFlightDiagnostic()> emitError, Type imageType)
static SampledImageType get(Type imageType)
static SamplerType get(MLIRContext *context)
static bool classof(Type type)
static bool isValid(FloatType)
Returns true if the given float type is valid for the SPIR-V dialect.
SPIR-V struct type.
Definition SPIRVTypes.h:314
void getStructDecorations(SmallVectorImpl< StructType::StructDecorationInfo > &structDecorations) const
void getMemberDecorations(SmallVectorImpl< StructType::MemberDecorationInfo > &memberDecorations) const
static StructType getIdentified(MLIRContext *context, StringRef identifier)
Construct an identified StructType.
bool isIdentified() const
Returns true if the StructType is identified.
StringRef getIdentifier() const
For literal structs, return an empty string.
static StructType getEmpty(MLIRContext *context, StringRef identifier="")
Construct a (possibly identified) StructType with no members.
bool hasDecoration(spirv::Decoration decoration) const
Returns true if the struct has a specified decoration.
unsigned getNumElements() const
Type getElementType(unsigned) const
LogicalResult trySetBody(ArrayRef< Type > memberTypes, ArrayRef< OffsetInfo > offsetInfo={}, ArrayRef< MemberDecorationInfo > memberDecorations={}, ArrayRef< StructDecorationInfo > structDecorations={})
Sets the contents of an incomplete identified StructType.
TypeRange getElementTypes() const
static StructType get(ArrayRef< Type > memberTypes, ArrayRef< OffsetInfo > offsetInfo={}, ArrayRef< MemberDecorationInfo > memberDecorations={}, ArrayRef< StructDecorationInfo > structDecorations={})
Construct a literal StructType with at least one member.
uint64_t getMemberOffset(unsigned) const
SPIR-V TensorARM Type.
Definition SPIRVTypes.h:559
static LogicalResult verifyInvariants(function_ref< InFlightDiagnostic()> emitError, ArrayRef< int64_t > shape, Type elementType)
static TensorArmType get(ArrayRef< int64_t > shape, Type elementType)
TensorArmType cloneWith(std::optional< ArrayRef< int64_t > > shape, Type elementType) const
ArrayRef< int64_t > getShape() const
StorageClass getStorageClass() const
static UntypedPointerType get(MLIRContext *context, StorageClass storageClass)
llvm::hash_code hash_value(const StructType::MemberDecorationInfo &memberDecorationInfo)
bool containsMicroscalingType(Type type, bool subByteOnly=false)
Returns whether a type contains a microscaling element, including through composite types and pointer...
Include the generated interface declarations.
StorageUniquer::StorageAllocator TypeStorageAllocator
This is a utility allocator used to allocate memory for instances of derived Types.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:147
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
static ArrayTypeStorage * construct(TypeStorageAllocator &allocator, const KeyTy &key)
std::tuple< Type, unsigned, unsigned > KeyTy
bool operator==(const KeyTy &key) const
static CooperativeMatrixTypeStorage * construct(TypeStorageAllocator &allocator, const KeyTy &key)
std::tuple< Type, int64_t, int64_t, Scope, CooperativeMatrixUseKHR > KeyTy
std::tuple< Type, Dim, ImageDepthInfo, ImageArrayedInfo, ImageSamplingInfo, ImageSamplerUseInfo, ImageFormat > KeyTy
bool operator==(const KeyTy &key) const
static ImageTypeStorage * construct(TypeStorageAllocator &allocator, const KeyTy &key)
std::tuple< Type, int64_t > KeyTy
bool operator==(const KeyTy &key) const
static MatrixTypeStorage * construct(TypeStorageAllocator &allocator, const KeyTy &key)
static PointerTypeStorage * construct(TypeStorageAllocator &allocator, const KeyTy &key)
bool operator==(const KeyTy &key) const
std::pair< Type, StorageClass > KeyTy
static RuntimeArrayTypeStorage * construct(TypeStorageAllocator &allocator, const KeyTy &key)
bool operator==(const KeyTy &key) const
bool operator==(const KeyTy &key) const
static SampledImageTypeStorage * construct(TypeStorageAllocator &allocator, const KeyTy &key)
Type storage for SPIR-V structure types:
ArrayRef< StructType::MemberDecorationInfo > getMemberDecorationsInfo() const
StructType::OffsetInfo const * offsetInfo
static StructTypeStorage * construct(TypeStorageAllocator &allocator, const KeyTy &key)
If the given key contains a non-empty identifier, this method constructs an identified struct and lea...
bool operator==(const KeyTy &key) const
For identified structs, return true if the given key contains the same identifier.
std::tuple< StringRef, ArrayRef< Type >, ArrayRef< StructType::OffsetInfo >, ArrayRef< StructType::MemberDecorationInfo >, ArrayRef< StructType::StructDecorationInfo > > KeyTy
A storage key is divided into 2 parts:
ArrayRef< StructType::OffsetInfo > getOffsetInfo() const
StructTypeStorage(StringRef identifier)
Construct a storage object for an identified struct type.
ArrayRef< StructType::StructDecorationInfo > getStructDecorationsInfo() const
StructType::MemberDecorationInfo const * memberDecorationsInfo
StructTypeStorage(unsigned numMembers, Type const *memberTypes, StructType::OffsetInfo const *layoutInfo, unsigned numMemberDecorations, StructType::MemberDecorationInfo const *memberDecorationsInfo, unsigned numStructDecorations, StructType::StructDecorationInfo const *structDecorationsInfo)
Construct a storage object for a literal struct type.
StructType::StructDecorationInfo const * structDecorationsInfo
llvm::PointerIntPair< Type const *, 1, bool > memberTypesAndIsBodySet
ArrayRef< Type > getMemberTypes() const
LogicalResult mutate(TypeStorageAllocator &allocator, ArrayRef< Type > structMemberTypes, ArrayRef< StructType::OffsetInfo > structOffsetInfo, ArrayRef< StructType::MemberDecorationInfo > structMemberDecorationInfo, ArrayRef< StructType::StructDecorationInfo > structDecorationInfo)
Sets the struct type content for identified structs.
static TensorArmTypeStorage * construct(TypeStorageAllocator &allocator, const KeyTy &key)
static llvm::hash_code hashKey(const KeyTy &key)
std::tuple< ArrayRef< int64_t >, Type > KeyTy
TensorArmTypeStorage(ArrayRef< int64_t > shape, Type elementType)
bool operator==(const KeyTy &key) const
static UntypedPointerTypeStorage * construct(TypeStorageAllocator &allocator, const KeyTy &key)