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 
8701178654SLei Zhang //===----------------------------------------------------------------------===//
8801178654SLei Zhang // Type Conversion
8901178654SLei Zhang //===----------------------------------------------------------------------===//
9001178654SLei Zhang 
9101178654SLei Zhang Type SPIRVTypeConverter::getIndexType(MLIRContext *context) {
9201178654SLei Zhang   // Convert to 32-bit integers for now. Might need a way to control this in
9301178654SLei Zhang   // future.
9401178654SLei Zhang   // TODO: It is probably better to make it 64-bit integers. To
9501178654SLei Zhang   // this some support is needed in SPIR-V dialect for Conversion
9601178654SLei Zhang   // instructions. The Vulkan spec requires the builtins like
9701178654SLei Zhang   // GlobalInvocationID, etc. to be 32-bit (unsigned) integers which should be
9801178654SLei Zhang   // SExtended to 64-bit for index computations.
991b97cdf8SRiver Riddle   return IntegerType::get(context, 32);
10001178654SLei Zhang }
10101178654SLei Zhang 
10201178654SLei Zhang /// Mapping between SPIR-V storage classes to memref memory spaces.
10301178654SLei Zhang ///
10401178654SLei Zhang /// Note: memref does not have a defined semantics for each memory space; it
10501178654SLei Zhang /// depends on the context where it is used. There are no particular reasons
10601178654SLei Zhang /// behind the number assignments; we try to follow NVVM conventions and largely
10701178654SLei Zhang /// give common storage classes a smaller number. The hope is use symbolic
10801178654SLei Zhang /// memory space representation eventually after memref supports it.
10901178654SLei Zhang // TODO: swap Generic and StorageBuffer assignment to be more akin
11001178654SLei Zhang // to NVVM.
11101178654SLei Zhang #define STORAGE_SPACE_MAP_LIST(MAP_FN)                                         \
11201178654SLei Zhang   MAP_FN(spirv::StorageClass::Generic, 1)                                      \
11301178654SLei Zhang   MAP_FN(spirv::StorageClass::StorageBuffer, 0)                                \
11401178654SLei Zhang   MAP_FN(spirv::StorageClass::Workgroup, 3)                                    \
11501178654SLei Zhang   MAP_FN(spirv::StorageClass::Uniform, 4)                                      \
11601178654SLei Zhang   MAP_FN(spirv::StorageClass::Private, 5)                                      \
11701178654SLei Zhang   MAP_FN(spirv::StorageClass::Function, 6)                                     \
11801178654SLei Zhang   MAP_FN(spirv::StorageClass::PushConstant, 7)                                 \
11901178654SLei Zhang   MAP_FN(spirv::StorageClass::UniformConstant, 8)                              \
12001178654SLei Zhang   MAP_FN(spirv::StorageClass::Input, 9)                                        \
12101178654SLei Zhang   MAP_FN(spirv::StorageClass::Output, 10)                                      \
12201178654SLei Zhang   MAP_FN(spirv::StorageClass::CrossWorkgroup, 11)                              \
12301178654SLei Zhang   MAP_FN(spirv::StorageClass::AtomicCounter, 12)                               \
12401178654SLei Zhang   MAP_FN(spirv::StorageClass::Image, 13)                                       \
12501178654SLei Zhang   MAP_FN(spirv::StorageClass::CallableDataNV, 14)                              \
12601178654SLei Zhang   MAP_FN(spirv::StorageClass::IncomingCallableDataNV, 15)                      \
12701178654SLei Zhang   MAP_FN(spirv::StorageClass::RayPayloadNV, 16)                                \
12801178654SLei Zhang   MAP_FN(spirv::StorageClass::HitAttributeNV, 17)                              \
12901178654SLei Zhang   MAP_FN(spirv::StorageClass::IncomingRayPayloadNV, 18)                        \
13001178654SLei Zhang   MAP_FN(spirv::StorageClass::ShaderRecordBufferNV, 19)                        \
13101178654SLei Zhang   MAP_FN(spirv::StorageClass::PhysicalStorageBuffer, 20)
13201178654SLei Zhang 
13301178654SLei Zhang unsigned
13401178654SLei Zhang SPIRVTypeConverter::getMemorySpaceForStorageClass(spirv::StorageClass storage) {
13501178654SLei Zhang #define STORAGE_SPACE_MAP_FN(storage, space)                                   \
13601178654SLei Zhang   case storage:                                                                \
13701178654SLei Zhang     return space;
13801178654SLei Zhang 
13901178654SLei Zhang   switch (storage) { STORAGE_SPACE_MAP_LIST(STORAGE_SPACE_MAP_FN) }
14001178654SLei Zhang #undef STORAGE_SPACE_MAP_FN
14101178654SLei Zhang   llvm_unreachable("unhandled storage class!");
14201178654SLei Zhang }
14301178654SLei Zhang 
14401178654SLei Zhang Optional<spirv::StorageClass>
14501178654SLei Zhang SPIRVTypeConverter::getStorageClassForMemorySpace(unsigned space) {
14601178654SLei Zhang #define STORAGE_SPACE_MAP_FN(storage, space)                                   \
14701178654SLei Zhang   case space:                                                                  \
14801178654SLei Zhang     return storage;
14901178654SLei Zhang 
15001178654SLei Zhang   switch (space) {
15101178654SLei Zhang     STORAGE_SPACE_MAP_LIST(STORAGE_SPACE_MAP_FN)
15201178654SLei Zhang   default:
15301178654SLei Zhang     return llvm::None;
15401178654SLei Zhang   }
15501178654SLei Zhang #undef STORAGE_SPACE_MAP_FN
15601178654SLei Zhang }
15701178654SLei Zhang 
158c3614358SHanhan Wang const SPIRVTypeConverter::Options &SPIRVTypeConverter::getOptions() const {
159c3614358SHanhan Wang   return options;
160c3614358SHanhan Wang }
161c3614358SHanhan Wang 
16201178654SLei Zhang #undef STORAGE_SPACE_MAP_LIST
16301178654SLei Zhang 
1645299843cSLei Zhang // TODO: This is a utility function that should probably be exposed by the
1655299843cSLei Zhang // SPIR-V dialect. Keeping it local till the use case arises.
1665299843cSLei Zhang static Optional<int64_t>
1675299843cSLei Zhang getTypeNumBytes(const SPIRVTypeConverter::Options &options, Type type) {
1685299843cSLei Zhang   if (type.isa<spirv::ScalarType>()) {
1695299843cSLei Zhang     auto bitWidth = type.getIntOrFloatBitWidth();
17001178654SLei Zhang     // According to the SPIR-V spec:
17101178654SLei Zhang     // "There is no physical size or bit pattern defined for values with boolean
17201178654SLei Zhang     // type. If they are stored (in conjunction with OpVariable), they can only
17301178654SLei Zhang     // be used with logical addressing operations, not physical, and only with
17401178654SLei Zhang     // non-externally visible shader Storage Classes: Workgroup, CrossWorkgroup,
17501178654SLei Zhang     // Private, Function, Input, and Output."
1765299843cSLei Zhang     if (bitWidth == 1)
17701178654SLei Zhang       return llvm::None;
17801178654SLei Zhang     return bitWidth / 8;
17901178654SLei Zhang   }
1806dd07fa5SLei Zhang 
1815299843cSLei Zhang   if (auto vecType = type.dyn_cast<VectorType>()) {
1825299843cSLei Zhang     auto elementSize = getTypeNumBytes(options, vecType.getElementType());
18301178654SLei Zhang     if (!elementSize)
18401178654SLei Zhang       return llvm::None;
1855299843cSLei Zhang     return vecType.getNumElements() * elementSize.getValue();
18601178654SLei Zhang   }
1876dd07fa5SLei Zhang 
1885299843cSLei Zhang   if (auto memRefType = type.dyn_cast<MemRefType>()) {
18901178654SLei Zhang     // TODO: Layout should also be controlled by the ABI attributes. For now
19001178654SLei Zhang     // using the layout from MemRef.
19101178654SLei Zhang     int64_t offset;
19201178654SLei Zhang     SmallVector<int64_t, 4> strides;
19301178654SLei Zhang     if (!memRefType.hasStaticShape() ||
1945299843cSLei Zhang         failed(getStridesAndOffset(memRefType, strides, offset)))
19501178654SLei Zhang       return llvm::None;
1965299843cSLei Zhang 
19701178654SLei Zhang     // To get the size of the memref object in memory, the total size is the
19801178654SLei Zhang     // max(stride * dimension-size) computed for all dimensions times the size
19901178654SLei Zhang     // of the element.
2005299843cSLei Zhang     auto elementSize = getTypeNumBytes(options, memRefType.getElementType());
2015299843cSLei Zhang     if (!elementSize)
20201178654SLei Zhang       return llvm::None;
2035299843cSLei Zhang 
2045299843cSLei Zhang     if (memRefType.getRank() == 0)
20501178654SLei Zhang       return elementSize;
2065299843cSLei Zhang 
20701178654SLei Zhang     auto dims = memRefType.getShape();
20801178654SLei Zhang     if (llvm::is_contained(dims, ShapedType::kDynamicSize) ||
20901178654SLei Zhang         offset == MemRefType::getDynamicStrideOrOffset() ||
2105299843cSLei Zhang         llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset()))
21101178654SLei Zhang       return llvm::None;
2125299843cSLei Zhang 
21301178654SLei Zhang     int64_t memrefSize = -1;
2145299843cSLei Zhang     for (auto shape : enumerate(dims))
21501178654SLei Zhang       memrefSize = std::max(memrefSize, shape.value() * strides[shape.index()]);
2165299843cSLei Zhang 
21701178654SLei Zhang     return (offset + memrefSize) * elementSize.getValue();
2186dd07fa5SLei Zhang   }
2196dd07fa5SLei Zhang 
2205299843cSLei Zhang   if (auto tensorType = type.dyn_cast<TensorType>()) {
2215299843cSLei Zhang     if (!tensorType.hasStaticShape())
22201178654SLei Zhang       return llvm::None;
2235299843cSLei Zhang 
2245299843cSLei Zhang     auto elementSize = getTypeNumBytes(options, tensorType.getElementType());
2255299843cSLei Zhang     if (!elementSize)
22601178654SLei Zhang       return llvm::None;
2275299843cSLei Zhang 
22801178654SLei Zhang     int64_t size = elementSize.getValue();
2295299843cSLei Zhang     for (auto shape : tensorType.getShape())
23001178654SLei Zhang       size *= shape;
2315299843cSLei Zhang 
23201178654SLei Zhang     return size;
23301178654SLei Zhang   }
2346dd07fa5SLei Zhang 
23501178654SLei Zhang   // TODO: Add size computation for other types.
23601178654SLei Zhang   return llvm::None;
23701178654SLei Zhang }
23801178654SLei Zhang 
23901178654SLei Zhang /// Converts a scalar `type` to a suitable type under the given `targetEnv`.
240004f29c0SLei Zhang static Type convertScalarType(const spirv::TargetEnv &targetEnv,
2415299843cSLei Zhang                               const SPIRVTypeConverter::Options &options,
242004f29c0SLei Zhang                               spirv::ScalarType type,
24301178654SLei Zhang                               Optional<spirv::StorageClass> storageClass = {}) {
24401178654SLei Zhang   // Get extension and capability requirements for the given type.
24501178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 1> extensions;
24601178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 2> capabilities;
24701178654SLei Zhang   type.getExtensions(extensions, storageClass);
24801178654SLei Zhang   type.getCapabilities(capabilities, storageClass);
24901178654SLei Zhang 
25001178654SLei Zhang   // If all requirements are met, then we can accept this type as-is.
25101178654SLei Zhang   if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) &&
25201178654SLei Zhang       succeeded(checkExtensionRequirements(type, targetEnv, extensions)))
25301178654SLei Zhang     return type;
25401178654SLei Zhang 
25501178654SLei Zhang   // Otherwise we need to adjust the type, which really means adjusting the
25601178654SLei Zhang   // bitwidth given this is a scalar type.
2575299843cSLei Zhang 
2585299843cSLei Zhang   if (!options.emulateNon32BitScalarTypes)
2595299843cSLei Zhang     return nullptr;
26001178654SLei Zhang 
26101178654SLei Zhang   if (auto floatType = type.dyn_cast<FloatType>()) {
26201178654SLei Zhang     LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n");
26301178654SLei Zhang     return Builder(targetEnv.getContext()).getF32Type();
26401178654SLei Zhang   }
26501178654SLei Zhang 
26601178654SLei Zhang   auto intType = type.cast<IntegerType>();
26701178654SLei Zhang   LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n");
2681b97cdf8SRiver Riddle   return IntegerType::get(targetEnv.getContext(), /*width=*/32,
2691b97cdf8SRiver Riddle                           intType.getSignedness());
27001178654SLei Zhang }
27101178654SLei Zhang 
27201178654SLei Zhang /// Converts a vector `type` to a suitable type under the given `targetEnv`.
273004f29c0SLei Zhang static Type convertVectorType(const spirv::TargetEnv &targetEnv,
2745299843cSLei Zhang                               const SPIRVTypeConverter::Options &options,
275004f29c0SLei Zhang                               VectorType type,
27601178654SLei Zhang                               Optional<spirv::StorageClass> storageClass = {}) {
2779f622b3dSLei Zhang   if (type.getRank() == 1 && type.getNumElements() == 1)
2789f622b3dSLei Zhang     return type.getElementType();
2799f622b3dSLei Zhang 
28001178654SLei Zhang   if (!spirv::CompositeType::isValid(type)) {
2819f622b3dSLei Zhang     // TODO: Vector types with more than four elements can be translated into
28201178654SLei Zhang     // array types.
2839f622b3dSLei Zhang     LLVM_DEBUG(llvm::dbgs() << type << " illegal: > 4-element unimplemented\n");
284004f29c0SLei Zhang     return nullptr;
28501178654SLei Zhang   }
28601178654SLei Zhang 
28701178654SLei Zhang   // Get extension and capability requirements for the given type.
28801178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 1> extensions;
28901178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 2> capabilities;
29001178654SLei Zhang   type.cast<spirv::CompositeType>().getExtensions(extensions, storageClass);
29101178654SLei Zhang   type.cast<spirv::CompositeType>().getCapabilities(capabilities, storageClass);
29201178654SLei Zhang 
29301178654SLei Zhang   // If all requirements are met, then we can accept this type as-is.
29401178654SLei Zhang   if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) &&
29501178654SLei Zhang       succeeded(checkExtensionRequirements(type, targetEnv, extensions)))
29601178654SLei Zhang     return type;
29701178654SLei Zhang 
29801178654SLei Zhang   auto elementType = convertScalarType(
2995299843cSLei Zhang       targetEnv, options, type.getElementType().cast<spirv::ScalarType>(),
3005299843cSLei Zhang       storageClass);
30101178654SLei Zhang   if (elementType)
302004f29c0SLei Zhang     return VectorType::get(type.getShape(), elementType);
303004f29c0SLei Zhang   return nullptr;
30401178654SLei Zhang }
30501178654SLei Zhang 
30601178654SLei Zhang /// Converts a tensor `type` to a suitable type under the given `targetEnv`.
30701178654SLei Zhang ///
30801178654SLei Zhang /// Note that this is mainly for lowering constant tensors. In SPIR-V one can
30901178654SLei Zhang /// create composite constants with OpConstantComposite to embed relative large
31001178654SLei Zhang /// constant values and use OpCompositeExtract and OpCompositeInsert to
31101178654SLei Zhang /// manipulate, like what we do for vectors.
312004f29c0SLei Zhang static Type convertTensorType(const spirv::TargetEnv &targetEnv,
3135299843cSLei Zhang                               const SPIRVTypeConverter::Options &options,
31401178654SLei Zhang                               TensorType type) {
31501178654SLei Zhang   // TODO: Handle dynamic shapes.
31601178654SLei Zhang   if (!type.hasStaticShape()) {
31701178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
31801178654SLei Zhang                << type << " illegal: dynamic shape unimplemented\n");
319004f29c0SLei Zhang     return nullptr;
32001178654SLei Zhang   }
32101178654SLei Zhang 
32201178654SLei Zhang   auto scalarType = type.getElementType().dyn_cast<spirv::ScalarType>();
32301178654SLei Zhang   if (!scalarType) {
32401178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
32501178654SLei Zhang                << type << " illegal: cannot convert non-scalar element type\n");
326004f29c0SLei Zhang     return nullptr;
32701178654SLei Zhang   }
32801178654SLei Zhang 
3295299843cSLei Zhang   Optional<int64_t> scalarSize = getTypeNumBytes(options, scalarType);
3305299843cSLei Zhang   Optional<int64_t> tensorSize = getTypeNumBytes(options, type);
33101178654SLei Zhang   if (!scalarSize || !tensorSize) {
33201178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
33301178654SLei Zhang                << type << " illegal: cannot deduce element count\n");
334004f29c0SLei Zhang     return nullptr;
33501178654SLei Zhang   }
33601178654SLei Zhang 
33701178654SLei Zhang   auto arrayElemCount = *tensorSize / *scalarSize;
3385299843cSLei Zhang   auto arrayElemType = convertScalarType(targetEnv, options, scalarType);
33901178654SLei Zhang   if (!arrayElemType)
340004f29c0SLei Zhang     return nullptr;
3415299843cSLei Zhang   Optional<int64_t> arrayElemSize = getTypeNumBytes(options, arrayElemType);
34201178654SLei Zhang   if (!arrayElemSize) {
34301178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
34401178654SLei Zhang                << type << " illegal: cannot deduce converted element size\n");
345004f29c0SLei Zhang     return nullptr;
34601178654SLei Zhang   }
34701178654SLei Zhang 
348004f29c0SLei Zhang   return spirv::ArrayType::get(arrayElemType, arrayElemCount, *arrayElemSize);
34901178654SLei Zhang }
35001178654SLei Zhang 
351c3614358SHanhan Wang static Type convertBoolMemrefType(const spirv::TargetEnv &targetEnv,
352c3614358SHanhan Wang                                   const SPIRVTypeConverter::Options &options,
353c3614358SHanhan Wang                                   MemRefType type) {
354c3614358SHanhan Wang   if (!type.hasStaticShape()) {
355c3614358SHanhan Wang     LLVM_DEBUG(llvm::dbgs()
356c3614358SHanhan Wang                << type << " dynamic shape on i1 is not supported yet\n");
357c3614358SHanhan Wang     return nullptr;
358c3614358SHanhan Wang   }
359c3614358SHanhan Wang 
360c3614358SHanhan Wang   Optional<spirv::StorageClass> storageClass =
361c3614358SHanhan Wang       SPIRVTypeConverter::getStorageClassForMemorySpace(
362c3614358SHanhan Wang           type.getMemorySpaceAsInt());
363c3614358SHanhan Wang   if (!storageClass) {
364c3614358SHanhan Wang     LLVM_DEBUG(llvm::dbgs()
365c3614358SHanhan Wang                << type << " illegal: cannot convert memory space\n");
366c3614358SHanhan Wang     return nullptr;
367c3614358SHanhan Wang   }
368c3614358SHanhan Wang 
369c3614358SHanhan Wang   unsigned numBoolBits = options.boolNumBits;
370c3614358SHanhan Wang   if (numBoolBits != 8) {
371c3614358SHanhan Wang     LLVM_DEBUG(llvm::dbgs()
372c3614358SHanhan Wang                << "using non-8-bit storage for bool types unimplemented");
373c3614358SHanhan Wang     return nullptr;
374c3614358SHanhan Wang   }
375c3614358SHanhan Wang   auto elementType = IntegerType::get(type.getContext(), numBoolBits)
376c3614358SHanhan Wang                          .dyn_cast<spirv::ScalarType>();
377c3614358SHanhan Wang   if (!elementType)
378c3614358SHanhan Wang     return nullptr;
379c3614358SHanhan Wang   Type arrayElemType =
380c3614358SHanhan Wang       convertScalarType(targetEnv, options, elementType, storageClass);
381c3614358SHanhan Wang   if (!arrayElemType)
382c3614358SHanhan Wang     return nullptr;
383c3614358SHanhan Wang   Optional<int64_t> arrayElemSize = getTypeNumBytes(options, arrayElemType);
384c3614358SHanhan Wang   if (!arrayElemSize) {
385c3614358SHanhan Wang     LLVM_DEBUG(llvm::dbgs()
386c3614358SHanhan Wang                << type << " illegal: cannot deduce converted element size\n");
387c3614358SHanhan Wang     return nullptr;
388c3614358SHanhan Wang   }
389c3614358SHanhan Wang 
390c3614358SHanhan Wang   int64_t memrefSize = (type.getNumElements() * numBoolBits + 7) / 8;
391c3614358SHanhan Wang   auto arrayElemCount = (memrefSize + *arrayElemSize - 1) / *arrayElemSize;
392c3614358SHanhan Wang   auto arrayType =
393c3614358SHanhan Wang       spirv::ArrayType::get(arrayElemType, arrayElemCount, *arrayElemSize);
394c3614358SHanhan Wang 
395c3614358SHanhan Wang   // Wrap in a struct to satisfy Vulkan interface requirements. Memrefs with
396c3614358SHanhan Wang   // workgroup storage class do not need the struct to be laid out explicitly.
397c3614358SHanhan Wang   auto structType = *storageClass == spirv::StorageClass::Workgroup
398c3614358SHanhan Wang                         ? spirv::StructType::get(arrayType)
399c3614358SHanhan Wang                         : spirv::StructType::get(arrayType, 0);
400c3614358SHanhan Wang   return spirv::PointerType::get(structType, *storageClass);
401c3614358SHanhan Wang }
402c3614358SHanhan Wang 
403004f29c0SLei Zhang static Type convertMemrefType(const spirv::TargetEnv &targetEnv,
4045299843cSLei Zhang                               const SPIRVTypeConverter::Options &options,
40501178654SLei Zhang                               MemRefType type) {
406c3614358SHanhan Wang   if (type.getElementType().isa<IntegerType>() &&
407c3614358SHanhan Wang       type.getElementTypeBitWidth() == 1) {
408c3614358SHanhan Wang     return convertBoolMemrefType(targetEnv, options, type);
409c3614358SHanhan Wang   }
410c3614358SHanhan Wang 
41101178654SLei Zhang   Optional<spirv::StorageClass> storageClass =
41237eca08eSVladislav Vinogradov       SPIRVTypeConverter::getStorageClassForMemorySpace(
41337eca08eSVladislav Vinogradov           type.getMemorySpaceAsInt());
41401178654SLei Zhang   if (!storageClass) {
41501178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
41601178654SLei Zhang                << type << " illegal: cannot convert memory space\n");
417004f29c0SLei Zhang     return nullptr;
41801178654SLei Zhang   }
41901178654SLei Zhang 
420004f29c0SLei Zhang   Type arrayElemType;
42101178654SLei Zhang   Type elementType = type.getElementType();
42201178654SLei Zhang   if (auto vecType = elementType.dyn_cast<VectorType>()) {
4235299843cSLei Zhang     arrayElemType =
4245299843cSLei Zhang         convertVectorType(targetEnv, options, vecType, storageClass);
42501178654SLei Zhang   } else if (auto scalarType = elementType.dyn_cast<spirv::ScalarType>()) {
4265299843cSLei Zhang     arrayElemType =
4275299843cSLei Zhang         convertScalarType(targetEnv, options, scalarType, storageClass);
42801178654SLei Zhang   } else {
42901178654SLei Zhang     LLVM_DEBUG(
43001178654SLei Zhang         llvm::dbgs()
43101178654SLei Zhang         << type
43201178654SLei Zhang         << " unhandled: can only convert scalar or vector element type\n");
433004f29c0SLei Zhang     return nullptr;
43401178654SLei Zhang   }
43501178654SLei Zhang   if (!arrayElemType)
436004f29c0SLei Zhang     return nullptr;
43701178654SLei Zhang 
4385299843cSLei Zhang   Optional<int64_t> elementSize = getTypeNumBytes(options, elementType);
43901178654SLei Zhang   if (!elementSize) {
44001178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
44101178654SLei Zhang                << type << " illegal: cannot deduce element size\n");
442004f29c0SLei Zhang     return nullptr;
44301178654SLei Zhang   }
44401178654SLei Zhang 
445*23b8264bSLei Zhang   Optional<int64_t> arrayElemSize = getTypeNumBytes(options, arrayElemType);
446*23b8264bSLei Zhang   if (!arrayElemSize) {
447*23b8264bSLei Zhang     LLVM_DEBUG(llvm::dbgs()
448*23b8264bSLei Zhang                << type << " illegal: cannot deduce converted element size\n");
449*23b8264bSLei Zhang     return nullptr;
450*23b8264bSLei Zhang   }
451*23b8264bSLei Zhang 
45201178654SLei Zhang   if (!type.hasStaticShape()) {
453*23b8264bSLei Zhang     auto arrayType =
454*23b8264bSLei Zhang         spirv::RuntimeArrayType::get(arrayElemType, *arrayElemSize);
45501178654SLei Zhang     // Wrap in a struct to satisfy Vulkan interface requirements.
45601178654SLei Zhang     auto structType = spirv::StructType::get(arrayType, 0);
45701178654SLei Zhang     return spirv::PointerType::get(structType, *storageClass);
45801178654SLei Zhang   }
45901178654SLei Zhang 
4605299843cSLei Zhang   Optional<int64_t> memrefSize = getTypeNumBytes(options, type);
46101178654SLei Zhang   if (!memrefSize) {
46201178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
46301178654SLei Zhang                << type << " illegal: cannot deduce element count\n");
464004f29c0SLei Zhang     return nullptr;
46501178654SLei Zhang   }
46601178654SLei Zhang 
46701178654SLei Zhang   auto arrayElemCount = *memrefSize / *elementSize;
46801178654SLei Zhang 
46901178654SLei Zhang 
47001178654SLei Zhang   auto arrayType =
471004f29c0SLei Zhang       spirv::ArrayType::get(arrayElemType, arrayElemCount, *arrayElemSize);
47201178654SLei Zhang 
47301178654SLei Zhang   // Wrap in a struct to satisfy Vulkan interface requirements. Memrefs with
47401178654SLei Zhang   // workgroup storage class do not need the struct to be laid out explicitly.
47501178654SLei Zhang   auto structType = *storageClass == spirv::StorageClass::Workgroup
47601178654SLei Zhang                         ? spirv::StructType::get(arrayType)
47701178654SLei Zhang                         : spirv::StructType::get(arrayType, 0);
47801178654SLei Zhang   return spirv::PointerType::get(structType, *storageClass);
47901178654SLei Zhang }
48001178654SLei Zhang 
4815299843cSLei Zhang SPIRVTypeConverter::SPIRVTypeConverter(spirv::TargetEnvAttr targetAttr,
4825299843cSLei Zhang                                        Options options)
4835299843cSLei Zhang     : targetEnv(targetAttr), options(options) {
48401178654SLei Zhang   // Add conversions. The order matters here: later ones will be tried earlier.
48501178654SLei Zhang 
48601178654SLei Zhang   // Allow all SPIR-V dialect specific types. This assumes all builtin types
48701178654SLei Zhang   // adopted in the SPIR-V dialect (i.e., IntegerType, FloatType, VectorType)
48801178654SLei Zhang   // were tried before.
48901178654SLei Zhang   //
49001178654SLei Zhang   // TODO: this assumes that the SPIR-V types are valid to use in
49101178654SLei Zhang   // the given target environment, which should be the case if the whole
49201178654SLei Zhang   // pipeline is driven by the same target environment. Still, we probably still
49301178654SLei Zhang   // want to validate and convert to be safe.
49401178654SLei Zhang   addConversion([](spirv::SPIRVType type) { return type; });
49501178654SLei Zhang 
49601178654SLei Zhang   addConversion([](IndexType indexType) {
49701178654SLei Zhang     return SPIRVTypeConverter::getIndexType(indexType.getContext());
49801178654SLei Zhang   });
49901178654SLei Zhang 
50001178654SLei Zhang   addConversion([this](IntegerType intType) -> Optional<Type> {
50101178654SLei Zhang     if (auto scalarType = intType.dyn_cast<spirv::ScalarType>())
5025299843cSLei Zhang       return convertScalarType(this->targetEnv, this->options, scalarType);
503004f29c0SLei Zhang     return Type();
50401178654SLei Zhang   });
50501178654SLei Zhang 
50601178654SLei Zhang   addConversion([this](FloatType floatType) -> Optional<Type> {
50701178654SLei Zhang     if (auto scalarType = floatType.dyn_cast<spirv::ScalarType>())
5085299843cSLei Zhang       return convertScalarType(this->targetEnv, this->options, scalarType);
509004f29c0SLei Zhang     return Type();
51001178654SLei Zhang   });
51101178654SLei Zhang 
51201178654SLei Zhang   addConversion([this](VectorType vectorType) {
5135299843cSLei Zhang     return convertVectorType(this->targetEnv, this->options, vectorType);
51401178654SLei Zhang   });
51501178654SLei Zhang 
51601178654SLei Zhang   addConversion([this](TensorType tensorType) {
5175299843cSLei Zhang     return convertTensorType(this->targetEnv, this->options, tensorType);
51801178654SLei Zhang   });
51901178654SLei Zhang 
52001178654SLei Zhang   addConversion([this](MemRefType memRefType) {
5215299843cSLei Zhang     return convertMemrefType(this->targetEnv, this->options, memRefType);
52201178654SLei Zhang   });
52301178654SLei Zhang }
52401178654SLei Zhang 
52501178654SLei Zhang //===----------------------------------------------------------------------===//
52601178654SLei Zhang // FuncOp Conversion Patterns
52701178654SLei Zhang //===----------------------------------------------------------------------===//
52801178654SLei Zhang 
52901178654SLei Zhang namespace {
53001178654SLei Zhang /// A pattern for rewriting function signature to convert arguments of functions
53101178654SLei Zhang /// to be of valid SPIR-V types.
5327c3ae48fSLei Zhang class FuncOpConversion final : public OpConversionPattern<FuncOp> {
53301178654SLei Zhang public:
5347c3ae48fSLei Zhang   using OpConversionPattern<FuncOp>::OpConversionPattern;
53501178654SLei Zhang 
53601178654SLei Zhang   LogicalResult
53701178654SLei Zhang   matchAndRewrite(FuncOp funcOp, ArrayRef<Value> operands,
53801178654SLei Zhang                   ConversionPatternRewriter &rewriter) const override;
53901178654SLei Zhang };
54001178654SLei Zhang } // namespace
54101178654SLei Zhang 
54201178654SLei Zhang LogicalResult
54301178654SLei Zhang FuncOpConversion::matchAndRewrite(FuncOp funcOp, ArrayRef<Value> operands,
54401178654SLei Zhang                                   ConversionPatternRewriter &rewriter) const {
54501178654SLei Zhang   auto fnType = funcOp.getType();
54642980a78SLei Zhang   if (fnType.getNumResults() > 1)
54701178654SLei Zhang     return failure();
54801178654SLei Zhang 
54901178654SLei Zhang   TypeConverter::SignatureConversion signatureConverter(fnType.getNumInputs());
55042980a78SLei Zhang   for (auto argType : enumerate(fnType.getInputs())) {
5517c3ae48fSLei Zhang     auto convertedType = getTypeConverter()->convertType(argType.value());
55201178654SLei Zhang     if (!convertedType)
55301178654SLei Zhang       return failure();
55401178654SLei Zhang     signatureConverter.addInputs(argType.index(), convertedType);
55501178654SLei Zhang   }
55601178654SLei Zhang 
55742980a78SLei Zhang   Type resultType;
5585299843cSLei Zhang   if (fnType.getNumResults() == 1) {
5597c3ae48fSLei Zhang     resultType = getTypeConverter()->convertType(fnType.getResult(0));
5605299843cSLei Zhang     if (!resultType)
5615299843cSLei Zhang       return failure();
5625299843cSLei Zhang   }
56342980a78SLei Zhang 
56401178654SLei Zhang   // Create the converted spv.func op.
56501178654SLei Zhang   auto newFuncOp = rewriter.create<spirv::FuncOp>(
56601178654SLei Zhang       funcOp.getLoc(), funcOp.getName(),
56701178654SLei Zhang       rewriter.getFunctionType(signatureConverter.getConvertedTypes(),
56842980a78SLei Zhang                                resultType ? TypeRange(resultType)
56942980a78SLei Zhang                                           : TypeRange()));
57001178654SLei Zhang 
57101178654SLei Zhang   // Copy over all attributes other than the function name and type.
57256774bddSMarius Brehler   for (const auto &namedAttr : funcOp->getAttrs()) {
57301178654SLei Zhang     if (namedAttr.first != impl::getTypeAttrName() &&
57401178654SLei Zhang         namedAttr.first != SymbolTable::getSymbolAttrName())
57501178654SLei Zhang       newFuncOp->setAttr(namedAttr.first, namedAttr.second);
57601178654SLei Zhang   }
57701178654SLei Zhang 
57801178654SLei Zhang   rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(),
57901178654SLei Zhang                               newFuncOp.end());
5807c3ae48fSLei Zhang   if (failed(rewriter.convertRegionTypes(
5817c3ae48fSLei Zhang           &newFuncOp.getBody(), *getTypeConverter(), &signatureConverter)))
58201178654SLei Zhang     return failure();
58301178654SLei Zhang   rewriter.eraseOp(funcOp);
58401178654SLei Zhang   return success();
58501178654SLei Zhang }
58601178654SLei Zhang 
587dc4e913bSChris Lattner void mlir::populateBuiltinFuncToSPIRVPatterns(SPIRVTypeConverter &typeConverter,
588dc4e913bSChris Lattner                                               RewritePatternSet &patterns) {
589dc4e913bSChris Lattner   patterns.add<FuncOpConversion>(typeConverter, patterns.getContext());
59001178654SLei Zhang }
59101178654SLei Zhang 
59201178654SLei Zhang //===----------------------------------------------------------------------===//
59301178654SLei Zhang // Builtin Variables
59401178654SLei Zhang //===----------------------------------------------------------------------===//
59501178654SLei Zhang 
59601178654SLei Zhang static spirv::GlobalVariableOp getBuiltinVariable(Block &body,
59701178654SLei Zhang                                                   spirv::BuiltIn builtin) {
59801178654SLei Zhang   // Look through all global variables in the given `body` block and check if
599c74eb466SKareemErgawy-TomTom   // there is a spv.GlobalVariable that has the same `builtin` attribute.
60001178654SLei Zhang   for (auto varOp : body.getOps<spirv::GlobalVariableOp>()) {
60101178654SLei Zhang     if (auto builtinAttr = varOp->getAttrOfType<StringAttr>(
60201178654SLei Zhang             spirv::SPIRVDialect::getAttributeName(
60301178654SLei Zhang                 spirv::Decoration::BuiltIn))) {
60401178654SLei Zhang       auto varBuiltIn = spirv::symbolizeBuiltIn(builtinAttr.getValue());
60501178654SLei Zhang       if (varBuiltIn && varBuiltIn.getValue() == builtin) {
60601178654SLei Zhang         return varOp;
60701178654SLei Zhang       }
60801178654SLei Zhang     }
60901178654SLei Zhang   }
61001178654SLei Zhang   return nullptr;
61101178654SLei Zhang }
61201178654SLei Zhang 
61301178654SLei Zhang /// Gets name of global variable for a builtin.
61401178654SLei Zhang static std::string getBuiltinVarName(spirv::BuiltIn builtin) {
61501178654SLei Zhang   return std::string("__builtin_var_") + stringifyBuiltIn(builtin).str() + "__";
61601178654SLei Zhang }
61701178654SLei Zhang 
61801178654SLei Zhang /// Gets or inserts a global variable for a builtin within `body` block.
61901178654SLei Zhang static spirv::GlobalVariableOp
62001178654SLei Zhang getOrInsertBuiltinVariable(Block &body, Location loc, spirv::BuiltIn builtin,
62101178654SLei Zhang                            OpBuilder &builder) {
62201178654SLei Zhang   if (auto varOp = getBuiltinVariable(body, builtin))
62301178654SLei Zhang     return varOp;
62401178654SLei Zhang 
62501178654SLei Zhang   OpBuilder::InsertionGuard guard(builder);
62601178654SLei Zhang   builder.setInsertionPointToStart(&body);
62701178654SLei Zhang 
62801178654SLei Zhang   spirv::GlobalVariableOp newVarOp;
62901178654SLei Zhang   switch (builtin) {
63001178654SLei Zhang   case spirv::BuiltIn::NumWorkgroups:
63101178654SLei Zhang   case spirv::BuiltIn::WorkgroupSize:
63201178654SLei Zhang   case spirv::BuiltIn::WorkgroupId:
63301178654SLei Zhang   case spirv::BuiltIn::LocalInvocationId:
63401178654SLei Zhang   case spirv::BuiltIn::GlobalInvocationId: {
63501178654SLei Zhang     auto ptrType = spirv::PointerType::get(
63601178654SLei Zhang         VectorType::get({3}, builder.getIntegerType(32)),
63701178654SLei Zhang         spirv::StorageClass::Input);
63801178654SLei Zhang     std::string name = getBuiltinVarName(builtin);
63901178654SLei Zhang     newVarOp =
64001178654SLei Zhang         builder.create<spirv::GlobalVariableOp>(loc, ptrType, name, builtin);
64101178654SLei Zhang     break;
64201178654SLei Zhang   }
64301178654SLei Zhang   case spirv::BuiltIn::SubgroupId:
64401178654SLei Zhang   case spirv::BuiltIn::NumSubgroups:
64501178654SLei Zhang   case spirv::BuiltIn::SubgroupSize: {
64601178654SLei Zhang     auto ptrType = spirv::PointerType::get(builder.getIntegerType(32),
64701178654SLei Zhang                                            spirv::StorageClass::Input);
64801178654SLei Zhang     std::string name = getBuiltinVarName(builtin);
64901178654SLei Zhang     newVarOp =
65001178654SLei Zhang         builder.create<spirv::GlobalVariableOp>(loc, ptrType, name, builtin);
65101178654SLei Zhang     break;
65201178654SLei Zhang   }
65301178654SLei Zhang   default:
65401178654SLei Zhang     emitError(loc, "unimplemented builtin variable generation for ")
65501178654SLei Zhang         << stringifyBuiltIn(builtin);
65601178654SLei Zhang   }
65701178654SLei Zhang   return newVarOp;
65801178654SLei Zhang }
65901178654SLei Zhang 
66001178654SLei Zhang Value mlir::spirv::getBuiltinVariableValue(Operation *op,
66101178654SLei Zhang                                            spirv::BuiltIn builtin,
66201178654SLei Zhang                                            OpBuilder &builder) {
66301178654SLei Zhang   Operation *parent = SymbolTable::getNearestSymbolTable(op->getParentOp());
66401178654SLei Zhang   if (!parent) {
66501178654SLei Zhang     op->emitError("expected operation to be within a module-like op");
66601178654SLei Zhang     return nullptr;
66701178654SLei Zhang   }
66801178654SLei Zhang 
66901178654SLei Zhang   spirv::GlobalVariableOp varOp = getOrInsertBuiltinVariable(
67001178654SLei Zhang       *parent->getRegion(0).begin(), op->getLoc(), builtin, builder);
67101178654SLei Zhang   Value ptr = builder.create<spirv::AddressOfOp>(op->getLoc(), varOp);
67201178654SLei Zhang   return builder.create<spirv::LoadOp>(op->getLoc(), ptr);
67301178654SLei Zhang }
67401178654SLei Zhang 
67501178654SLei Zhang //===----------------------------------------------------------------------===//
6766dd07fa5SLei Zhang // Push constant storage
6776dd07fa5SLei Zhang //===----------------------------------------------------------------------===//
6786dd07fa5SLei Zhang 
6796dd07fa5SLei Zhang /// Returns the pointer type for the push constant storage containing
6806dd07fa5SLei Zhang /// `elementCount` 32-bit integer values.
6816dd07fa5SLei Zhang static spirv::PointerType getPushConstantStorageType(unsigned elementCount,
6826dd07fa5SLei Zhang                                                      Builder &builder) {
6836dd07fa5SLei Zhang   auto arrayType = spirv::ArrayType::get(
6846dd07fa5SLei Zhang       SPIRVTypeConverter::getIndexType(builder.getContext()), elementCount,
6856dd07fa5SLei Zhang       /*stride=*/4);
6866dd07fa5SLei Zhang   auto structType = spirv::StructType::get({arrayType}, /*offsetInfo=*/0);
6876dd07fa5SLei Zhang   return spirv::PointerType::get(structType, spirv::StorageClass::PushConstant);
6886dd07fa5SLei Zhang }
6896dd07fa5SLei Zhang 
6906dd07fa5SLei Zhang /// Returns the push constant varible containing `elementCount` 32-bit integer
6916dd07fa5SLei Zhang /// values in `body`. Returns null op if such an op does not exit.
6926dd07fa5SLei Zhang static spirv::GlobalVariableOp getPushConstantVariable(Block &body,
6936dd07fa5SLei Zhang                                                        unsigned elementCount) {
6946dd07fa5SLei Zhang   for (auto varOp : body.getOps<spirv::GlobalVariableOp>()) {
6956dd07fa5SLei Zhang     auto ptrType = varOp.type().cast<spirv::PointerType>();
6966dd07fa5SLei Zhang     // Note that Vulkan requires "There must be no more than one push constant
6976dd07fa5SLei Zhang     // block statically used per shader entry point." So we should always reuse
6986dd07fa5SLei Zhang     // the existing one.
6996dd07fa5SLei Zhang     if (ptrType.getStorageClass() == spirv::StorageClass::PushConstant) {
7006dd07fa5SLei Zhang       auto numElements = ptrType.getPointeeType()
7016dd07fa5SLei Zhang                              .cast<spirv::StructType>()
7026dd07fa5SLei Zhang                              .getElementType(0)
7036dd07fa5SLei Zhang                              .cast<spirv::ArrayType>()
7046dd07fa5SLei Zhang                              .getNumElements();
7056dd07fa5SLei Zhang       if (numElements == elementCount)
7066dd07fa5SLei Zhang         return varOp;
7076dd07fa5SLei Zhang     }
7086dd07fa5SLei Zhang   }
7096dd07fa5SLei Zhang   return nullptr;
7106dd07fa5SLei Zhang }
7116dd07fa5SLei Zhang 
7126dd07fa5SLei Zhang /// Gets or inserts a global variable for push constant storage containing
7136dd07fa5SLei Zhang /// `elementCount` 32-bit integer values in `block`.
7146dd07fa5SLei Zhang static spirv::GlobalVariableOp
7156dd07fa5SLei Zhang getOrInsertPushConstantVariable(Location loc, Block &block,
7166dd07fa5SLei Zhang                                 unsigned elementCount, OpBuilder &b) {
7176dd07fa5SLei Zhang   if (auto varOp = getPushConstantVariable(block, elementCount))
7186dd07fa5SLei Zhang     return varOp;
7196dd07fa5SLei Zhang 
7206dd07fa5SLei Zhang   auto builder = OpBuilder::atBlockBegin(&block, b.getListener());
7216dd07fa5SLei Zhang   auto type = getPushConstantStorageType(elementCount, builder);
7226dd07fa5SLei Zhang   const char *name = "__push_constant_var__";
7236dd07fa5SLei Zhang   return builder.create<spirv::GlobalVariableOp>(loc, type, name,
7246dd07fa5SLei Zhang                                                  /*initializer=*/nullptr);
7256dd07fa5SLei Zhang }
7266dd07fa5SLei Zhang 
7276dd07fa5SLei Zhang Value spirv::getPushConstantValue(Operation *op, unsigned elementCount,
7286dd07fa5SLei Zhang                                   unsigned offset, OpBuilder &builder) {
7296dd07fa5SLei Zhang   Location loc = op->getLoc();
7306dd07fa5SLei Zhang   Operation *parent = SymbolTable::getNearestSymbolTable(op->getParentOp());
7316dd07fa5SLei Zhang   if (!parent) {
7326dd07fa5SLei Zhang     op->emitError("expected operation to be within a module-like op");
7336dd07fa5SLei Zhang     return nullptr;
7346dd07fa5SLei Zhang   }
7356dd07fa5SLei Zhang 
7366dd07fa5SLei Zhang   spirv::GlobalVariableOp varOp = getOrInsertPushConstantVariable(
7376dd07fa5SLei Zhang       loc, parent->getRegion(0).front(), elementCount, builder);
7386dd07fa5SLei Zhang 
7396dd07fa5SLei Zhang   auto i32Type = SPIRVTypeConverter::getIndexType(builder.getContext());
7406dd07fa5SLei Zhang   Value zeroOp = spirv::ConstantOp::getZero(i32Type, loc, builder);
7416dd07fa5SLei Zhang   Value offsetOp = builder.create<spirv::ConstantOp>(
7426dd07fa5SLei Zhang       loc, i32Type, builder.getI32IntegerAttr(offset));
7436dd07fa5SLei Zhang   auto addrOp = builder.create<spirv::AddressOfOp>(loc, varOp);
7446dd07fa5SLei Zhang   auto acOp = builder.create<spirv::AccessChainOp>(
7456dd07fa5SLei Zhang       loc, addrOp, llvm::makeArrayRef({zeroOp, offsetOp}));
7466dd07fa5SLei Zhang   return builder.create<spirv::LoadOp>(loc, acOp);
7476dd07fa5SLei Zhang }
7486dd07fa5SLei Zhang 
7496dd07fa5SLei Zhang //===----------------------------------------------------------------------===//
75001178654SLei Zhang // Index calculation
75101178654SLei Zhang //===----------------------------------------------------------------------===//
75201178654SLei Zhang 
753bb6f5c83SLei Zhang Value mlir::spirv::linearizeIndex(ValueRange indices, ArrayRef<int64_t> strides,
754bb6f5c83SLei Zhang                                   int64_t offset, Location loc,
755bb6f5c83SLei Zhang                                   OpBuilder &builder) {
756bb6f5c83SLei Zhang   assert(indices.size() == strides.size() &&
757bb6f5c83SLei Zhang          "must provide indices for all dimensions");
758bb6f5c83SLei Zhang 
759bb6f5c83SLei Zhang   auto indexType = SPIRVTypeConverter::getIndexType(builder.getContext());
760bb6f5c83SLei Zhang 
761bb6f5c83SLei Zhang   // TODO: Consider moving to use affine.apply and patterns converting
762bb6f5c83SLei Zhang   // affine.apply to standard ops. This needs converting to SPIR-V passes to be
763bb6f5c83SLei Zhang   // broken down into progressive small steps so we can have intermediate steps
764bb6f5c83SLei Zhang   // using other dialects. At the moment SPIR-V is the final sink.
765bb6f5c83SLei Zhang 
766bb6f5c83SLei Zhang   Value linearizedIndex = builder.create<spirv::ConstantOp>(
767bb6f5c83SLei Zhang       loc, indexType, IntegerAttr::get(indexType, offset));
768bb6f5c83SLei Zhang   for (auto index : llvm::enumerate(indices)) {
769bb6f5c83SLei Zhang     Value strideVal = builder.create<spirv::ConstantOp>(
770bb6f5c83SLei Zhang         loc, indexType, IntegerAttr::get(indexType, strides[index.index()]));
771bb6f5c83SLei Zhang     Value update = builder.create<spirv::IMulOp>(loc, strideVal, index.value());
772bb6f5c83SLei Zhang     linearizedIndex =
773bb6f5c83SLei Zhang         builder.create<spirv::IAddOp>(loc, linearizedIndex, update);
774bb6f5c83SLei Zhang   }
775bb6f5c83SLei Zhang   return linearizedIndex;
776bb6f5c83SLei Zhang }
777bb6f5c83SLei Zhang 
77801178654SLei Zhang spirv::AccessChainOp mlir::spirv::getElementPtr(
77901178654SLei Zhang     SPIRVTypeConverter &typeConverter, MemRefType baseType, Value basePtr,
78001178654SLei Zhang     ValueRange indices, Location loc, OpBuilder &builder) {
78101178654SLei Zhang   // Get base and offset of the MemRefType and verify they are static.
78201178654SLei Zhang 
78301178654SLei Zhang   int64_t offset;
78401178654SLei Zhang   SmallVector<int64_t, 4> strides;
78501178654SLei Zhang   if (failed(getStridesAndOffset(baseType, strides, offset)) ||
78601178654SLei Zhang       llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset()) ||
78701178654SLei Zhang       offset == MemRefType::getDynamicStrideOrOffset()) {
78801178654SLei Zhang     return nullptr;
78901178654SLei Zhang   }
79001178654SLei Zhang 
79101178654SLei Zhang   auto indexType = typeConverter.getIndexType(builder.getContext());
79201178654SLei Zhang 
79301178654SLei Zhang   SmallVector<Value, 2> linearizedIndices;
79401178654SLei Zhang   auto zero = spirv::ConstantOp::getZero(indexType, loc, builder);
795bb6f5c83SLei Zhang 
796bb6f5c83SLei Zhang   // Add a '0' at the start to index into the struct.
79701178654SLei Zhang   linearizedIndices.push_back(zero);
79801178654SLei Zhang 
79901178654SLei Zhang   if (baseType.getRank() == 0) {
80001178654SLei Zhang     linearizedIndices.push_back(zero);
80101178654SLei Zhang   } else {
802bb6f5c83SLei Zhang     linearizedIndices.push_back(
803bb6f5c83SLei Zhang         linearizeIndex(indices, strides, offset, loc, builder));
80401178654SLei Zhang   }
80501178654SLei Zhang   return builder.create<spirv::AccessChainOp>(loc, basePtr, linearizedIndices);
80601178654SLei Zhang }
80701178654SLei Zhang 
80801178654SLei Zhang //===----------------------------------------------------------------------===//
80901178654SLei Zhang // SPIR-V ConversionTarget
81001178654SLei Zhang //===----------------------------------------------------------------------===//
81101178654SLei Zhang 
8126dd07fa5SLei Zhang std::unique_ptr<SPIRVConversionTarget>
8136dd07fa5SLei Zhang SPIRVConversionTarget::get(spirv::TargetEnvAttr targetAttr) {
81401178654SLei Zhang   std::unique_ptr<SPIRVConversionTarget> target(
81501178654SLei Zhang       // std::make_unique does not work here because the constructor is private.
81601178654SLei Zhang       new SPIRVConversionTarget(targetAttr));
81701178654SLei Zhang   SPIRVConversionTarget *targetPtr = target.get();
8186dd07fa5SLei Zhang   target->addDynamicallyLegalDialect<spirv::SPIRVDialect>(
81901178654SLei Zhang       // We need to capture the raw pointer here because it is stable:
82001178654SLei Zhang       // target will be destroyed once this function is returned.
82101178654SLei Zhang       [targetPtr](Operation *op) { return targetPtr->isLegalOp(op); });
82201178654SLei Zhang   return target;
82301178654SLei Zhang }
82401178654SLei Zhang 
8256dd07fa5SLei Zhang SPIRVConversionTarget::SPIRVConversionTarget(spirv::TargetEnvAttr targetAttr)
82601178654SLei Zhang     : ConversionTarget(*targetAttr.getContext()), targetEnv(targetAttr) {}
82701178654SLei Zhang 
8286dd07fa5SLei Zhang bool SPIRVConversionTarget::isLegalOp(Operation *op) {
82901178654SLei Zhang   // Make sure this op is available at the given version. Ops not implementing
83001178654SLei Zhang   // QueryMinVersionInterface/QueryMaxVersionInterface are available to all
83101178654SLei Zhang   // SPIR-V versions.
83201178654SLei Zhang   if (auto minVersion = dyn_cast<spirv::QueryMinVersionInterface>(op))
83301178654SLei Zhang     if (minVersion.getMinVersion() > this->targetEnv.getVersion()) {
83401178654SLei Zhang       LLVM_DEBUG(llvm::dbgs()
83501178654SLei Zhang                  << op->getName() << " illegal: requiring min version "
83601178654SLei Zhang                  << spirv::stringifyVersion(minVersion.getMinVersion())
83701178654SLei Zhang                  << "\n");
83801178654SLei Zhang       return false;
83901178654SLei Zhang     }
84001178654SLei Zhang   if (auto maxVersion = dyn_cast<spirv::QueryMaxVersionInterface>(op))
84101178654SLei Zhang     if (maxVersion.getMaxVersion() < this->targetEnv.getVersion()) {
84201178654SLei Zhang       LLVM_DEBUG(llvm::dbgs()
84301178654SLei Zhang                  << op->getName() << " illegal: requiring max version "
84401178654SLei Zhang                  << spirv::stringifyVersion(maxVersion.getMaxVersion())
84501178654SLei Zhang                  << "\n");
84601178654SLei Zhang       return false;
84701178654SLei Zhang     }
84801178654SLei Zhang 
84901178654SLei Zhang   // Make sure this op's required extensions are allowed to use. Ops not
85001178654SLei Zhang   // implementing QueryExtensionInterface do not require extensions to be
85101178654SLei Zhang   // available.
85201178654SLei Zhang   if (auto extensions = dyn_cast<spirv::QueryExtensionInterface>(op))
85301178654SLei Zhang     if (failed(checkExtensionRequirements(op->getName(), this->targetEnv,
85401178654SLei Zhang                                           extensions.getExtensions())))
85501178654SLei Zhang       return false;
85601178654SLei Zhang 
85701178654SLei Zhang   // Make sure this op's required extensions are allowed to use. Ops not
85801178654SLei Zhang   // implementing QueryCapabilityInterface do not require capabilities to be
85901178654SLei Zhang   // available.
86001178654SLei Zhang   if (auto capabilities = dyn_cast<spirv::QueryCapabilityInterface>(op))
86101178654SLei Zhang     if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv,
86201178654SLei Zhang                                            capabilities.getCapabilities())))
86301178654SLei Zhang       return false;
86401178654SLei Zhang 
86501178654SLei Zhang   SmallVector<Type, 4> valueTypes;
86601178654SLei Zhang   valueTypes.append(op->operand_type_begin(), op->operand_type_end());
86701178654SLei Zhang   valueTypes.append(op->result_type_begin(), op->result_type_end());
86801178654SLei Zhang 
86901178654SLei Zhang   // Special treatment for global variables, whose type requirements are
87001178654SLei Zhang   // conveyed by type attributes.
87101178654SLei Zhang   if (auto globalVar = dyn_cast<spirv::GlobalVariableOp>(op))
87201178654SLei Zhang     valueTypes.push_back(globalVar.type());
87301178654SLei Zhang 
87401178654SLei Zhang   // Make sure the op's operands/results use types that are allowed by the
87501178654SLei Zhang   // target environment.
87601178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 4> typeExtensions;
87701178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 8> typeCapabilities;
87801178654SLei Zhang   for (Type valueType : valueTypes) {
87901178654SLei Zhang     typeExtensions.clear();
88001178654SLei Zhang     valueType.cast<spirv::SPIRVType>().getExtensions(typeExtensions);
88101178654SLei Zhang     if (failed(checkExtensionRequirements(op->getName(), this->targetEnv,
88201178654SLei Zhang                                           typeExtensions)))
88301178654SLei Zhang       return false;
88401178654SLei Zhang 
88501178654SLei Zhang     typeCapabilities.clear();
88601178654SLei Zhang     valueType.cast<spirv::SPIRVType>().getCapabilities(typeCapabilities);
88701178654SLei Zhang     if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv,
88801178654SLei Zhang                                            typeCapabilities)))
88901178654SLei Zhang       return false;
89001178654SLei Zhang   }
89101178654SLei Zhang 
89201178654SLei Zhang   return true;
89301178654SLei Zhang }
894