101178654SLei Zhang //===- SPIRVConversion.cpp - SPIR-V Conversion Utilities ------------------===//
201178654SLei Zhang //
301178654SLei Zhang // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
401178654SLei Zhang // See https://llvm.org/LICENSE.txt for license information.
501178654SLei Zhang // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
601178654SLei Zhang //
701178654SLei Zhang //===----------------------------------------------------------------------===//
801178654SLei Zhang //
901178654SLei Zhang // This file implements utilities used to lower to SPIR-V dialect.
1001178654SLei Zhang //
1101178654SLei Zhang //===----------------------------------------------------------------------===//
1201178654SLei Zhang 
1301178654SLei Zhang #include "mlir/Dialect/SPIRV/Transforms/SPIRVConversion.h"
1401178654SLei Zhang #include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
1501178654SLei Zhang #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
167c3ae48fSLei Zhang #include "mlir/Transforms/DialectConversion.h"
1701178654SLei Zhang #include "llvm/ADT/Sequence.h"
1801178654SLei Zhang #include "llvm/ADT/StringExtras.h"
1901178654SLei Zhang #include "llvm/Support/Debug.h"
2001178654SLei Zhang 
2101178654SLei Zhang #include <functional>
2201178654SLei Zhang 
2301178654SLei Zhang #define DEBUG_TYPE "mlir-spirv-conversion"
2401178654SLei Zhang 
2501178654SLei Zhang using namespace mlir;
2601178654SLei Zhang 
2701178654SLei Zhang //===----------------------------------------------------------------------===//
2801178654SLei Zhang // Utility functions
2901178654SLei Zhang //===----------------------------------------------------------------------===//
3001178654SLei Zhang 
3101178654SLei Zhang /// Checks that `candidates` extension requirements are possible to be satisfied
3201178654SLei Zhang /// with the given `targetEnv`.
3301178654SLei Zhang ///
3401178654SLei Zhang ///  `candidates` is a vector of vector for extension requirements following
3501178654SLei Zhang /// ((Extension::A OR Extension::B) AND (Extension::C OR Extension::D))
3601178654SLei Zhang /// convention.
3701178654SLei Zhang template <typename LabelT>
3801178654SLei Zhang static LogicalResult checkExtensionRequirements(
3901178654SLei Zhang     LabelT label, const spirv::TargetEnv &targetEnv,
4001178654SLei Zhang     const spirv::SPIRVType::ExtensionArrayRefVector &candidates) {
4101178654SLei Zhang   for (const auto &ors : candidates) {
4201178654SLei Zhang     if (targetEnv.allows(ors))
4301178654SLei Zhang       continue;
4401178654SLei Zhang 
45fd91f81cSLei Zhang     LLVM_DEBUG({
46fd91f81cSLei Zhang       SmallVector<StringRef> extStrings;
4701178654SLei Zhang       for (spirv::Extension ext : ors)
4801178654SLei Zhang         extStrings.push_back(spirv::stringifyExtension(ext));
4901178654SLei Zhang 
50fd91f81cSLei Zhang       llvm::dbgs() << label << " illegal: requires at least one extension in ["
5101178654SLei Zhang                    << llvm::join(extStrings, ", ")
52fd91f81cSLei Zhang                    << "] but none allowed in target environment\n";
53fd91f81cSLei Zhang     });
5401178654SLei Zhang     return failure();
5501178654SLei Zhang   }
5601178654SLei Zhang   return success();
5701178654SLei Zhang }
5801178654SLei Zhang 
5901178654SLei Zhang /// Checks that `candidates`capability requirements are possible to be satisfied
6001178654SLei Zhang /// with the given `isAllowedFn`.
6101178654SLei Zhang ///
6201178654SLei Zhang ///  `candidates` is a vector of vector for capability requirements following
6301178654SLei Zhang /// ((Capability::A OR Capability::B) AND (Capability::C OR Capability::D))
6401178654SLei Zhang /// convention.
6501178654SLei Zhang template <typename LabelT>
6601178654SLei Zhang static LogicalResult checkCapabilityRequirements(
6701178654SLei Zhang     LabelT label, const spirv::TargetEnv &targetEnv,
6801178654SLei Zhang     const spirv::SPIRVType::CapabilityArrayRefVector &candidates) {
6901178654SLei Zhang   for (const auto &ors : candidates) {
7001178654SLei Zhang     if (targetEnv.allows(ors))
7101178654SLei Zhang       continue;
7201178654SLei Zhang 
73fd91f81cSLei Zhang     LLVM_DEBUG({
74fd91f81cSLei Zhang       SmallVector<StringRef> capStrings;
7501178654SLei Zhang       for (spirv::Capability cap : ors)
7601178654SLei Zhang         capStrings.push_back(spirv::stringifyCapability(cap));
7701178654SLei Zhang 
78fd91f81cSLei Zhang       llvm::dbgs() << label << " illegal: requires at least one capability in ["
7901178654SLei Zhang                    << llvm::join(capStrings, ", ")
80fd91f81cSLei Zhang                    << "] but none allowed in target environment\n";
81fd91f81cSLei Zhang     });
8201178654SLei Zhang     return failure();
8301178654SLei Zhang   }
8401178654SLei Zhang   return success();
8501178654SLei Zhang }
8601178654SLei Zhang 
875b15fe93SLei Zhang /// Returns true if the given `storageClass` needs explicit layout when used in
885b15fe93SLei Zhang /// Shader environments.
895b15fe93SLei Zhang static bool needsExplicitLayout(spirv::StorageClass storageClass) {
905b15fe93SLei Zhang   switch (storageClass) {
915b15fe93SLei Zhang   case spirv::StorageClass::PhysicalStorageBuffer:
925b15fe93SLei Zhang   case spirv::StorageClass::PushConstant:
935b15fe93SLei Zhang   case spirv::StorageClass::StorageBuffer:
945b15fe93SLei Zhang   case spirv::StorageClass::Uniform:
955b15fe93SLei Zhang     return true;
965b15fe93SLei Zhang   default:
975b15fe93SLei Zhang     return false;
985b15fe93SLei Zhang   }
995b15fe93SLei Zhang }
1005b15fe93SLei Zhang 
1015b15fe93SLei Zhang /// Wraps the given `elementType` in a struct and gets the pointer to the
1025b15fe93SLei Zhang /// struct. This is used to satisfy Vulkan interface requirements.
1035b15fe93SLei Zhang static spirv::PointerType
1045b15fe93SLei Zhang wrapInStructAndGetPointer(Type elementType, spirv::StorageClass storageClass) {
1055b15fe93SLei Zhang   auto structType = needsExplicitLayout(storageClass)
1065b15fe93SLei Zhang                         ? spirv::StructType::get(elementType, /*offsetInfo=*/0)
1075b15fe93SLei Zhang                         : spirv::StructType::get(elementType);
1085b15fe93SLei Zhang   return spirv::PointerType::get(structType, storageClass);
1095b15fe93SLei Zhang }
1105b15fe93SLei Zhang 
11101178654SLei Zhang //===----------------------------------------------------------------------===//
11201178654SLei Zhang // Type Conversion
11301178654SLei Zhang //===----------------------------------------------------------------------===//
11401178654SLei Zhang 
11501178654SLei Zhang Type SPIRVTypeConverter::getIndexType(MLIRContext *context) {
11601178654SLei Zhang   // Convert to 32-bit integers for now. Might need a way to control this in
11701178654SLei Zhang   // future.
11801178654SLei Zhang   // TODO: It is probably better to make it 64-bit integers. To
11901178654SLei Zhang   // this some support is needed in SPIR-V dialect for Conversion
12001178654SLei Zhang   // instructions. The Vulkan spec requires the builtins like
12101178654SLei Zhang   // GlobalInvocationID, etc. to be 32-bit (unsigned) integers which should be
12201178654SLei Zhang   // SExtended to 64-bit for index computations.
1231b97cdf8SRiver Riddle   return IntegerType::get(context, 32);
12401178654SLei Zhang }
12501178654SLei Zhang 
12601178654SLei Zhang /// Mapping between SPIR-V storage classes to memref memory spaces.
12701178654SLei Zhang ///
12801178654SLei Zhang /// Note: memref does not have a defined semantics for each memory space; it
12901178654SLei Zhang /// depends on the context where it is used. There are no particular reasons
13001178654SLei Zhang /// behind the number assignments; we try to follow NVVM conventions and largely
13101178654SLei Zhang /// give common storage classes a smaller number. The hope is use symbolic
13201178654SLei Zhang /// memory space representation eventually after memref supports it.
13301178654SLei Zhang // TODO: swap Generic and StorageBuffer assignment to be more akin
13401178654SLei Zhang // to NVVM.
13501178654SLei Zhang #define STORAGE_SPACE_MAP_LIST(MAP_FN)                                         \
13601178654SLei Zhang   MAP_FN(spirv::StorageClass::Generic, 1)                                      \
13701178654SLei Zhang   MAP_FN(spirv::StorageClass::StorageBuffer, 0)                                \
13801178654SLei Zhang   MAP_FN(spirv::StorageClass::Workgroup, 3)                                    \
13901178654SLei Zhang   MAP_FN(spirv::StorageClass::Uniform, 4)                                      \
14001178654SLei Zhang   MAP_FN(spirv::StorageClass::Private, 5)                                      \
14101178654SLei Zhang   MAP_FN(spirv::StorageClass::Function, 6)                                     \
14201178654SLei Zhang   MAP_FN(spirv::StorageClass::PushConstant, 7)                                 \
14301178654SLei Zhang   MAP_FN(spirv::StorageClass::UniformConstant, 8)                              \
14401178654SLei Zhang   MAP_FN(spirv::StorageClass::Input, 9)                                        \
14501178654SLei Zhang   MAP_FN(spirv::StorageClass::Output, 10)                                      \
14601178654SLei Zhang   MAP_FN(spirv::StorageClass::CrossWorkgroup, 11)                              \
14701178654SLei Zhang   MAP_FN(spirv::StorageClass::AtomicCounter, 12)                               \
14801178654SLei Zhang   MAP_FN(spirv::StorageClass::Image, 13)                                       \
14901178654SLei Zhang   MAP_FN(spirv::StorageClass::CallableDataNV, 14)                              \
15001178654SLei Zhang   MAP_FN(spirv::StorageClass::IncomingCallableDataNV, 15)                      \
15101178654SLei Zhang   MAP_FN(spirv::StorageClass::RayPayloadNV, 16)                                \
15201178654SLei Zhang   MAP_FN(spirv::StorageClass::HitAttributeNV, 17)                              \
15301178654SLei Zhang   MAP_FN(spirv::StorageClass::IncomingRayPayloadNV, 18)                        \
15401178654SLei Zhang   MAP_FN(spirv::StorageClass::ShaderRecordBufferNV, 19)                        \
15501178654SLei Zhang   MAP_FN(spirv::StorageClass::PhysicalStorageBuffer, 20)
15601178654SLei Zhang 
15701178654SLei Zhang unsigned
15801178654SLei Zhang SPIRVTypeConverter::getMemorySpaceForStorageClass(spirv::StorageClass storage) {
15901178654SLei Zhang #define STORAGE_SPACE_MAP_FN(storage, space)                                   \
16001178654SLei Zhang   case storage:                                                                \
16101178654SLei Zhang     return space;
16201178654SLei Zhang 
16301178654SLei Zhang   switch (storage) { STORAGE_SPACE_MAP_LIST(STORAGE_SPACE_MAP_FN) }
16401178654SLei Zhang #undef STORAGE_SPACE_MAP_FN
16501178654SLei Zhang   llvm_unreachable("unhandled storage class!");
16601178654SLei Zhang }
16701178654SLei Zhang 
16801178654SLei Zhang Optional<spirv::StorageClass>
16901178654SLei Zhang SPIRVTypeConverter::getStorageClassForMemorySpace(unsigned space) {
17001178654SLei Zhang #define STORAGE_SPACE_MAP_FN(storage, space)                                   \
17101178654SLei Zhang   case space:                                                                  \
17201178654SLei Zhang     return storage;
17301178654SLei Zhang 
17401178654SLei Zhang   switch (space) {
17501178654SLei Zhang     STORAGE_SPACE_MAP_LIST(STORAGE_SPACE_MAP_FN)
17601178654SLei Zhang   default:
17701178654SLei Zhang     return llvm::None;
17801178654SLei Zhang   }
17901178654SLei Zhang #undef STORAGE_SPACE_MAP_FN
18001178654SLei Zhang }
18101178654SLei Zhang 
182c3614358SHanhan Wang const SPIRVTypeConverter::Options &SPIRVTypeConverter::getOptions() const {
183c3614358SHanhan Wang   return options;
184c3614358SHanhan Wang }
185c3614358SHanhan Wang 
18601178654SLei Zhang #undef STORAGE_SPACE_MAP_LIST
18701178654SLei Zhang 
1885299843cSLei Zhang // TODO: This is a utility function that should probably be exposed by the
1895299843cSLei Zhang // SPIR-V dialect. Keeping it local till the use case arises.
1905299843cSLei Zhang static Optional<int64_t>
1915299843cSLei Zhang getTypeNumBytes(const SPIRVTypeConverter::Options &options, Type type) {
1925299843cSLei Zhang   if (type.isa<spirv::ScalarType>()) {
1935299843cSLei Zhang     auto bitWidth = type.getIntOrFloatBitWidth();
19401178654SLei Zhang     // According to the SPIR-V spec:
19501178654SLei Zhang     // "There is no physical size or bit pattern defined for values with boolean
19601178654SLei Zhang     // type. If they are stored (in conjunction with OpVariable), they can only
19701178654SLei Zhang     // be used with logical addressing operations, not physical, and only with
19801178654SLei Zhang     // non-externally visible shader Storage Classes: Workgroup, CrossWorkgroup,
19901178654SLei Zhang     // Private, Function, Input, and Output."
2005299843cSLei Zhang     if (bitWidth == 1)
20101178654SLei Zhang       return llvm::None;
20201178654SLei Zhang     return bitWidth / 8;
20301178654SLei Zhang   }
2046dd07fa5SLei Zhang 
2055299843cSLei Zhang   if (auto vecType = type.dyn_cast<VectorType>()) {
2065299843cSLei Zhang     auto elementSize = getTypeNumBytes(options, vecType.getElementType());
20701178654SLei Zhang     if (!elementSize)
20801178654SLei Zhang       return llvm::None;
2095299843cSLei Zhang     return vecType.getNumElements() * elementSize.getValue();
21001178654SLei Zhang   }
2116dd07fa5SLei Zhang 
2125299843cSLei Zhang   if (auto memRefType = type.dyn_cast<MemRefType>()) {
21301178654SLei Zhang     // TODO: Layout should also be controlled by the ABI attributes. For now
21401178654SLei Zhang     // using the layout from MemRef.
21501178654SLei Zhang     int64_t offset;
21601178654SLei Zhang     SmallVector<int64_t, 4> strides;
21701178654SLei Zhang     if (!memRefType.hasStaticShape() ||
2185299843cSLei Zhang         failed(getStridesAndOffset(memRefType, strides, offset)))
21901178654SLei Zhang       return llvm::None;
2205299843cSLei Zhang 
22101178654SLei Zhang     // To get the size of the memref object in memory, the total size is the
22201178654SLei Zhang     // max(stride * dimension-size) computed for all dimensions times the size
22301178654SLei Zhang     // of the element.
2245299843cSLei Zhang     auto elementSize = getTypeNumBytes(options, memRefType.getElementType());
2255299843cSLei Zhang     if (!elementSize)
22601178654SLei Zhang       return llvm::None;
2275299843cSLei Zhang 
2285299843cSLei Zhang     if (memRefType.getRank() == 0)
22901178654SLei Zhang       return elementSize;
2305299843cSLei Zhang 
23101178654SLei Zhang     auto dims = memRefType.getShape();
23201178654SLei Zhang     if (llvm::is_contained(dims, ShapedType::kDynamicSize) ||
23301178654SLei Zhang         offset == MemRefType::getDynamicStrideOrOffset() ||
2345299843cSLei Zhang         llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset()))
23501178654SLei Zhang       return llvm::None;
2365299843cSLei Zhang 
23701178654SLei Zhang     int64_t memrefSize = -1;
2385299843cSLei Zhang     for (auto shape : enumerate(dims))
23901178654SLei Zhang       memrefSize = std::max(memrefSize, shape.value() * strides[shape.index()]);
2405299843cSLei Zhang 
24101178654SLei Zhang     return (offset + memrefSize) * elementSize.getValue();
2426dd07fa5SLei Zhang   }
2436dd07fa5SLei Zhang 
2445299843cSLei Zhang   if (auto tensorType = type.dyn_cast<TensorType>()) {
2455299843cSLei Zhang     if (!tensorType.hasStaticShape())
24601178654SLei Zhang       return llvm::None;
2475299843cSLei Zhang 
2485299843cSLei Zhang     auto elementSize = getTypeNumBytes(options, tensorType.getElementType());
2495299843cSLei Zhang     if (!elementSize)
25001178654SLei Zhang       return llvm::None;
2515299843cSLei Zhang 
25201178654SLei Zhang     int64_t size = elementSize.getValue();
2535299843cSLei Zhang     for (auto shape : tensorType.getShape())
25401178654SLei Zhang       size *= shape;
2555299843cSLei Zhang 
25601178654SLei Zhang     return size;
25701178654SLei Zhang   }
2586dd07fa5SLei Zhang 
25901178654SLei Zhang   // TODO: Add size computation for other types.
26001178654SLei Zhang   return llvm::None;
26101178654SLei Zhang }
26201178654SLei Zhang 
26301178654SLei Zhang /// Converts a scalar `type` to a suitable type under the given `targetEnv`.
264004f29c0SLei Zhang static Type convertScalarType(const spirv::TargetEnv &targetEnv,
2655299843cSLei Zhang                               const SPIRVTypeConverter::Options &options,
266004f29c0SLei Zhang                               spirv::ScalarType type,
26701178654SLei Zhang                               Optional<spirv::StorageClass> storageClass = {}) {
26801178654SLei Zhang   // Get extension and capability requirements for the given type.
26901178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 1> extensions;
27001178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 2> capabilities;
27101178654SLei Zhang   type.getExtensions(extensions, storageClass);
27201178654SLei Zhang   type.getCapabilities(capabilities, storageClass);
27301178654SLei Zhang 
27401178654SLei Zhang   // If all requirements are met, then we can accept this type as-is.
27501178654SLei Zhang   if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) &&
27601178654SLei Zhang       succeeded(checkExtensionRequirements(type, targetEnv, extensions)))
27701178654SLei Zhang     return type;
27801178654SLei Zhang 
27901178654SLei Zhang   // Otherwise we need to adjust the type, which really means adjusting the
28001178654SLei Zhang   // bitwidth given this is a scalar type.
2815299843cSLei Zhang 
2825299843cSLei Zhang   if (!options.emulateNon32BitScalarTypes)
2835299843cSLei Zhang     return nullptr;
28401178654SLei Zhang 
28501178654SLei Zhang   if (auto floatType = type.dyn_cast<FloatType>()) {
28601178654SLei Zhang     LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n");
28701178654SLei Zhang     return Builder(targetEnv.getContext()).getF32Type();
28801178654SLei Zhang   }
28901178654SLei Zhang 
29001178654SLei Zhang   auto intType = type.cast<IntegerType>();
29101178654SLei Zhang   LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n");
2921b97cdf8SRiver Riddle   return IntegerType::get(targetEnv.getContext(), /*width=*/32,
2931b97cdf8SRiver Riddle                           intType.getSignedness());
29401178654SLei Zhang }
29501178654SLei Zhang 
29601178654SLei Zhang /// Converts a vector `type` to a suitable type under the given `targetEnv`.
297004f29c0SLei Zhang static Type convertVectorType(const spirv::TargetEnv &targetEnv,
2985299843cSLei Zhang                               const SPIRVTypeConverter::Options &options,
299004f29c0SLei Zhang                               VectorType type,
30001178654SLei Zhang                               Optional<spirv::StorageClass> storageClass = {}) {
3019f622b3dSLei Zhang   if (type.getRank() == 1 && type.getNumElements() == 1)
3029f622b3dSLei Zhang     return type.getElementType();
3039f622b3dSLei Zhang 
30401178654SLei Zhang   if (!spirv::CompositeType::isValid(type)) {
3059f622b3dSLei Zhang     // TODO: Vector types with more than four elements can be translated into
30601178654SLei Zhang     // array types.
3079f622b3dSLei Zhang     LLVM_DEBUG(llvm::dbgs() << type << " illegal: > 4-element unimplemented\n");
308004f29c0SLei Zhang     return nullptr;
30901178654SLei Zhang   }
31001178654SLei Zhang 
31101178654SLei Zhang   // Get extension and capability requirements for the given type.
31201178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 1> extensions;
31301178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 2> capabilities;
31401178654SLei Zhang   type.cast<spirv::CompositeType>().getExtensions(extensions, storageClass);
31501178654SLei Zhang   type.cast<spirv::CompositeType>().getCapabilities(capabilities, storageClass);
31601178654SLei Zhang 
31701178654SLei Zhang   // If all requirements are met, then we can accept this type as-is.
31801178654SLei Zhang   if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) &&
31901178654SLei Zhang       succeeded(checkExtensionRequirements(type, targetEnv, extensions)))
32001178654SLei Zhang     return type;
32101178654SLei Zhang 
32201178654SLei Zhang   auto elementType = convertScalarType(
3235299843cSLei Zhang       targetEnv, options, type.getElementType().cast<spirv::ScalarType>(),
3245299843cSLei Zhang       storageClass);
32501178654SLei Zhang   if (elementType)
326004f29c0SLei Zhang     return VectorType::get(type.getShape(), elementType);
327004f29c0SLei Zhang   return nullptr;
32801178654SLei Zhang }
32901178654SLei Zhang 
33001178654SLei Zhang /// Converts a tensor `type` to a suitable type under the given `targetEnv`.
33101178654SLei Zhang ///
33201178654SLei Zhang /// Note that this is mainly for lowering constant tensors. In SPIR-V one can
33301178654SLei Zhang /// create composite constants with OpConstantComposite to embed relative large
33401178654SLei Zhang /// constant values and use OpCompositeExtract and OpCompositeInsert to
33501178654SLei Zhang /// manipulate, like what we do for vectors.
336004f29c0SLei Zhang static Type convertTensorType(const spirv::TargetEnv &targetEnv,
3375299843cSLei Zhang                               const SPIRVTypeConverter::Options &options,
33801178654SLei Zhang                               TensorType type) {
33901178654SLei Zhang   // TODO: Handle dynamic shapes.
34001178654SLei Zhang   if (!type.hasStaticShape()) {
34101178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
34201178654SLei Zhang                << type << " illegal: dynamic shape unimplemented\n");
343004f29c0SLei Zhang     return nullptr;
34401178654SLei Zhang   }
34501178654SLei Zhang 
34601178654SLei Zhang   auto scalarType = type.getElementType().dyn_cast<spirv::ScalarType>();
34701178654SLei Zhang   if (!scalarType) {
34801178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
34901178654SLei Zhang                << type << " illegal: cannot convert non-scalar element type\n");
350004f29c0SLei Zhang     return nullptr;
35101178654SLei Zhang   }
35201178654SLei Zhang 
3535299843cSLei Zhang   Optional<int64_t> scalarSize = getTypeNumBytes(options, scalarType);
3545299843cSLei Zhang   Optional<int64_t> tensorSize = getTypeNumBytes(options, type);
35501178654SLei Zhang   if (!scalarSize || !tensorSize) {
35601178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
35701178654SLei Zhang                << type << " illegal: cannot deduce element count\n");
358004f29c0SLei Zhang     return nullptr;
35901178654SLei Zhang   }
36001178654SLei Zhang 
36101178654SLei Zhang   auto arrayElemCount = *tensorSize / *scalarSize;
3625299843cSLei Zhang   auto arrayElemType = convertScalarType(targetEnv, options, scalarType);
36301178654SLei Zhang   if (!arrayElemType)
364004f29c0SLei Zhang     return nullptr;
3655299843cSLei Zhang   Optional<int64_t> arrayElemSize = getTypeNumBytes(options, arrayElemType);
36601178654SLei Zhang   if (!arrayElemSize) {
36701178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
36801178654SLei Zhang                << type << " illegal: cannot deduce converted element size\n");
369004f29c0SLei Zhang     return nullptr;
37001178654SLei Zhang   }
37101178654SLei Zhang 
372004f29c0SLei Zhang   return spirv::ArrayType::get(arrayElemType, arrayElemCount, *arrayElemSize);
37301178654SLei Zhang }
37401178654SLei Zhang 
375c3614358SHanhan Wang static Type convertBoolMemrefType(const spirv::TargetEnv &targetEnv,
376c3614358SHanhan Wang                                   const SPIRVTypeConverter::Options &options,
377c3614358SHanhan Wang                                   MemRefType type) {
378c3614358SHanhan Wang   Optional<spirv::StorageClass> storageClass =
379c3614358SHanhan Wang       SPIRVTypeConverter::getStorageClassForMemorySpace(
380c3614358SHanhan Wang           type.getMemorySpaceAsInt());
381c3614358SHanhan Wang   if (!storageClass) {
382c3614358SHanhan Wang     LLVM_DEBUG(llvm::dbgs()
383c3614358SHanhan Wang                << type << " illegal: cannot convert memory space\n");
384c3614358SHanhan Wang     return nullptr;
385c3614358SHanhan Wang   }
386c3614358SHanhan Wang 
387c3614358SHanhan Wang   unsigned numBoolBits = options.boolNumBits;
388c3614358SHanhan Wang   if (numBoolBits != 8) {
389c3614358SHanhan Wang     LLVM_DEBUG(llvm::dbgs()
390c3614358SHanhan Wang                << "using non-8-bit storage for bool types unimplemented");
391c3614358SHanhan Wang     return nullptr;
392c3614358SHanhan Wang   }
393c3614358SHanhan Wang   auto elementType = IntegerType::get(type.getContext(), numBoolBits)
394c3614358SHanhan Wang                          .dyn_cast<spirv::ScalarType>();
395c3614358SHanhan Wang   if (!elementType)
396c3614358SHanhan Wang     return nullptr;
397c3614358SHanhan Wang   Type arrayElemType =
398c3614358SHanhan Wang       convertScalarType(targetEnv, options, elementType, storageClass);
399c3614358SHanhan Wang   if (!arrayElemType)
400c3614358SHanhan Wang     return nullptr;
401c3614358SHanhan Wang   Optional<int64_t> arrayElemSize = getTypeNumBytes(options, arrayElemType);
402c3614358SHanhan Wang   if (!arrayElemSize) {
403c3614358SHanhan Wang     LLVM_DEBUG(llvm::dbgs()
404c3614358SHanhan Wang                << type << " illegal: cannot deduce converted element size\n");
405c3614358SHanhan Wang     return nullptr;
406c3614358SHanhan Wang   }
407c3614358SHanhan Wang 
408*7c4de2e9SHanhan Wang   if (!type.hasStaticShape()) {
409*7c4de2e9SHanhan Wang     auto arrayType =
410*7c4de2e9SHanhan Wang         spirv::RuntimeArrayType::get(arrayElemType, *arrayElemSize);
411*7c4de2e9SHanhan Wang     return wrapInStructAndGetPointer(arrayType, *storageClass);
412*7c4de2e9SHanhan Wang   }
413*7c4de2e9SHanhan Wang 
414c3614358SHanhan Wang   int64_t memrefSize = (type.getNumElements() * numBoolBits + 7) / 8;
415c3614358SHanhan Wang   auto arrayElemCount = (memrefSize + *arrayElemSize - 1) / *arrayElemSize;
416c3614358SHanhan Wang   auto arrayType =
417c3614358SHanhan Wang       spirv::ArrayType::get(arrayElemType, arrayElemCount, *arrayElemSize);
418c3614358SHanhan Wang 
4195b15fe93SLei Zhang   return wrapInStructAndGetPointer(arrayType, *storageClass);
420c3614358SHanhan Wang }
421c3614358SHanhan Wang 
422004f29c0SLei Zhang static Type convertMemrefType(const spirv::TargetEnv &targetEnv,
4235299843cSLei Zhang                               const SPIRVTypeConverter::Options &options,
42401178654SLei Zhang                               MemRefType type) {
425c3614358SHanhan Wang   if (type.getElementType().isa<IntegerType>() &&
426c3614358SHanhan Wang       type.getElementTypeBitWidth() == 1) {
427c3614358SHanhan Wang     return convertBoolMemrefType(targetEnv, options, type);
428c3614358SHanhan Wang   }
429c3614358SHanhan Wang 
43001178654SLei Zhang   Optional<spirv::StorageClass> storageClass =
43137eca08eSVladislav Vinogradov       SPIRVTypeConverter::getStorageClassForMemorySpace(
43237eca08eSVladislav Vinogradov           type.getMemorySpaceAsInt());
43301178654SLei Zhang   if (!storageClass) {
43401178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
43501178654SLei Zhang                << type << " illegal: cannot convert memory space\n");
436004f29c0SLei Zhang     return nullptr;
43701178654SLei Zhang   }
43801178654SLei Zhang 
439004f29c0SLei Zhang   Type arrayElemType;
44001178654SLei Zhang   Type elementType = type.getElementType();
44101178654SLei Zhang   if (auto vecType = elementType.dyn_cast<VectorType>()) {
4425299843cSLei Zhang     arrayElemType =
4435299843cSLei Zhang         convertVectorType(targetEnv, options, vecType, storageClass);
44401178654SLei Zhang   } else if (auto scalarType = elementType.dyn_cast<spirv::ScalarType>()) {
4455299843cSLei Zhang     arrayElemType =
4465299843cSLei Zhang         convertScalarType(targetEnv, options, scalarType, storageClass);
44701178654SLei Zhang   } else {
44801178654SLei Zhang     LLVM_DEBUG(
44901178654SLei Zhang         llvm::dbgs()
45001178654SLei Zhang         << type
45101178654SLei Zhang         << " unhandled: can only convert scalar or vector element type\n");
452004f29c0SLei Zhang     return nullptr;
45301178654SLei Zhang   }
45401178654SLei Zhang   if (!arrayElemType)
455004f29c0SLei Zhang     return nullptr;
45601178654SLei Zhang 
4575299843cSLei Zhang   Optional<int64_t> elementSize = getTypeNumBytes(options, elementType);
45801178654SLei Zhang   if (!elementSize) {
45901178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
46001178654SLei Zhang                << type << " illegal: cannot deduce element size\n");
461004f29c0SLei Zhang     return nullptr;
46201178654SLei Zhang   }
46301178654SLei Zhang 
46423b8264bSLei Zhang   Optional<int64_t> arrayElemSize = getTypeNumBytes(options, arrayElemType);
46523b8264bSLei Zhang   if (!arrayElemSize) {
46623b8264bSLei Zhang     LLVM_DEBUG(llvm::dbgs()
46723b8264bSLei Zhang                << type << " illegal: cannot deduce converted element size\n");
46823b8264bSLei Zhang     return nullptr;
46923b8264bSLei Zhang   }
47023b8264bSLei Zhang 
47101178654SLei Zhang   if (!type.hasStaticShape()) {
47223b8264bSLei Zhang     auto arrayType =
47323b8264bSLei Zhang         spirv::RuntimeArrayType::get(arrayElemType, *arrayElemSize);
4745b15fe93SLei Zhang     return wrapInStructAndGetPointer(arrayType, *storageClass);
47501178654SLei Zhang   }
47601178654SLei Zhang 
4775299843cSLei Zhang   Optional<int64_t> memrefSize = getTypeNumBytes(options, type);
47801178654SLei Zhang   if (!memrefSize) {
47901178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
48001178654SLei Zhang                << type << " illegal: cannot deduce element count\n");
481004f29c0SLei Zhang     return nullptr;
48201178654SLei Zhang   }
48301178654SLei Zhang 
48401178654SLei Zhang   auto arrayElemCount = *memrefSize / *elementSize;
48501178654SLei Zhang 
48601178654SLei Zhang 
48701178654SLei Zhang   auto arrayType =
488004f29c0SLei Zhang       spirv::ArrayType::get(arrayElemType, arrayElemCount, *arrayElemSize);
48901178654SLei Zhang 
4905b15fe93SLei Zhang   return wrapInStructAndGetPointer(arrayType, *storageClass);
49101178654SLei Zhang }
49201178654SLei Zhang 
4935299843cSLei Zhang SPIRVTypeConverter::SPIRVTypeConverter(spirv::TargetEnvAttr targetAttr,
4945299843cSLei Zhang                                        Options options)
4955299843cSLei Zhang     : targetEnv(targetAttr), options(options) {
49601178654SLei Zhang   // Add conversions. The order matters here: later ones will be tried earlier.
49701178654SLei Zhang 
49801178654SLei Zhang   // Allow all SPIR-V dialect specific types. This assumes all builtin types
49901178654SLei Zhang   // adopted in the SPIR-V dialect (i.e., IntegerType, FloatType, VectorType)
50001178654SLei Zhang   // were tried before.
50101178654SLei Zhang   //
50201178654SLei Zhang   // TODO: this assumes that the SPIR-V types are valid to use in
50301178654SLei Zhang   // the given target environment, which should be the case if the whole
50401178654SLei Zhang   // pipeline is driven by the same target environment. Still, we probably still
50501178654SLei Zhang   // want to validate and convert to be safe.
50601178654SLei Zhang   addConversion([](spirv::SPIRVType type) { return type; });
50701178654SLei Zhang 
50801178654SLei Zhang   addConversion([](IndexType indexType) {
50901178654SLei Zhang     return SPIRVTypeConverter::getIndexType(indexType.getContext());
51001178654SLei Zhang   });
51101178654SLei Zhang 
51201178654SLei Zhang   addConversion([this](IntegerType intType) -> Optional<Type> {
51301178654SLei Zhang     if (auto scalarType = intType.dyn_cast<spirv::ScalarType>())
5145299843cSLei Zhang       return convertScalarType(this->targetEnv, this->options, scalarType);
515004f29c0SLei Zhang     return Type();
51601178654SLei Zhang   });
51701178654SLei Zhang 
51801178654SLei Zhang   addConversion([this](FloatType floatType) -> Optional<Type> {
51901178654SLei Zhang     if (auto scalarType = floatType.dyn_cast<spirv::ScalarType>())
5205299843cSLei Zhang       return convertScalarType(this->targetEnv, this->options, scalarType);
521004f29c0SLei Zhang     return Type();
52201178654SLei Zhang   });
52301178654SLei Zhang 
52401178654SLei Zhang   addConversion([this](VectorType vectorType) {
5255299843cSLei Zhang     return convertVectorType(this->targetEnv, this->options, vectorType);
52601178654SLei Zhang   });
52701178654SLei Zhang 
52801178654SLei Zhang   addConversion([this](TensorType tensorType) {
5295299843cSLei Zhang     return convertTensorType(this->targetEnv, this->options, tensorType);
53001178654SLei Zhang   });
53101178654SLei Zhang 
53201178654SLei Zhang   addConversion([this](MemRefType memRefType) {
5335299843cSLei Zhang     return convertMemrefType(this->targetEnv, this->options, memRefType);
53401178654SLei Zhang   });
53501178654SLei Zhang }
53601178654SLei Zhang 
53701178654SLei Zhang //===----------------------------------------------------------------------===//
53801178654SLei Zhang // FuncOp Conversion Patterns
53901178654SLei Zhang //===----------------------------------------------------------------------===//
54001178654SLei Zhang 
54101178654SLei Zhang namespace {
54201178654SLei Zhang /// A pattern for rewriting function signature to convert arguments of functions
54301178654SLei Zhang /// to be of valid SPIR-V types.
5447c3ae48fSLei Zhang class FuncOpConversion final : public OpConversionPattern<FuncOp> {
54501178654SLei Zhang public:
5467c3ae48fSLei Zhang   using OpConversionPattern<FuncOp>::OpConversionPattern;
54701178654SLei Zhang 
54801178654SLei Zhang   LogicalResult
54901178654SLei Zhang   matchAndRewrite(FuncOp funcOp, ArrayRef<Value> operands,
55001178654SLei Zhang                   ConversionPatternRewriter &rewriter) const override;
55101178654SLei Zhang };
55201178654SLei Zhang } // namespace
55301178654SLei Zhang 
55401178654SLei Zhang LogicalResult
55501178654SLei Zhang FuncOpConversion::matchAndRewrite(FuncOp funcOp, ArrayRef<Value> operands,
55601178654SLei Zhang                                   ConversionPatternRewriter &rewriter) const {
55701178654SLei Zhang   auto fnType = funcOp.getType();
55842980a78SLei Zhang   if (fnType.getNumResults() > 1)
55901178654SLei Zhang     return failure();
56001178654SLei Zhang 
56101178654SLei Zhang   TypeConverter::SignatureConversion signatureConverter(fnType.getNumInputs());
56242980a78SLei Zhang   for (auto argType : enumerate(fnType.getInputs())) {
5637c3ae48fSLei Zhang     auto convertedType = getTypeConverter()->convertType(argType.value());
56401178654SLei Zhang     if (!convertedType)
56501178654SLei Zhang       return failure();
56601178654SLei Zhang     signatureConverter.addInputs(argType.index(), convertedType);
56701178654SLei Zhang   }
56801178654SLei Zhang 
56942980a78SLei Zhang   Type resultType;
5705299843cSLei Zhang   if (fnType.getNumResults() == 1) {
5717c3ae48fSLei Zhang     resultType = getTypeConverter()->convertType(fnType.getResult(0));
5725299843cSLei Zhang     if (!resultType)
5735299843cSLei Zhang       return failure();
5745299843cSLei Zhang   }
57542980a78SLei Zhang 
57601178654SLei Zhang   // Create the converted spv.func op.
57701178654SLei Zhang   auto newFuncOp = rewriter.create<spirv::FuncOp>(
57801178654SLei Zhang       funcOp.getLoc(), funcOp.getName(),
57901178654SLei Zhang       rewriter.getFunctionType(signatureConverter.getConvertedTypes(),
58042980a78SLei Zhang                                resultType ? TypeRange(resultType)
58142980a78SLei Zhang                                           : TypeRange()));
58201178654SLei Zhang 
58301178654SLei Zhang   // Copy over all attributes other than the function name and type.
58456774bddSMarius Brehler   for (const auto &namedAttr : funcOp->getAttrs()) {
58501178654SLei Zhang     if (namedAttr.first != impl::getTypeAttrName() &&
58601178654SLei Zhang         namedAttr.first != SymbolTable::getSymbolAttrName())
58701178654SLei Zhang       newFuncOp->setAttr(namedAttr.first, namedAttr.second);
58801178654SLei Zhang   }
58901178654SLei Zhang 
59001178654SLei Zhang   rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(),
59101178654SLei Zhang                               newFuncOp.end());
5927c3ae48fSLei Zhang   if (failed(rewriter.convertRegionTypes(
5937c3ae48fSLei Zhang           &newFuncOp.getBody(), *getTypeConverter(), &signatureConverter)))
59401178654SLei Zhang     return failure();
59501178654SLei Zhang   rewriter.eraseOp(funcOp);
59601178654SLei Zhang   return success();
59701178654SLei Zhang }
59801178654SLei Zhang 
599dc4e913bSChris Lattner void mlir::populateBuiltinFuncToSPIRVPatterns(SPIRVTypeConverter &typeConverter,
600dc4e913bSChris Lattner                                               RewritePatternSet &patterns) {
601dc4e913bSChris Lattner   patterns.add<FuncOpConversion>(typeConverter, patterns.getContext());
60201178654SLei Zhang }
60301178654SLei Zhang 
60401178654SLei Zhang //===----------------------------------------------------------------------===//
60501178654SLei Zhang // Builtin Variables
60601178654SLei Zhang //===----------------------------------------------------------------------===//
60701178654SLei Zhang 
60801178654SLei Zhang static spirv::GlobalVariableOp getBuiltinVariable(Block &body,
60901178654SLei Zhang                                                   spirv::BuiltIn builtin) {
61001178654SLei Zhang   // Look through all global variables in the given `body` block and check if
611c74eb466SKareemErgawy-TomTom   // there is a spv.GlobalVariable that has the same `builtin` attribute.
61201178654SLei Zhang   for (auto varOp : body.getOps<spirv::GlobalVariableOp>()) {
61301178654SLei Zhang     if (auto builtinAttr = varOp->getAttrOfType<StringAttr>(
61401178654SLei Zhang             spirv::SPIRVDialect::getAttributeName(
61501178654SLei Zhang                 spirv::Decoration::BuiltIn))) {
61601178654SLei Zhang       auto varBuiltIn = spirv::symbolizeBuiltIn(builtinAttr.getValue());
61701178654SLei Zhang       if (varBuiltIn && varBuiltIn.getValue() == builtin) {
61801178654SLei Zhang         return varOp;
61901178654SLei Zhang       }
62001178654SLei Zhang     }
62101178654SLei Zhang   }
62201178654SLei Zhang   return nullptr;
62301178654SLei Zhang }
62401178654SLei Zhang 
62501178654SLei Zhang /// Gets name of global variable for a builtin.
62601178654SLei Zhang static std::string getBuiltinVarName(spirv::BuiltIn builtin) {
62701178654SLei Zhang   return std::string("__builtin_var_") + stringifyBuiltIn(builtin).str() + "__";
62801178654SLei Zhang }
62901178654SLei Zhang 
63001178654SLei Zhang /// Gets or inserts a global variable for a builtin within `body` block.
63101178654SLei Zhang static spirv::GlobalVariableOp
63201178654SLei Zhang getOrInsertBuiltinVariable(Block &body, Location loc, spirv::BuiltIn builtin,
63301178654SLei Zhang                            OpBuilder &builder) {
63401178654SLei Zhang   if (auto varOp = getBuiltinVariable(body, builtin))
63501178654SLei Zhang     return varOp;
63601178654SLei Zhang 
63701178654SLei Zhang   OpBuilder::InsertionGuard guard(builder);
63801178654SLei Zhang   builder.setInsertionPointToStart(&body);
63901178654SLei Zhang 
64001178654SLei Zhang   spirv::GlobalVariableOp newVarOp;
64101178654SLei Zhang   switch (builtin) {
64201178654SLei Zhang   case spirv::BuiltIn::NumWorkgroups:
64301178654SLei Zhang   case spirv::BuiltIn::WorkgroupSize:
64401178654SLei Zhang   case spirv::BuiltIn::WorkgroupId:
64501178654SLei Zhang   case spirv::BuiltIn::LocalInvocationId:
64601178654SLei Zhang   case spirv::BuiltIn::GlobalInvocationId: {
64701178654SLei Zhang     auto ptrType = spirv::PointerType::get(
64801178654SLei Zhang         VectorType::get({3}, builder.getIntegerType(32)),
64901178654SLei Zhang         spirv::StorageClass::Input);
65001178654SLei Zhang     std::string name = getBuiltinVarName(builtin);
65101178654SLei Zhang     newVarOp =
65201178654SLei Zhang         builder.create<spirv::GlobalVariableOp>(loc, ptrType, name, builtin);
65301178654SLei Zhang     break;
65401178654SLei Zhang   }
65501178654SLei Zhang   case spirv::BuiltIn::SubgroupId:
65601178654SLei Zhang   case spirv::BuiltIn::NumSubgroups:
65701178654SLei Zhang   case spirv::BuiltIn::SubgroupSize: {
65801178654SLei Zhang     auto ptrType = spirv::PointerType::get(builder.getIntegerType(32),
65901178654SLei Zhang                                            spirv::StorageClass::Input);
66001178654SLei Zhang     std::string name = getBuiltinVarName(builtin);
66101178654SLei Zhang     newVarOp =
66201178654SLei Zhang         builder.create<spirv::GlobalVariableOp>(loc, ptrType, name, builtin);
66301178654SLei Zhang     break;
66401178654SLei Zhang   }
66501178654SLei Zhang   default:
66601178654SLei Zhang     emitError(loc, "unimplemented builtin variable generation for ")
66701178654SLei Zhang         << stringifyBuiltIn(builtin);
66801178654SLei Zhang   }
66901178654SLei Zhang   return newVarOp;
67001178654SLei Zhang }
67101178654SLei Zhang 
67201178654SLei Zhang Value mlir::spirv::getBuiltinVariableValue(Operation *op,
67301178654SLei Zhang                                            spirv::BuiltIn builtin,
67401178654SLei Zhang                                            OpBuilder &builder) {
67501178654SLei Zhang   Operation *parent = SymbolTable::getNearestSymbolTable(op->getParentOp());
67601178654SLei Zhang   if (!parent) {
67701178654SLei Zhang     op->emitError("expected operation to be within a module-like op");
67801178654SLei Zhang     return nullptr;
67901178654SLei Zhang   }
68001178654SLei Zhang 
68101178654SLei Zhang   spirv::GlobalVariableOp varOp = getOrInsertBuiltinVariable(
68201178654SLei Zhang       *parent->getRegion(0).begin(), op->getLoc(), builtin, builder);
68301178654SLei Zhang   Value ptr = builder.create<spirv::AddressOfOp>(op->getLoc(), varOp);
68401178654SLei Zhang   return builder.create<spirv::LoadOp>(op->getLoc(), ptr);
68501178654SLei Zhang }
68601178654SLei Zhang 
68701178654SLei Zhang //===----------------------------------------------------------------------===//
6886dd07fa5SLei Zhang // Push constant storage
6896dd07fa5SLei Zhang //===----------------------------------------------------------------------===//
6906dd07fa5SLei Zhang 
6916dd07fa5SLei Zhang /// Returns the pointer type for the push constant storage containing
6926dd07fa5SLei Zhang /// `elementCount` 32-bit integer values.
6936dd07fa5SLei Zhang static spirv::PointerType getPushConstantStorageType(unsigned elementCount,
6946dd07fa5SLei Zhang                                                      Builder &builder) {
6956dd07fa5SLei Zhang   auto arrayType = spirv::ArrayType::get(
6966dd07fa5SLei Zhang       SPIRVTypeConverter::getIndexType(builder.getContext()), elementCount,
6976dd07fa5SLei Zhang       /*stride=*/4);
6986dd07fa5SLei Zhang   auto structType = spirv::StructType::get({arrayType}, /*offsetInfo=*/0);
6996dd07fa5SLei Zhang   return spirv::PointerType::get(structType, spirv::StorageClass::PushConstant);
7006dd07fa5SLei Zhang }
7016dd07fa5SLei Zhang 
7026dd07fa5SLei Zhang /// Returns the push constant varible containing `elementCount` 32-bit integer
7036dd07fa5SLei Zhang /// values in `body`. Returns null op if such an op does not exit.
7046dd07fa5SLei Zhang static spirv::GlobalVariableOp getPushConstantVariable(Block &body,
7056dd07fa5SLei Zhang                                                        unsigned elementCount) {
7066dd07fa5SLei Zhang   for (auto varOp : body.getOps<spirv::GlobalVariableOp>()) {
7076dd07fa5SLei Zhang     auto ptrType = varOp.type().cast<spirv::PointerType>();
7086dd07fa5SLei Zhang     // Note that Vulkan requires "There must be no more than one push constant
7096dd07fa5SLei Zhang     // block statically used per shader entry point." So we should always reuse
7106dd07fa5SLei Zhang     // the existing one.
7116dd07fa5SLei Zhang     if (ptrType.getStorageClass() == spirv::StorageClass::PushConstant) {
7126dd07fa5SLei Zhang       auto numElements = ptrType.getPointeeType()
7136dd07fa5SLei Zhang                              .cast<spirv::StructType>()
7146dd07fa5SLei Zhang                              .getElementType(0)
7156dd07fa5SLei Zhang                              .cast<spirv::ArrayType>()
7166dd07fa5SLei Zhang                              .getNumElements();
7176dd07fa5SLei Zhang       if (numElements == elementCount)
7186dd07fa5SLei Zhang         return varOp;
7196dd07fa5SLei Zhang     }
7206dd07fa5SLei Zhang   }
7216dd07fa5SLei Zhang   return nullptr;
7226dd07fa5SLei Zhang }
7236dd07fa5SLei Zhang 
7246dd07fa5SLei Zhang /// Gets or inserts a global variable for push constant storage containing
7256dd07fa5SLei Zhang /// `elementCount` 32-bit integer values in `block`.
7266dd07fa5SLei Zhang static spirv::GlobalVariableOp
7276dd07fa5SLei Zhang getOrInsertPushConstantVariable(Location loc, Block &block,
7286dd07fa5SLei Zhang                                 unsigned elementCount, OpBuilder &b) {
7296dd07fa5SLei Zhang   if (auto varOp = getPushConstantVariable(block, elementCount))
7306dd07fa5SLei Zhang     return varOp;
7316dd07fa5SLei Zhang 
7326dd07fa5SLei Zhang   auto builder = OpBuilder::atBlockBegin(&block, b.getListener());
7336dd07fa5SLei Zhang   auto type = getPushConstantStorageType(elementCount, builder);
7346dd07fa5SLei Zhang   const char *name = "__push_constant_var__";
7356dd07fa5SLei Zhang   return builder.create<spirv::GlobalVariableOp>(loc, type, name,
7366dd07fa5SLei Zhang                                                  /*initializer=*/nullptr);
7376dd07fa5SLei Zhang }
7386dd07fa5SLei Zhang 
7396dd07fa5SLei Zhang Value spirv::getPushConstantValue(Operation *op, unsigned elementCount,
7406dd07fa5SLei Zhang                                   unsigned offset, OpBuilder &builder) {
7416dd07fa5SLei Zhang   Location loc = op->getLoc();
7426dd07fa5SLei Zhang   Operation *parent = SymbolTable::getNearestSymbolTable(op->getParentOp());
7436dd07fa5SLei Zhang   if (!parent) {
7446dd07fa5SLei Zhang     op->emitError("expected operation to be within a module-like op");
7456dd07fa5SLei Zhang     return nullptr;
7466dd07fa5SLei Zhang   }
7476dd07fa5SLei Zhang 
7486dd07fa5SLei Zhang   spirv::GlobalVariableOp varOp = getOrInsertPushConstantVariable(
7496dd07fa5SLei Zhang       loc, parent->getRegion(0).front(), elementCount, builder);
7506dd07fa5SLei Zhang 
7516dd07fa5SLei Zhang   auto i32Type = SPIRVTypeConverter::getIndexType(builder.getContext());
7526dd07fa5SLei Zhang   Value zeroOp = spirv::ConstantOp::getZero(i32Type, loc, builder);
7536dd07fa5SLei Zhang   Value offsetOp = builder.create<spirv::ConstantOp>(
7546dd07fa5SLei Zhang       loc, i32Type, builder.getI32IntegerAttr(offset));
7556dd07fa5SLei Zhang   auto addrOp = builder.create<spirv::AddressOfOp>(loc, varOp);
7566dd07fa5SLei Zhang   auto acOp = builder.create<spirv::AccessChainOp>(
7576dd07fa5SLei Zhang       loc, addrOp, llvm::makeArrayRef({zeroOp, offsetOp}));
7586dd07fa5SLei Zhang   return builder.create<spirv::LoadOp>(loc, acOp);
7596dd07fa5SLei Zhang }
7606dd07fa5SLei Zhang 
7616dd07fa5SLei Zhang //===----------------------------------------------------------------------===//
76201178654SLei Zhang // Index calculation
76301178654SLei Zhang //===----------------------------------------------------------------------===//
76401178654SLei Zhang 
765bb6f5c83SLei Zhang Value mlir::spirv::linearizeIndex(ValueRange indices, ArrayRef<int64_t> strides,
766bb6f5c83SLei Zhang                                   int64_t offset, Location loc,
767bb6f5c83SLei Zhang                                   OpBuilder &builder) {
768bb6f5c83SLei Zhang   assert(indices.size() == strides.size() &&
769bb6f5c83SLei Zhang          "must provide indices for all dimensions");
770bb6f5c83SLei Zhang 
771bb6f5c83SLei Zhang   auto indexType = SPIRVTypeConverter::getIndexType(builder.getContext());
772bb6f5c83SLei Zhang 
773bb6f5c83SLei Zhang   // TODO: Consider moving to use affine.apply and patterns converting
774bb6f5c83SLei Zhang   // affine.apply to standard ops. This needs converting to SPIR-V passes to be
775bb6f5c83SLei Zhang   // broken down into progressive small steps so we can have intermediate steps
776bb6f5c83SLei Zhang   // using other dialects. At the moment SPIR-V is the final sink.
777bb6f5c83SLei Zhang 
778bb6f5c83SLei Zhang   Value linearizedIndex = builder.create<spirv::ConstantOp>(
779bb6f5c83SLei Zhang       loc, indexType, IntegerAttr::get(indexType, offset));
780bb6f5c83SLei Zhang   for (auto index : llvm::enumerate(indices)) {
781bb6f5c83SLei Zhang     Value strideVal = builder.create<spirv::ConstantOp>(
782bb6f5c83SLei Zhang         loc, indexType, IntegerAttr::get(indexType, strides[index.index()]));
783bb6f5c83SLei Zhang     Value update = builder.create<spirv::IMulOp>(loc, strideVal, index.value());
784bb6f5c83SLei Zhang     linearizedIndex =
785bb6f5c83SLei Zhang         builder.create<spirv::IAddOp>(loc, linearizedIndex, update);
786bb6f5c83SLei Zhang   }
787bb6f5c83SLei Zhang   return linearizedIndex;
788bb6f5c83SLei Zhang }
789bb6f5c83SLei Zhang 
79001178654SLei Zhang spirv::AccessChainOp mlir::spirv::getElementPtr(
79101178654SLei Zhang     SPIRVTypeConverter &typeConverter, MemRefType baseType, Value basePtr,
79201178654SLei Zhang     ValueRange indices, Location loc, OpBuilder &builder) {
79301178654SLei Zhang   // Get base and offset of the MemRefType and verify they are static.
79401178654SLei Zhang 
79501178654SLei Zhang   int64_t offset;
79601178654SLei Zhang   SmallVector<int64_t, 4> strides;
79701178654SLei Zhang   if (failed(getStridesAndOffset(baseType, strides, offset)) ||
79801178654SLei Zhang       llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset()) ||
79901178654SLei Zhang       offset == MemRefType::getDynamicStrideOrOffset()) {
80001178654SLei Zhang     return nullptr;
80101178654SLei Zhang   }
80201178654SLei Zhang 
80301178654SLei Zhang   auto indexType = typeConverter.getIndexType(builder.getContext());
80401178654SLei Zhang 
80501178654SLei Zhang   SmallVector<Value, 2> linearizedIndices;
80601178654SLei Zhang   auto zero = spirv::ConstantOp::getZero(indexType, loc, builder);
807bb6f5c83SLei Zhang 
808bb6f5c83SLei Zhang   // Add a '0' at the start to index into the struct.
80901178654SLei Zhang   linearizedIndices.push_back(zero);
81001178654SLei Zhang 
81101178654SLei Zhang   if (baseType.getRank() == 0) {
81201178654SLei Zhang     linearizedIndices.push_back(zero);
81301178654SLei Zhang   } else {
814bb6f5c83SLei Zhang     linearizedIndices.push_back(
815bb6f5c83SLei Zhang         linearizeIndex(indices, strides, offset, loc, builder));
81601178654SLei Zhang   }
81701178654SLei Zhang   return builder.create<spirv::AccessChainOp>(loc, basePtr, linearizedIndices);
81801178654SLei Zhang }
81901178654SLei Zhang 
82001178654SLei Zhang //===----------------------------------------------------------------------===//
82101178654SLei Zhang // SPIR-V ConversionTarget
82201178654SLei Zhang //===----------------------------------------------------------------------===//
82301178654SLei Zhang 
8246dd07fa5SLei Zhang std::unique_ptr<SPIRVConversionTarget>
8256dd07fa5SLei Zhang SPIRVConversionTarget::get(spirv::TargetEnvAttr targetAttr) {
82601178654SLei Zhang   std::unique_ptr<SPIRVConversionTarget> target(
82701178654SLei Zhang       // std::make_unique does not work here because the constructor is private.
82801178654SLei Zhang       new SPIRVConversionTarget(targetAttr));
82901178654SLei Zhang   SPIRVConversionTarget *targetPtr = target.get();
8306dd07fa5SLei Zhang   target->addDynamicallyLegalDialect<spirv::SPIRVDialect>(
83101178654SLei Zhang       // We need to capture the raw pointer here because it is stable:
83201178654SLei Zhang       // target will be destroyed once this function is returned.
83301178654SLei Zhang       [targetPtr](Operation *op) { return targetPtr->isLegalOp(op); });
83401178654SLei Zhang   return target;
83501178654SLei Zhang }
83601178654SLei Zhang 
8376dd07fa5SLei Zhang SPIRVConversionTarget::SPIRVConversionTarget(spirv::TargetEnvAttr targetAttr)
83801178654SLei Zhang     : ConversionTarget(*targetAttr.getContext()), targetEnv(targetAttr) {}
83901178654SLei Zhang 
8406dd07fa5SLei Zhang bool SPIRVConversionTarget::isLegalOp(Operation *op) {
84101178654SLei Zhang   // Make sure this op is available at the given version. Ops not implementing
84201178654SLei Zhang   // QueryMinVersionInterface/QueryMaxVersionInterface are available to all
84301178654SLei Zhang   // SPIR-V versions.
84401178654SLei Zhang   if (auto minVersion = dyn_cast<spirv::QueryMinVersionInterface>(op))
84501178654SLei Zhang     if (minVersion.getMinVersion() > this->targetEnv.getVersion()) {
84601178654SLei Zhang       LLVM_DEBUG(llvm::dbgs()
84701178654SLei Zhang                  << op->getName() << " illegal: requiring min version "
84801178654SLei Zhang                  << spirv::stringifyVersion(minVersion.getMinVersion())
84901178654SLei Zhang                  << "\n");
85001178654SLei Zhang       return false;
85101178654SLei Zhang     }
85201178654SLei Zhang   if (auto maxVersion = dyn_cast<spirv::QueryMaxVersionInterface>(op))
85301178654SLei Zhang     if (maxVersion.getMaxVersion() < this->targetEnv.getVersion()) {
85401178654SLei Zhang       LLVM_DEBUG(llvm::dbgs()
85501178654SLei Zhang                  << op->getName() << " illegal: requiring max version "
85601178654SLei Zhang                  << spirv::stringifyVersion(maxVersion.getMaxVersion())
85701178654SLei Zhang                  << "\n");
85801178654SLei Zhang       return false;
85901178654SLei Zhang     }
86001178654SLei Zhang 
86101178654SLei Zhang   // Make sure this op's required extensions are allowed to use. Ops not
86201178654SLei Zhang   // implementing QueryExtensionInterface do not require extensions to be
86301178654SLei Zhang   // available.
86401178654SLei Zhang   if (auto extensions = dyn_cast<spirv::QueryExtensionInterface>(op))
86501178654SLei Zhang     if (failed(checkExtensionRequirements(op->getName(), this->targetEnv,
86601178654SLei Zhang                                           extensions.getExtensions())))
86701178654SLei Zhang       return false;
86801178654SLei Zhang 
86901178654SLei Zhang   // Make sure this op's required extensions are allowed to use. Ops not
87001178654SLei Zhang   // implementing QueryCapabilityInterface do not require capabilities to be
87101178654SLei Zhang   // available.
87201178654SLei Zhang   if (auto capabilities = dyn_cast<spirv::QueryCapabilityInterface>(op))
87301178654SLei Zhang     if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv,
87401178654SLei Zhang                                            capabilities.getCapabilities())))
87501178654SLei Zhang       return false;
87601178654SLei Zhang 
87701178654SLei Zhang   SmallVector<Type, 4> valueTypes;
87801178654SLei Zhang   valueTypes.append(op->operand_type_begin(), op->operand_type_end());
87901178654SLei Zhang   valueTypes.append(op->result_type_begin(), op->result_type_end());
88001178654SLei Zhang 
88101178654SLei Zhang   // Special treatment for global variables, whose type requirements are
88201178654SLei Zhang   // conveyed by type attributes.
88301178654SLei Zhang   if (auto globalVar = dyn_cast<spirv::GlobalVariableOp>(op))
88401178654SLei Zhang     valueTypes.push_back(globalVar.type());
88501178654SLei Zhang 
88601178654SLei Zhang   // Make sure the op's operands/results use types that are allowed by the
88701178654SLei Zhang   // target environment.
88801178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 4> typeExtensions;
88901178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 8> typeCapabilities;
89001178654SLei Zhang   for (Type valueType : valueTypes) {
89101178654SLei Zhang     typeExtensions.clear();
89201178654SLei Zhang     valueType.cast<spirv::SPIRVType>().getExtensions(typeExtensions);
89301178654SLei Zhang     if (failed(checkExtensionRequirements(op->getName(), this->targetEnv,
89401178654SLei Zhang                                           typeExtensions)))
89501178654SLei Zhang       return false;
89601178654SLei Zhang 
89701178654SLei Zhang     typeCapabilities.clear();
89801178654SLei Zhang     valueType.cast<spirv::SPIRVType>().getCapabilities(typeCapabilities);
89901178654SLei Zhang     if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv,
90001178654SLei Zhang                                            typeCapabilities)))
90101178654SLei Zhang       return false;
90201178654SLei Zhang   }
90301178654SLei Zhang 
90401178654SLei Zhang   return true;
90501178654SLei Zhang }
906