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"
1601178654SLei Zhang #include "llvm/ADT/Sequence.h"
1701178654SLei Zhang #include "llvm/ADT/StringExtras.h"
1801178654SLei Zhang #include "llvm/Support/Debug.h"
1901178654SLei Zhang 
2001178654SLei Zhang #include <functional>
2101178654SLei Zhang 
2201178654SLei Zhang #define DEBUG_TYPE "mlir-spirv-conversion"
2301178654SLei Zhang 
2401178654SLei Zhang using namespace mlir;
2501178654SLei Zhang 
2601178654SLei Zhang //===----------------------------------------------------------------------===//
2701178654SLei Zhang // Utility functions
2801178654SLei Zhang //===----------------------------------------------------------------------===//
2901178654SLei Zhang 
3001178654SLei Zhang /// Checks that `candidates` extension requirements are possible to be satisfied
3101178654SLei Zhang /// with the given `targetEnv`.
3201178654SLei Zhang ///
3301178654SLei Zhang ///  `candidates` is a vector of vector for extension requirements following
3401178654SLei Zhang /// ((Extension::A OR Extension::B) AND (Extension::C OR Extension::D))
3501178654SLei Zhang /// convention.
3601178654SLei Zhang template <typename LabelT>
3701178654SLei Zhang static LogicalResult checkExtensionRequirements(
3801178654SLei Zhang     LabelT label, const spirv::TargetEnv &targetEnv,
3901178654SLei Zhang     const spirv::SPIRVType::ExtensionArrayRefVector &candidates) {
4001178654SLei Zhang   for (const auto &ors : candidates) {
4101178654SLei Zhang     if (targetEnv.allows(ors))
4201178654SLei Zhang       continue;
4301178654SLei Zhang 
4401178654SLei Zhang     SmallVector<StringRef, 4> extStrings;
4501178654SLei Zhang     for (spirv::Extension ext : ors)
4601178654SLei Zhang       extStrings.push_back(spirv::stringifyExtension(ext));
4701178654SLei Zhang 
4801178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
4901178654SLei Zhang                << label << " illegal: requires at least one extension in ["
5001178654SLei Zhang                << llvm::join(extStrings, ", ")
5101178654SLei Zhang                << "] but none allowed in target environment\n");
5201178654SLei Zhang     return failure();
5301178654SLei Zhang   }
5401178654SLei Zhang   return success();
5501178654SLei Zhang }
5601178654SLei Zhang 
5701178654SLei Zhang /// Checks that `candidates`capability requirements are possible to be satisfied
5801178654SLei Zhang /// with the given `isAllowedFn`.
5901178654SLei Zhang ///
6001178654SLei Zhang ///  `candidates` is a vector of vector for capability requirements following
6101178654SLei Zhang /// ((Capability::A OR Capability::B) AND (Capability::C OR Capability::D))
6201178654SLei Zhang /// convention.
6301178654SLei Zhang template <typename LabelT>
6401178654SLei Zhang static LogicalResult checkCapabilityRequirements(
6501178654SLei Zhang     LabelT label, const spirv::TargetEnv &targetEnv,
6601178654SLei Zhang     const spirv::SPIRVType::CapabilityArrayRefVector &candidates) {
6701178654SLei Zhang   for (const auto &ors : candidates) {
6801178654SLei Zhang     if (targetEnv.allows(ors))
6901178654SLei Zhang       continue;
7001178654SLei Zhang 
7101178654SLei Zhang     SmallVector<StringRef, 4> capStrings;
7201178654SLei Zhang     for (spirv::Capability cap : ors)
7301178654SLei Zhang       capStrings.push_back(spirv::stringifyCapability(cap));
7401178654SLei Zhang 
7501178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
7601178654SLei Zhang                << label << " illegal: requires at least one capability in ["
7701178654SLei Zhang                << llvm::join(capStrings, ", ")
7801178654SLei Zhang                << "] but none allowed in target environment\n");
7901178654SLei Zhang     return failure();
8001178654SLei Zhang   }
8101178654SLei Zhang   return success();
8201178654SLei Zhang }
8301178654SLei Zhang 
8401178654SLei Zhang //===----------------------------------------------------------------------===//
8501178654SLei Zhang // Type Conversion
8601178654SLei Zhang //===----------------------------------------------------------------------===//
8701178654SLei Zhang 
8801178654SLei Zhang Type SPIRVTypeConverter::getIndexType(MLIRContext *context) {
8901178654SLei Zhang   // Convert to 32-bit integers for now. Might need a way to control this in
9001178654SLei Zhang   // future.
9101178654SLei Zhang   // TODO: It is probably better to make it 64-bit integers. To
9201178654SLei Zhang   // this some support is needed in SPIR-V dialect for Conversion
9301178654SLei Zhang   // instructions. The Vulkan spec requires the builtins like
9401178654SLei Zhang   // GlobalInvocationID, etc. to be 32-bit (unsigned) integers which should be
9501178654SLei Zhang   // SExtended to 64-bit for index computations.
96*1b97cdf8SRiver Riddle   return IntegerType::get(context, 32);
9701178654SLei Zhang }
9801178654SLei Zhang 
9901178654SLei Zhang /// Mapping between SPIR-V storage classes to memref memory spaces.
10001178654SLei Zhang ///
10101178654SLei Zhang /// Note: memref does not have a defined semantics for each memory space; it
10201178654SLei Zhang /// depends on the context where it is used. There are no particular reasons
10301178654SLei Zhang /// behind the number assignments; we try to follow NVVM conventions and largely
10401178654SLei Zhang /// give common storage classes a smaller number. The hope is use symbolic
10501178654SLei Zhang /// memory space representation eventually after memref supports it.
10601178654SLei Zhang // TODO: swap Generic and StorageBuffer assignment to be more akin
10701178654SLei Zhang // to NVVM.
10801178654SLei Zhang #define STORAGE_SPACE_MAP_LIST(MAP_FN)                                         \
10901178654SLei Zhang   MAP_FN(spirv::StorageClass::Generic, 1)                                      \
11001178654SLei Zhang   MAP_FN(spirv::StorageClass::StorageBuffer, 0)                                \
11101178654SLei Zhang   MAP_FN(spirv::StorageClass::Workgroup, 3)                                    \
11201178654SLei Zhang   MAP_FN(spirv::StorageClass::Uniform, 4)                                      \
11301178654SLei Zhang   MAP_FN(spirv::StorageClass::Private, 5)                                      \
11401178654SLei Zhang   MAP_FN(spirv::StorageClass::Function, 6)                                     \
11501178654SLei Zhang   MAP_FN(spirv::StorageClass::PushConstant, 7)                                 \
11601178654SLei Zhang   MAP_FN(spirv::StorageClass::UniformConstant, 8)                              \
11701178654SLei Zhang   MAP_FN(spirv::StorageClass::Input, 9)                                        \
11801178654SLei Zhang   MAP_FN(spirv::StorageClass::Output, 10)                                      \
11901178654SLei Zhang   MAP_FN(spirv::StorageClass::CrossWorkgroup, 11)                              \
12001178654SLei Zhang   MAP_FN(spirv::StorageClass::AtomicCounter, 12)                               \
12101178654SLei Zhang   MAP_FN(spirv::StorageClass::Image, 13)                                       \
12201178654SLei Zhang   MAP_FN(spirv::StorageClass::CallableDataNV, 14)                              \
12301178654SLei Zhang   MAP_FN(spirv::StorageClass::IncomingCallableDataNV, 15)                      \
12401178654SLei Zhang   MAP_FN(spirv::StorageClass::RayPayloadNV, 16)                                \
12501178654SLei Zhang   MAP_FN(spirv::StorageClass::HitAttributeNV, 17)                              \
12601178654SLei Zhang   MAP_FN(spirv::StorageClass::IncomingRayPayloadNV, 18)                        \
12701178654SLei Zhang   MAP_FN(spirv::StorageClass::ShaderRecordBufferNV, 19)                        \
12801178654SLei Zhang   MAP_FN(spirv::StorageClass::PhysicalStorageBuffer, 20)
12901178654SLei Zhang 
13001178654SLei Zhang unsigned
13101178654SLei Zhang SPIRVTypeConverter::getMemorySpaceForStorageClass(spirv::StorageClass storage) {
13201178654SLei Zhang #define STORAGE_SPACE_MAP_FN(storage, space)                                   \
13301178654SLei Zhang   case storage:                                                                \
13401178654SLei Zhang     return space;
13501178654SLei Zhang 
13601178654SLei Zhang   switch (storage) { STORAGE_SPACE_MAP_LIST(STORAGE_SPACE_MAP_FN) }
13701178654SLei Zhang #undef STORAGE_SPACE_MAP_FN
13801178654SLei Zhang   llvm_unreachable("unhandled storage class!");
13901178654SLei Zhang }
14001178654SLei Zhang 
14101178654SLei Zhang Optional<spirv::StorageClass>
14201178654SLei Zhang SPIRVTypeConverter::getStorageClassForMemorySpace(unsigned space) {
14301178654SLei Zhang #define STORAGE_SPACE_MAP_FN(storage, space)                                   \
14401178654SLei Zhang   case space:                                                                  \
14501178654SLei Zhang     return storage;
14601178654SLei Zhang 
14701178654SLei Zhang   switch (space) {
14801178654SLei Zhang     STORAGE_SPACE_MAP_LIST(STORAGE_SPACE_MAP_FN)
14901178654SLei Zhang   default:
15001178654SLei Zhang     return llvm::None;
15101178654SLei Zhang   }
15201178654SLei Zhang #undef STORAGE_SPACE_MAP_FN
15301178654SLei Zhang }
15401178654SLei Zhang 
15501178654SLei Zhang #undef STORAGE_SPACE_MAP_LIST
15601178654SLei Zhang 
15701178654SLei Zhang // TODO: This is a utility function that should probably be
15801178654SLei Zhang // exposed by the SPIR-V dialect. Keeping it local till the use case arises.
15901178654SLei Zhang static Optional<int64_t> getTypeNumBytes(Type t) {
16001178654SLei Zhang   if (t.isa<spirv::ScalarType>()) {
16101178654SLei Zhang     auto bitWidth = t.getIntOrFloatBitWidth();
16201178654SLei Zhang     // According to the SPIR-V spec:
16301178654SLei Zhang     // "There is no physical size or bit pattern defined for values with boolean
16401178654SLei Zhang     // type. If they are stored (in conjunction with OpVariable), they can only
16501178654SLei Zhang     // be used with logical addressing operations, not physical, and only with
16601178654SLei Zhang     // non-externally visible shader Storage Classes: Workgroup, CrossWorkgroup,
16701178654SLei Zhang     // Private, Function, Input, and Output."
16801178654SLei Zhang     if (bitWidth == 1) {
16901178654SLei Zhang       return llvm::None;
17001178654SLei Zhang     }
17101178654SLei Zhang     return bitWidth / 8;
17201178654SLei Zhang   }
17301178654SLei Zhang   if (auto vecType = t.dyn_cast<VectorType>()) {
17401178654SLei Zhang     auto elementSize = getTypeNumBytes(vecType.getElementType());
17501178654SLei Zhang     if (!elementSize)
17601178654SLei Zhang       return llvm::None;
17701178654SLei Zhang     return vecType.getNumElements() * *elementSize;
17801178654SLei Zhang   }
17901178654SLei Zhang   if (auto memRefType = t.dyn_cast<MemRefType>()) {
18001178654SLei Zhang     // TODO: Layout should also be controlled by the ABI attributes. For now
18101178654SLei Zhang     // using the layout from MemRef.
18201178654SLei Zhang     int64_t offset;
18301178654SLei Zhang     SmallVector<int64_t, 4> strides;
18401178654SLei Zhang     if (!memRefType.hasStaticShape() ||
18501178654SLei Zhang         failed(getStridesAndOffset(memRefType, strides, offset))) {
18601178654SLei Zhang       return llvm::None;
18701178654SLei Zhang     }
18801178654SLei Zhang     // To get the size of the memref object in memory, the total size is the
18901178654SLei Zhang     // max(stride * dimension-size) computed for all dimensions times the size
19001178654SLei Zhang     // of the element.
19101178654SLei Zhang     auto elementSize = getTypeNumBytes(memRefType.getElementType());
19201178654SLei Zhang     if (!elementSize) {
19301178654SLei Zhang       return llvm::None;
19401178654SLei Zhang     }
19501178654SLei Zhang     if (memRefType.getRank() == 0) {
19601178654SLei Zhang       return elementSize;
19701178654SLei Zhang     }
19801178654SLei Zhang     auto dims = memRefType.getShape();
19901178654SLei Zhang     if (llvm::is_contained(dims, ShapedType::kDynamicSize) ||
20001178654SLei Zhang         offset == MemRefType::getDynamicStrideOrOffset() ||
20101178654SLei Zhang         llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset())) {
20201178654SLei Zhang       return llvm::None;
20301178654SLei Zhang     }
20401178654SLei Zhang     int64_t memrefSize = -1;
20501178654SLei Zhang     for (auto shape : enumerate(dims)) {
20601178654SLei Zhang       memrefSize = std::max(memrefSize, shape.value() * strides[shape.index()]);
20701178654SLei Zhang     }
20801178654SLei Zhang     return (offset + memrefSize) * elementSize.getValue();
20901178654SLei Zhang   } else if (auto tensorType = t.dyn_cast<TensorType>()) {
21001178654SLei Zhang     if (!tensorType.hasStaticShape()) {
21101178654SLei Zhang       return llvm::None;
21201178654SLei Zhang     }
21301178654SLei Zhang     auto elementSize = getTypeNumBytes(tensorType.getElementType());
21401178654SLei Zhang     if (!elementSize) {
21501178654SLei Zhang       return llvm::None;
21601178654SLei Zhang     }
21701178654SLei Zhang     int64_t size = elementSize.getValue();
21801178654SLei Zhang     for (auto shape : tensorType.getShape()) {
21901178654SLei Zhang       size *= shape;
22001178654SLei Zhang     }
22101178654SLei Zhang     return size;
22201178654SLei Zhang   }
22301178654SLei Zhang   // TODO: Add size computation for other types.
22401178654SLei Zhang   return llvm::None;
22501178654SLei Zhang }
22601178654SLei Zhang 
22701178654SLei Zhang Optional<int64_t> SPIRVTypeConverter::getConvertedTypeNumBytes(Type t) {
22801178654SLei Zhang   return getTypeNumBytes(t);
22901178654SLei Zhang }
23001178654SLei Zhang 
23101178654SLei Zhang /// Converts a scalar `type` to a suitable type under the given `targetEnv`.
23201178654SLei Zhang static Optional<Type>
23301178654SLei Zhang convertScalarType(const spirv::TargetEnv &targetEnv, spirv::ScalarType type,
23401178654SLei Zhang                   Optional<spirv::StorageClass> storageClass = {}) {
23501178654SLei Zhang   // Get extension and capability requirements for the given type.
23601178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 1> extensions;
23701178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 2> capabilities;
23801178654SLei Zhang   type.getExtensions(extensions, storageClass);
23901178654SLei Zhang   type.getCapabilities(capabilities, storageClass);
24001178654SLei Zhang 
24101178654SLei Zhang   // If all requirements are met, then we can accept this type as-is.
24201178654SLei Zhang   if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) &&
24301178654SLei Zhang       succeeded(checkExtensionRequirements(type, targetEnv, extensions)))
24401178654SLei Zhang     return type;
24501178654SLei Zhang 
24601178654SLei Zhang   // Otherwise we need to adjust the type, which really means adjusting the
24701178654SLei Zhang   // bitwidth given this is a scalar type.
24801178654SLei Zhang   // TODO: We are unconditionally converting the bitwidth here,
24901178654SLei Zhang   // this might be okay for non-interface types (i.e., types used in
25001178654SLei Zhang   // Private/Function storage classes), but not for interface types (i.e.,
25101178654SLei Zhang   // types used in StorageBuffer/Uniform/PushConstant/etc. storage classes).
25201178654SLei Zhang   // This is because the later actually affects the ABI contract with the
25301178654SLei Zhang   // runtime. So we may want to expose a control on SPIRVTypeConverter to fail
25401178654SLei Zhang   // conversion if we cannot change there.
25501178654SLei Zhang 
25601178654SLei Zhang   if (auto floatType = type.dyn_cast<FloatType>()) {
25701178654SLei Zhang     LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n");
25801178654SLei Zhang     return Builder(targetEnv.getContext()).getF32Type();
25901178654SLei Zhang   }
26001178654SLei Zhang 
26101178654SLei Zhang   auto intType = type.cast<IntegerType>();
26201178654SLei Zhang   LLVM_DEBUG(llvm::dbgs() << type << " converted to 32-bit for SPIR-V\n");
263*1b97cdf8SRiver Riddle   return IntegerType::get(targetEnv.getContext(), /*width=*/32,
264*1b97cdf8SRiver Riddle                           intType.getSignedness());
26501178654SLei Zhang }
26601178654SLei Zhang 
26701178654SLei Zhang /// Converts a vector `type` to a suitable type under the given `targetEnv`.
26801178654SLei Zhang static Optional<Type>
26901178654SLei Zhang convertVectorType(const spirv::TargetEnv &targetEnv, VectorType type,
27001178654SLei Zhang                   Optional<spirv::StorageClass> storageClass = {}) {
27101178654SLei Zhang   if (!spirv::CompositeType::isValid(type)) {
27201178654SLei Zhang     // TODO: One-element vector types can be translated into scalar
27301178654SLei Zhang     // types. Vector types with more than four elements can be translated into
27401178654SLei Zhang     // array types.
27501178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
27601178654SLei Zhang                << type << " illegal: 1- and > 4-element unimplemented\n");
27701178654SLei Zhang     return llvm::None;
27801178654SLei Zhang   }
27901178654SLei Zhang 
28001178654SLei Zhang   // Get extension and capability requirements for the given type.
28101178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 1> extensions;
28201178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 2> capabilities;
28301178654SLei Zhang   type.cast<spirv::CompositeType>().getExtensions(extensions, storageClass);
28401178654SLei Zhang   type.cast<spirv::CompositeType>().getCapabilities(capabilities, storageClass);
28501178654SLei Zhang 
28601178654SLei Zhang   // If all requirements are met, then we can accept this type as-is.
28701178654SLei Zhang   if (succeeded(checkCapabilityRequirements(type, targetEnv, capabilities)) &&
28801178654SLei Zhang       succeeded(checkExtensionRequirements(type, targetEnv, extensions)))
28901178654SLei Zhang     return type;
29001178654SLei Zhang 
29101178654SLei Zhang   auto elementType = convertScalarType(
29201178654SLei Zhang       targetEnv, type.getElementType().cast<spirv::ScalarType>(), storageClass);
29301178654SLei Zhang   if (elementType)
29401178654SLei Zhang     return VectorType::get(type.getShape(), *elementType);
29501178654SLei Zhang   return llvm::None;
29601178654SLei Zhang }
29701178654SLei Zhang 
29801178654SLei Zhang /// Converts a tensor `type` to a suitable type under the given `targetEnv`.
29901178654SLei Zhang ///
30001178654SLei Zhang /// Note that this is mainly for lowering constant tensors.In SPIR-V one can
30101178654SLei Zhang /// create composite constants with OpConstantComposite to embed relative large
30201178654SLei Zhang /// constant values and use OpCompositeExtract and OpCompositeInsert to
30301178654SLei Zhang /// manipulate, like what we do for vectors.
30401178654SLei Zhang static Optional<Type> convertTensorType(const spirv::TargetEnv &targetEnv,
30501178654SLei Zhang                                         TensorType type) {
30601178654SLei Zhang   // TODO: Handle dynamic shapes.
30701178654SLei Zhang   if (!type.hasStaticShape()) {
30801178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
30901178654SLei Zhang                << type << " illegal: dynamic shape unimplemented\n");
31001178654SLei Zhang     return llvm::None;
31101178654SLei Zhang   }
31201178654SLei Zhang 
31301178654SLei Zhang   auto scalarType = type.getElementType().dyn_cast<spirv::ScalarType>();
31401178654SLei Zhang   if (!scalarType) {
31501178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
31601178654SLei Zhang                << type << " illegal: cannot convert non-scalar element type\n");
31701178654SLei Zhang     return llvm::None;
31801178654SLei Zhang   }
31901178654SLei Zhang 
32001178654SLei Zhang   Optional<int64_t> scalarSize = getTypeNumBytes(scalarType);
32101178654SLei Zhang   Optional<int64_t> tensorSize = getTypeNumBytes(type);
32201178654SLei Zhang   if (!scalarSize || !tensorSize) {
32301178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
32401178654SLei Zhang                << type << " illegal: cannot deduce element count\n");
32501178654SLei Zhang     return llvm::None;
32601178654SLei Zhang   }
32701178654SLei Zhang 
32801178654SLei Zhang   auto arrayElemCount = *tensorSize / *scalarSize;
32901178654SLei Zhang   auto arrayElemType = convertScalarType(targetEnv, scalarType);
33001178654SLei Zhang   if (!arrayElemType)
33101178654SLei Zhang     return llvm::None;
33201178654SLei Zhang   Optional<int64_t> arrayElemSize = getTypeNumBytes(*arrayElemType);
33301178654SLei Zhang   if (!arrayElemSize) {
33401178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
33501178654SLei Zhang                << type << " illegal: cannot deduce converted element size\n");
33601178654SLei Zhang     return llvm::None;
33701178654SLei Zhang   }
33801178654SLei Zhang 
33901178654SLei Zhang   return spirv::ArrayType::get(*arrayElemType, arrayElemCount, *arrayElemSize);
34001178654SLei Zhang }
34101178654SLei Zhang 
34201178654SLei Zhang static Optional<Type> convertMemrefType(const spirv::TargetEnv &targetEnv,
34301178654SLei Zhang                                         MemRefType type) {
34401178654SLei Zhang   Optional<spirv::StorageClass> storageClass =
34501178654SLei Zhang       SPIRVTypeConverter::getStorageClassForMemorySpace(type.getMemorySpace());
34601178654SLei Zhang   if (!storageClass) {
34701178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
34801178654SLei Zhang                << type << " illegal: cannot convert memory space\n");
34901178654SLei Zhang     return llvm::None;
35001178654SLei Zhang   }
35101178654SLei Zhang 
35201178654SLei Zhang   Optional<Type> arrayElemType;
35301178654SLei Zhang   Type elementType = type.getElementType();
35401178654SLei Zhang   if (auto vecType = elementType.dyn_cast<VectorType>()) {
35501178654SLei Zhang     arrayElemType = convertVectorType(targetEnv, vecType, storageClass);
35601178654SLei Zhang   } else if (auto scalarType = elementType.dyn_cast<spirv::ScalarType>()) {
35701178654SLei Zhang     arrayElemType = convertScalarType(targetEnv, scalarType, storageClass);
35801178654SLei Zhang   } else {
35901178654SLei Zhang     LLVM_DEBUG(
36001178654SLei Zhang         llvm::dbgs()
36101178654SLei Zhang         << type
36201178654SLei Zhang         << " unhandled: can only convert scalar or vector element type\n");
36301178654SLei Zhang     return llvm::None;
36401178654SLei Zhang   }
36501178654SLei Zhang   if (!arrayElemType)
36601178654SLei Zhang     return llvm::None;
36701178654SLei Zhang 
36801178654SLei Zhang   Optional<int64_t> elementSize = getTypeNumBytes(elementType);
36901178654SLei Zhang   if (!elementSize) {
37001178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
37101178654SLei Zhang                << type << " illegal: cannot deduce element size\n");
37201178654SLei Zhang     return llvm::None;
37301178654SLei Zhang   }
37401178654SLei Zhang 
37501178654SLei Zhang   if (!type.hasStaticShape()) {
37601178654SLei Zhang     auto arrayType = spirv::RuntimeArrayType::get(*arrayElemType, *elementSize);
37701178654SLei Zhang     // Wrap in a struct to satisfy Vulkan interface requirements.
37801178654SLei Zhang     auto structType = spirv::StructType::get(arrayType, 0);
37901178654SLei Zhang     return spirv::PointerType::get(structType, *storageClass);
38001178654SLei Zhang   }
38101178654SLei Zhang 
38201178654SLei Zhang   Optional<int64_t> memrefSize = getTypeNumBytes(type);
38301178654SLei Zhang   if (!memrefSize) {
38401178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
38501178654SLei Zhang                << type << " illegal: cannot deduce element count\n");
38601178654SLei Zhang     return llvm::None;
38701178654SLei Zhang   }
38801178654SLei Zhang 
38901178654SLei Zhang   auto arrayElemCount = *memrefSize / *elementSize;
39001178654SLei Zhang 
39101178654SLei Zhang   Optional<int64_t> arrayElemSize = getTypeNumBytes(*arrayElemType);
39201178654SLei Zhang   if (!arrayElemSize) {
39301178654SLei Zhang     LLVM_DEBUG(llvm::dbgs()
39401178654SLei Zhang                << type << " illegal: cannot deduce converted element size\n");
39501178654SLei Zhang     return llvm::None;
39601178654SLei Zhang   }
39701178654SLei Zhang 
39801178654SLei Zhang   auto arrayType =
39901178654SLei Zhang       spirv::ArrayType::get(*arrayElemType, arrayElemCount, *arrayElemSize);
40001178654SLei Zhang 
40101178654SLei Zhang   // Wrap in a struct to satisfy Vulkan interface requirements. Memrefs with
40201178654SLei Zhang   // workgroup storage class do not need the struct to be laid out explicitly.
40301178654SLei Zhang   auto structType = *storageClass == spirv::StorageClass::Workgroup
40401178654SLei Zhang                         ? spirv::StructType::get(arrayType)
40501178654SLei Zhang                         : spirv::StructType::get(arrayType, 0);
40601178654SLei Zhang   return spirv::PointerType::get(structType, *storageClass);
40701178654SLei Zhang }
40801178654SLei Zhang 
40901178654SLei Zhang SPIRVTypeConverter::SPIRVTypeConverter(spirv::TargetEnvAttr targetAttr)
41001178654SLei Zhang     : targetEnv(targetAttr) {
41101178654SLei Zhang   // Add conversions. The order matters here: later ones will be tried earlier.
41201178654SLei Zhang 
41301178654SLei Zhang   // All other cases failed. Then we cannot convert this type.
41401178654SLei Zhang   addConversion([](Type type) { return llvm::None; });
41501178654SLei Zhang 
41601178654SLei Zhang   // Allow all SPIR-V dialect specific types. This assumes all builtin types
41701178654SLei Zhang   // adopted in the SPIR-V dialect (i.e., IntegerType, FloatType, VectorType)
41801178654SLei Zhang   // were tried before.
41901178654SLei Zhang   //
42001178654SLei Zhang   // TODO: this assumes that the SPIR-V types are valid to use in
42101178654SLei Zhang   // the given target environment, which should be the case if the whole
42201178654SLei Zhang   // pipeline is driven by the same target environment. Still, we probably still
42301178654SLei Zhang   // want to validate and convert to be safe.
42401178654SLei Zhang   addConversion([](spirv::SPIRVType type) { return type; });
42501178654SLei Zhang 
42601178654SLei Zhang   addConversion([](IndexType indexType) {
42701178654SLei Zhang     return SPIRVTypeConverter::getIndexType(indexType.getContext());
42801178654SLei Zhang   });
42901178654SLei Zhang 
43001178654SLei Zhang   addConversion([this](IntegerType intType) -> Optional<Type> {
43101178654SLei Zhang     if (auto scalarType = intType.dyn_cast<spirv::ScalarType>())
43201178654SLei Zhang       return convertScalarType(targetEnv, scalarType);
43301178654SLei Zhang     return llvm::None;
43401178654SLei Zhang   });
43501178654SLei Zhang 
43601178654SLei Zhang   addConversion([this](FloatType floatType) -> Optional<Type> {
43701178654SLei Zhang     if (auto scalarType = floatType.dyn_cast<spirv::ScalarType>())
43801178654SLei Zhang       return convertScalarType(targetEnv, scalarType);
43901178654SLei Zhang     return llvm::None;
44001178654SLei Zhang   });
44101178654SLei Zhang 
44201178654SLei Zhang   addConversion([this](VectorType vectorType) {
44301178654SLei Zhang     return convertVectorType(targetEnv, vectorType);
44401178654SLei Zhang   });
44501178654SLei Zhang 
44601178654SLei Zhang   addConversion([this](TensorType tensorType) {
44701178654SLei Zhang     return convertTensorType(targetEnv, tensorType);
44801178654SLei Zhang   });
44901178654SLei Zhang 
45001178654SLei Zhang   addConversion([this](MemRefType memRefType) {
45101178654SLei Zhang     return convertMemrefType(targetEnv, memRefType);
45201178654SLei Zhang   });
45301178654SLei Zhang }
45401178654SLei Zhang 
45501178654SLei Zhang //===----------------------------------------------------------------------===//
45601178654SLei Zhang // FuncOp Conversion Patterns
45701178654SLei Zhang //===----------------------------------------------------------------------===//
45801178654SLei Zhang 
45901178654SLei Zhang namespace {
46001178654SLei Zhang /// A pattern for rewriting function signature to convert arguments of functions
46101178654SLei Zhang /// to be of valid SPIR-V types.
46201178654SLei Zhang class FuncOpConversion final : public SPIRVOpLowering<FuncOp> {
46301178654SLei Zhang public:
46401178654SLei Zhang   using SPIRVOpLowering<FuncOp>::SPIRVOpLowering;
46501178654SLei Zhang 
46601178654SLei Zhang   LogicalResult
46701178654SLei Zhang   matchAndRewrite(FuncOp funcOp, ArrayRef<Value> operands,
46801178654SLei Zhang                   ConversionPatternRewriter &rewriter) const override;
46901178654SLei Zhang };
47001178654SLei Zhang } // namespace
47101178654SLei Zhang 
47201178654SLei Zhang LogicalResult
47301178654SLei Zhang FuncOpConversion::matchAndRewrite(FuncOp funcOp, ArrayRef<Value> operands,
47401178654SLei Zhang                                   ConversionPatternRewriter &rewriter) const {
47501178654SLei Zhang   auto fnType = funcOp.getType();
47601178654SLei Zhang   // TODO: support converting functions with one result.
47701178654SLei Zhang   if (fnType.getNumResults())
47801178654SLei Zhang     return failure();
47901178654SLei Zhang 
48001178654SLei Zhang   TypeConverter::SignatureConversion signatureConverter(fnType.getNumInputs());
48101178654SLei Zhang   for (auto argType : enumerate(funcOp.getType().getInputs())) {
48201178654SLei Zhang     auto convertedType = typeConverter.convertType(argType.value());
48301178654SLei Zhang     if (!convertedType)
48401178654SLei Zhang       return failure();
48501178654SLei Zhang     signatureConverter.addInputs(argType.index(), convertedType);
48601178654SLei Zhang   }
48701178654SLei Zhang 
48801178654SLei Zhang   // Create the converted spv.func op.
48901178654SLei Zhang   auto newFuncOp = rewriter.create<spirv::FuncOp>(
49001178654SLei Zhang       funcOp.getLoc(), funcOp.getName(),
49101178654SLei Zhang       rewriter.getFunctionType(signatureConverter.getConvertedTypes(),
49201178654SLei Zhang                                llvm::None));
49301178654SLei Zhang 
49401178654SLei Zhang   // Copy over all attributes other than the function name and type.
49501178654SLei Zhang   for (const auto &namedAttr : funcOp.getAttrs()) {
49601178654SLei Zhang     if (namedAttr.first != impl::getTypeAttrName() &&
49701178654SLei Zhang         namedAttr.first != SymbolTable::getSymbolAttrName())
49801178654SLei Zhang       newFuncOp->setAttr(namedAttr.first, namedAttr.second);
49901178654SLei Zhang   }
50001178654SLei Zhang 
50101178654SLei Zhang   rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(),
50201178654SLei Zhang                               newFuncOp.end());
50301178654SLei Zhang   if (failed(rewriter.convertRegionTypes(&newFuncOp.getBody(), typeConverter,
50401178654SLei Zhang                                          &signatureConverter)))
50501178654SLei Zhang     return failure();
50601178654SLei Zhang   rewriter.eraseOp(funcOp);
50701178654SLei Zhang   return success();
50801178654SLei Zhang }
50901178654SLei Zhang 
51001178654SLei Zhang void mlir::populateBuiltinFuncToSPIRVPatterns(
51101178654SLei Zhang     MLIRContext *context, SPIRVTypeConverter &typeConverter,
51201178654SLei Zhang     OwningRewritePatternList &patterns) {
51301178654SLei Zhang   patterns.insert<FuncOpConversion>(context, typeConverter);
51401178654SLei Zhang }
51501178654SLei Zhang 
51601178654SLei Zhang //===----------------------------------------------------------------------===//
51701178654SLei Zhang // Builtin Variables
51801178654SLei Zhang //===----------------------------------------------------------------------===//
51901178654SLei Zhang 
52001178654SLei Zhang static spirv::GlobalVariableOp getBuiltinVariable(Block &body,
52101178654SLei Zhang                                                   spirv::BuiltIn builtin) {
52201178654SLei Zhang   // Look through all global variables in the given `body` block and check if
52301178654SLei Zhang   // there is a spv.globalVariable that has the same `builtin` attribute.
52401178654SLei Zhang   for (auto varOp : body.getOps<spirv::GlobalVariableOp>()) {
52501178654SLei Zhang     if (auto builtinAttr = varOp->getAttrOfType<StringAttr>(
52601178654SLei Zhang             spirv::SPIRVDialect::getAttributeName(
52701178654SLei Zhang                 spirv::Decoration::BuiltIn))) {
52801178654SLei Zhang       auto varBuiltIn = spirv::symbolizeBuiltIn(builtinAttr.getValue());
52901178654SLei Zhang       if (varBuiltIn && varBuiltIn.getValue() == builtin) {
53001178654SLei Zhang         return varOp;
53101178654SLei Zhang       }
53201178654SLei Zhang     }
53301178654SLei Zhang   }
53401178654SLei Zhang   return nullptr;
53501178654SLei Zhang }
53601178654SLei Zhang 
53701178654SLei Zhang /// Gets name of global variable for a builtin.
53801178654SLei Zhang static std::string getBuiltinVarName(spirv::BuiltIn builtin) {
53901178654SLei Zhang   return std::string("__builtin_var_") + stringifyBuiltIn(builtin).str() + "__";
54001178654SLei Zhang }
54101178654SLei Zhang 
54201178654SLei Zhang /// Gets or inserts a global variable for a builtin within `body` block.
54301178654SLei Zhang static spirv::GlobalVariableOp
54401178654SLei Zhang getOrInsertBuiltinVariable(Block &body, Location loc, spirv::BuiltIn builtin,
54501178654SLei Zhang                            OpBuilder &builder) {
54601178654SLei Zhang   if (auto varOp = getBuiltinVariable(body, builtin))
54701178654SLei Zhang     return varOp;
54801178654SLei Zhang 
54901178654SLei Zhang   OpBuilder::InsertionGuard guard(builder);
55001178654SLei Zhang   builder.setInsertionPointToStart(&body);
55101178654SLei Zhang 
55201178654SLei Zhang   spirv::GlobalVariableOp newVarOp;
55301178654SLei Zhang   switch (builtin) {
55401178654SLei Zhang   case spirv::BuiltIn::NumWorkgroups:
55501178654SLei Zhang   case spirv::BuiltIn::WorkgroupSize:
55601178654SLei Zhang   case spirv::BuiltIn::WorkgroupId:
55701178654SLei Zhang   case spirv::BuiltIn::LocalInvocationId:
55801178654SLei Zhang   case spirv::BuiltIn::GlobalInvocationId: {
55901178654SLei Zhang     auto ptrType = spirv::PointerType::get(
56001178654SLei Zhang         VectorType::get({3}, builder.getIntegerType(32)),
56101178654SLei Zhang         spirv::StorageClass::Input);
56201178654SLei Zhang     std::string name = getBuiltinVarName(builtin);
56301178654SLei Zhang     newVarOp =
56401178654SLei Zhang         builder.create<spirv::GlobalVariableOp>(loc, ptrType, name, builtin);
56501178654SLei Zhang     break;
56601178654SLei Zhang   }
56701178654SLei Zhang   case spirv::BuiltIn::SubgroupId:
56801178654SLei Zhang   case spirv::BuiltIn::NumSubgroups:
56901178654SLei Zhang   case spirv::BuiltIn::SubgroupSize: {
57001178654SLei Zhang     auto ptrType = spirv::PointerType::get(builder.getIntegerType(32),
57101178654SLei Zhang                                            spirv::StorageClass::Input);
57201178654SLei Zhang     std::string name = getBuiltinVarName(builtin);
57301178654SLei Zhang     newVarOp =
57401178654SLei Zhang         builder.create<spirv::GlobalVariableOp>(loc, ptrType, name, builtin);
57501178654SLei Zhang     break;
57601178654SLei Zhang   }
57701178654SLei Zhang   default:
57801178654SLei Zhang     emitError(loc, "unimplemented builtin variable generation for ")
57901178654SLei Zhang         << stringifyBuiltIn(builtin);
58001178654SLei Zhang   }
58101178654SLei Zhang   return newVarOp;
58201178654SLei Zhang }
58301178654SLei Zhang 
58401178654SLei Zhang Value mlir::spirv::getBuiltinVariableValue(Operation *op,
58501178654SLei Zhang                                            spirv::BuiltIn builtin,
58601178654SLei Zhang                                            OpBuilder &builder) {
58701178654SLei Zhang   Operation *parent = SymbolTable::getNearestSymbolTable(op->getParentOp());
58801178654SLei Zhang   if (!parent) {
58901178654SLei Zhang     op->emitError("expected operation to be within a module-like op");
59001178654SLei Zhang     return nullptr;
59101178654SLei Zhang   }
59201178654SLei Zhang 
59301178654SLei Zhang   spirv::GlobalVariableOp varOp = getOrInsertBuiltinVariable(
59401178654SLei Zhang       *parent->getRegion(0).begin(), op->getLoc(), builtin, builder);
59501178654SLei Zhang   Value ptr = builder.create<spirv::AddressOfOp>(op->getLoc(), varOp);
59601178654SLei Zhang   return builder.create<spirv::LoadOp>(op->getLoc(), ptr);
59701178654SLei Zhang }
59801178654SLei Zhang 
59901178654SLei Zhang //===----------------------------------------------------------------------===//
60001178654SLei Zhang // Index calculation
60101178654SLei Zhang //===----------------------------------------------------------------------===//
60201178654SLei Zhang 
60301178654SLei Zhang spirv::AccessChainOp mlir::spirv::getElementPtr(
60401178654SLei Zhang     SPIRVTypeConverter &typeConverter, MemRefType baseType, Value basePtr,
60501178654SLei Zhang     ValueRange indices, Location loc, OpBuilder &builder) {
60601178654SLei Zhang   // Get base and offset of the MemRefType and verify they are static.
60701178654SLei Zhang 
60801178654SLei Zhang   int64_t offset;
60901178654SLei Zhang   SmallVector<int64_t, 4> strides;
61001178654SLei Zhang   if (failed(getStridesAndOffset(baseType, strides, offset)) ||
61101178654SLei Zhang       llvm::is_contained(strides, MemRefType::getDynamicStrideOrOffset()) ||
61201178654SLei Zhang       offset == MemRefType::getDynamicStrideOrOffset()) {
61301178654SLei Zhang     return nullptr;
61401178654SLei Zhang   }
61501178654SLei Zhang 
61601178654SLei Zhang   auto indexType = typeConverter.getIndexType(builder.getContext());
61701178654SLei Zhang 
61801178654SLei Zhang   SmallVector<Value, 2> linearizedIndices;
61901178654SLei Zhang   // Add a '0' at the start to index into the struct.
62001178654SLei Zhang   auto zero = spirv::ConstantOp::getZero(indexType, loc, builder);
62101178654SLei Zhang   linearizedIndices.push_back(zero);
62201178654SLei Zhang 
62301178654SLei Zhang   if (baseType.getRank() == 0) {
62401178654SLei Zhang     linearizedIndices.push_back(zero);
62501178654SLei Zhang   } else {
62601178654SLei Zhang     // TODO: Instead of this logic, use affine.apply and add patterns for
62701178654SLei Zhang     // lowering affine.apply to standard ops. These will get lowered to SPIR-V
62801178654SLei Zhang     // ops by the DialectConversion framework.
62901178654SLei Zhang     Value ptrLoc = builder.create<spirv::ConstantOp>(
63001178654SLei Zhang         loc, indexType, IntegerAttr::get(indexType, offset));
63101178654SLei Zhang     assert(indices.size() == strides.size() &&
63201178654SLei Zhang            "must provide indices for all dimensions");
63301178654SLei Zhang     for (auto index : llvm::enumerate(indices)) {
63401178654SLei Zhang       Value strideVal = builder.create<spirv::ConstantOp>(
63501178654SLei Zhang           loc, indexType, IntegerAttr::get(indexType, strides[index.index()]));
63601178654SLei Zhang       Value update =
63701178654SLei Zhang           builder.create<spirv::IMulOp>(loc, strideVal, index.value());
63801178654SLei Zhang       ptrLoc = builder.create<spirv::IAddOp>(loc, ptrLoc, update);
63901178654SLei Zhang     }
64001178654SLei Zhang     linearizedIndices.push_back(ptrLoc);
64101178654SLei Zhang   }
64201178654SLei Zhang   return builder.create<spirv::AccessChainOp>(loc, basePtr, linearizedIndices);
64301178654SLei Zhang }
64401178654SLei Zhang 
64501178654SLei Zhang //===----------------------------------------------------------------------===//
64601178654SLei Zhang // Set ABI attributes for lowering entry functions.
64701178654SLei Zhang //===----------------------------------------------------------------------===//
64801178654SLei Zhang 
64901178654SLei Zhang LogicalResult
65001178654SLei Zhang mlir::spirv::setABIAttrs(spirv::FuncOp funcOp,
65101178654SLei Zhang                          spirv::EntryPointABIAttr entryPointInfo,
65201178654SLei Zhang                          ArrayRef<spirv::InterfaceVarABIAttr> argABIInfo) {
65301178654SLei Zhang   // Set the attributes for argument and the function.
65401178654SLei Zhang   StringRef argABIAttrName = spirv::getInterfaceVarABIAttrName();
65501178654SLei Zhang   for (auto argIndex : llvm::seq<unsigned>(0, argABIInfo.size())) {
65601178654SLei Zhang     funcOp.setArgAttr(argIndex, argABIAttrName, argABIInfo[argIndex]);
65701178654SLei Zhang   }
65801178654SLei Zhang   funcOp->setAttr(spirv::getEntryPointABIAttrName(), entryPointInfo);
65901178654SLei Zhang   return success();
66001178654SLei Zhang }
66101178654SLei Zhang 
66201178654SLei Zhang //===----------------------------------------------------------------------===//
66301178654SLei Zhang // SPIR-V ConversionTarget
66401178654SLei Zhang //===----------------------------------------------------------------------===//
66501178654SLei Zhang 
66601178654SLei Zhang std::unique_ptr<spirv::SPIRVConversionTarget>
66701178654SLei Zhang spirv::SPIRVConversionTarget::get(spirv::TargetEnvAttr targetAttr) {
66801178654SLei Zhang   std::unique_ptr<SPIRVConversionTarget> target(
66901178654SLei Zhang       // std::make_unique does not work here because the constructor is private.
67001178654SLei Zhang       new SPIRVConversionTarget(targetAttr));
67101178654SLei Zhang   SPIRVConversionTarget *targetPtr = target.get();
67201178654SLei Zhang   target->addDynamicallyLegalDialect<SPIRVDialect>(
67301178654SLei Zhang       // We need to capture the raw pointer here because it is stable:
67401178654SLei Zhang       // target will be destroyed once this function is returned.
67501178654SLei Zhang       [targetPtr](Operation *op) { return targetPtr->isLegalOp(op); });
67601178654SLei Zhang   return target;
67701178654SLei Zhang }
67801178654SLei Zhang 
67901178654SLei Zhang spirv::SPIRVConversionTarget::SPIRVConversionTarget(
68001178654SLei Zhang     spirv::TargetEnvAttr targetAttr)
68101178654SLei Zhang     : ConversionTarget(*targetAttr.getContext()), targetEnv(targetAttr) {}
68201178654SLei Zhang 
68301178654SLei Zhang bool spirv::SPIRVConversionTarget::isLegalOp(Operation *op) {
68401178654SLei Zhang   // Make sure this op is available at the given version. Ops not implementing
68501178654SLei Zhang   // QueryMinVersionInterface/QueryMaxVersionInterface are available to all
68601178654SLei Zhang   // SPIR-V versions.
68701178654SLei Zhang   if (auto minVersion = dyn_cast<spirv::QueryMinVersionInterface>(op))
68801178654SLei Zhang     if (minVersion.getMinVersion() > this->targetEnv.getVersion()) {
68901178654SLei Zhang       LLVM_DEBUG(llvm::dbgs()
69001178654SLei Zhang                  << op->getName() << " illegal: requiring min version "
69101178654SLei Zhang                  << spirv::stringifyVersion(minVersion.getMinVersion())
69201178654SLei Zhang                  << "\n");
69301178654SLei Zhang       return false;
69401178654SLei Zhang     }
69501178654SLei Zhang   if (auto maxVersion = dyn_cast<spirv::QueryMaxVersionInterface>(op))
69601178654SLei Zhang     if (maxVersion.getMaxVersion() < this->targetEnv.getVersion()) {
69701178654SLei Zhang       LLVM_DEBUG(llvm::dbgs()
69801178654SLei Zhang                  << op->getName() << " illegal: requiring max version "
69901178654SLei Zhang                  << spirv::stringifyVersion(maxVersion.getMaxVersion())
70001178654SLei Zhang                  << "\n");
70101178654SLei Zhang       return false;
70201178654SLei Zhang     }
70301178654SLei Zhang 
70401178654SLei Zhang   // Make sure this op's required extensions are allowed to use. Ops not
70501178654SLei Zhang   // implementing QueryExtensionInterface do not require extensions to be
70601178654SLei Zhang   // available.
70701178654SLei Zhang   if (auto extensions = dyn_cast<spirv::QueryExtensionInterface>(op))
70801178654SLei Zhang     if (failed(checkExtensionRequirements(op->getName(), this->targetEnv,
70901178654SLei Zhang                                           extensions.getExtensions())))
71001178654SLei Zhang       return false;
71101178654SLei Zhang 
71201178654SLei Zhang   // Make sure this op's required extensions are allowed to use. Ops not
71301178654SLei Zhang   // implementing QueryCapabilityInterface do not require capabilities to be
71401178654SLei Zhang   // available.
71501178654SLei Zhang   if (auto capabilities = dyn_cast<spirv::QueryCapabilityInterface>(op))
71601178654SLei Zhang     if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv,
71701178654SLei Zhang                                            capabilities.getCapabilities())))
71801178654SLei Zhang       return false;
71901178654SLei Zhang 
72001178654SLei Zhang   SmallVector<Type, 4> valueTypes;
72101178654SLei Zhang   valueTypes.append(op->operand_type_begin(), op->operand_type_end());
72201178654SLei Zhang   valueTypes.append(op->result_type_begin(), op->result_type_end());
72301178654SLei Zhang 
72401178654SLei Zhang   // Special treatment for global variables, whose type requirements are
72501178654SLei Zhang   // conveyed by type attributes.
72601178654SLei Zhang   if (auto globalVar = dyn_cast<spirv::GlobalVariableOp>(op))
72701178654SLei Zhang     valueTypes.push_back(globalVar.type());
72801178654SLei Zhang 
72901178654SLei Zhang   // Make sure the op's operands/results use types that are allowed by the
73001178654SLei Zhang   // target environment.
73101178654SLei Zhang   SmallVector<ArrayRef<spirv::Extension>, 4> typeExtensions;
73201178654SLei Zhang   SmallVector<ArrayRef<spirv::Capability>, 8> typeCapabilities;
73301178654SLei Zhang   for (Type valueType : valueTypes) {
73401178654SLei Zhang     typeExtensions.clear();
73501178654SLei Zhang     valueType.cast<spirv::SPIRVType>().getExtensions(typeExtensions);
73601178654SLei Zhang     if (failed(checkExtensionRequirements(op->getName(), this->targetEnv,
73701178654SLei Zhang                                           typeExtensions)))
73801178654SLei Zhang       return false;
73901178654SLei Zhang 
74001178654SLei Zhang     typeCapabilities.clear();
74101178654SLei Zhang     valueType.cast<spirv::SPIRVType>().getCapabilities(typeCapabilities);
74201178654SLei Zhang     if (failed(checkCapabilityRequirements(op->getName(), this->targetEnv,
74301178654SLei Zhang                                            typeCapabilities)))
74401178654SLei Zhang       return false;
74501178654SLei Zhang   }
74601178654SLei Zhang 
74701178654SLei Zhang   return true;
74801178654SLei Zhang }
749