1930c74f1SLei Zhang //===- SPIRVToLLVM.cpp - SPIR-V to LLVM Patterns --------------------------===//
2930c74f1SLei Zhang //
3930c74f1SLei Zhang // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4930c74f1SLei Zhang // See https://llvm.org/LICENSE.txt for license information.
5930c74f1SLei Zhang // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6930c74f1SLei Zhang //
7930c74f1SLei Zhang //===----------------------------------------------------------------------===//
8930c74f1SLei Zhang //
9930c74f1SLei Zhang // This file implements patterns to convert SPIR-V dialect to LLVM dialect.
10930c74f1SLei Zhang //
11930c74f1SLei Zhang //===----------------------------------------------------------------------===//
12930c74f1SLei Zhang 
13930c74f1SLei Zhang #include "mlir/Conversion/SPIRVToLLVM/SPIRVToLLVM.h"
1475e5f0aaSAlex Zinenko #include "mlir/Conversion/LLVMCommon/Pattern.h"
1575e5f0aaSAlex Zinenko #include "mlir/Conversion/LLVMCommon/TypeConverter.h"
16930c74f1SLei Zhang #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
17930c74f1SLei Zhang #include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
18930c74f1SLei Zhang #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
19930c74f1SLei Zhang #include "mlir/Dialect/SPIRV/Utils/LayoutUtils.h"
20930c74f1SLei Zhang #include "mlir/IR/BuiltinOps.h"
21930c74f1SLei Zhang #include "mlir/IR/PatternMatch.h"
22930c74f1SLei Zhang #include "mlir/Support/LogicalResult.h"
23930c74f1SLei Zhang #include "mlir/Transforms/DialectConversion.h"
24930c74f1SLei Zhang #include "llvm/Support/Debug.h"
25930c74f1SLei Zhang #include "llvm/Support/FormatVariadic.h"
26930c74f1SLei Zhang 
27930c74f1SLei Zhang #define DEBUG_TYPE "spirv-to-llvm-pattern"
28930c74f1SLei Zhang 
29930c74f1SLei Zhang using namespace mlir;
30930c74f1SLei Zhang 
31930c74f1SLei Zhang //===----------------------------------------------------------------------===//
32930c74f1SLei Zhang // Utility functions
33930c74f1SLei Zhang //===----------------------------------------------------------------------===//
34930c74f1SLei Zhang 
35930c74f1SLei Zhang /// Returns true if the given type is a signed integer or vector type.
36930c74f1SLei Zhang static bool isSignedIntegerOrVector(Type type) {
37930c74f1SLei Zhang   if (type.isSignedInteger())
38930c74f1SLei Zhang     return true;
39930c74f1SLei Zhang   if (auto vecType = type.dyn_cast<VectorType>())
40930c74f1SLei Zhang     return vecType.getElementType().isSignedInteger();
41930c74f1SLei Zhang   return false;
42930c74f1SLei Zhang }
43930c74f1SLei Zhang 
44930c74f1SLei Zhang /// Returns true if the given type is an unsigned integer or vector type
45930c74f1SLei Zhang static bool isUnsignedIntegerOrVector(Type type) {
46930c74f1SLei Zhang   if (type.isUnsignedInteger())
47930c74f1SLei Zhang     return true;
48930c74f1SLei Zhang   if (auto vecType = type.dyn_cast<VectorType>())
49930c74f1SLei Zhang     return vecType.getElementType().isUnsignedInteger();
50930c74f1SLei Zhang   return false;
51930c74f1SLei Zhang }
52930c74f1SLei Zhang 
53930c74f1SLei Zhang /// Returns the bit width of integer, float or vector of float or integer values
54930c74f1SLei Zhang static unsigned getBitWidth(Type type) {
55930c74f1SLei Zhang   assert((type.isIntOrFloat() || type.isa<VectorType>()) &&
56930c74f1SLei Zhang          "bitwidth is not supported for this type");
57930c74f1SLei Zhang   if (type.isIntOrFloat())
58930c74f1SLei Zhang     return type.getIntOrFloatBitWidth();
59930c74f1SLei Zhang   auto vecType = type.dyn_cast<VectorType>();
60930c74f1SLei Zhang   auto elementType = vecType.getElementType();
61930c74f1SLei Zhang   assert(elementType.isIntOrFloat() &&
62930c74f1SLei Zhang          "only integers and floats have a bitwidth");
63930c74f1SLei Zhang   return elementType.getIntOrFloatBitWidth();
64930c74f1SLei Zhang }
65930c74f1SLei Zhang 
66930c74f1SLei Zhang /// Returns the bit width of LLVMType integer or vector.
67c69c9e0fSAlex Zinenko static unsigned getLLVMTypeBitWidth(Type type) {
68bd30a796SAlex Zinenko   return (LLVM::isCompatibleVectorType(type) ? LLVM::getVectorElementType(type)
69bd30a796SAlex Zinenko                                              : type)
702230bf99SAlex Zinenko       .cast<IntegerType>()
712230bf99SAlex Zinenko       .getWidth();
72930c74f1SLei Zhang }
73930c74f1SLei Zhang 
74930c74f1SLei Zhang /// Creates `IntegerAttribute` with all bits set for given type
75930c74f1SLei Zhang static IntegerAttr minusOneIntegerAttribute(Type type, Builder builder) {
76930c74f1SLei Zhang   if (auto vecType = type.dyn_cast<VectorType>()) {
77930c74f1SLei Zhang     auto integerType = vecType.getElementType().cast<IntegerType>();
78930c74f1SLei Zhang     return builder.getIntegerAttr(integerType, -1);
79930c74f1SLei Zhang   }
80930c74f1SLei Zhang   auto integerType = type.cast<IntegerType>();
81930c74f1SLei Zhang   return builder.getIntegerAttr(integerType, -1);
82930c74f1SLei Zhang }
83930c74f1SLei Zhang 
84930c74f1SLei Zhang /// Creates `llvm.mlir.constant` with all bits set for the given type.
85930c74f1SLei Zhang static Value createConstantAllBitsSet(Location loc, Type srcType, Type dstType,
86930c74f1SLei Zhang                                       PatternRewriter &rewriter) {
87930c74f1SLei Zhang   if (srcType.isa<VectorType>()) {
88930c74f1SLei Zhang     return rewriter.create<LLVM::ConstantOp>(
89930c74f1SLei Zhang         loc, dstType,
90930c74f1SLei Zhang         SplatElementsAttr::get(srcType.cast<ShapedType>(),
91930c74f1SLei Zhang                                minusOneIntegerAttribute(srcType, rewriter)));
92930c74f1SLei Zhang   }
93930c74f1SLei Zhang   return rewriter.create<LLVM::ConstantOp>(
94930c74f1SLei Zhang       loc, dstType, minusOneIntegerAttribute(srcType, rewriter));
95930c74f1SLei Zhang }
96930c74f1SLei Zhang 
97930c74f1SLei Zhang /// Creates `llvm.mlir.constant` with a floating-point scalar or vector value.
98930c74f1SLei Zhang static Value createFPConstant(Location loc, Type srcType, Type dstType,
99930c74f1SLei Zhang                               PatternRewriter &rewriter, double value) {
100930c74f1SLei Zhang   if (auto vecType = srcType.dyn_cast<VectorType>()) {
101930c74f1SLei Zhang     auto floatType = vecType.getElementType().cast<FloatType>();
102930c74f1SLei Zhang     return rewriter.create<LLVM::ConstantOp>(
103930c74f1SLei Zhang         loc, dstType,
104930c74f1SLei Zhang         SplatElementsAttr::get(vecType,
105930c74f1SLei Zhang                                rewriter.getFloatAttr(floatType, value)));
106930c74f1SLei Zhang   }
107930c74f1SLei Zhang   auto floatType = srcType.cast<FloatType>();
108930c74f1SLei Zhang   return rewriter.create<LLVM::ConstantOp>(
109930c74f1SLei Zhang       loc, dstType, rewriter.getFloatAttr(floatType, value));
110930c74f1SLei Zhang }
111930c74f1SLei Zhang 
112930c74f1SLei Zhang /// Utility function for bitfield ops:
113930c74f1SLei Zhang ///   - `BitFieldInsert`
114930c74f1SLei Zhang ///   - `BitFieldSExtract`
115930c74f1SLei Zhang ///   - `BitFieldUExtract`
116930c74f1SLei Zhang /// Truncates or extends the value. If the bitwidth of the value is the same as
117c69c9e0fSAlex Zinenko /// `llvmType` bitwidth, the value remains unchanged.
118c69c9e0fSAlex Zinenko static Value optionallyTruncateOrExtend(Location loc, Value value,
119c69c9e0fSAlex Zinenko                                         Type llvmType,
120930c74f1SLei Zhang                                         PatternRewriter &rewriter) {
121930c74f1SLei Zhang   auto srcType = value.getType();
122930c74f1SLei Zhang   unsigned targetBitWidth = getLLVMTypeBitWidth(llvmType);
123c69c9e0fSAlex Zinenko   unsigned valueBitWidth = LLVM::isCompatibleType(srcType)
124c69c9e0fSAlex Zinenko                                ? getLLVMTypeBitWidth(srcType)
125930c74f1SLei Zhang                                : getBitWidth(srcType);
126930c74f1SLei Zhang 
127930c74f1SLei Zhang   if (valueBitWidth < targetBitWidth)
128930c74f1SLei Zhang     return rewriter.create<LLVM::ZExtOp>(loc, llvmType, value);
129930c74f1SLei Zhang   // If the bit widths of `Count` and `Offset` are greater than the bit width
130930c74f1SLei Zhang   // of the target type, they are truncated. Truncation is safe since `Count`
131930c74f1SLei Zhang   // and `Offset` must be no more than 64 for op behaviour to be defined. Hence,
132930c74f1SLei Zhang   // both values can be expressed in 8 bits.
133930c74f1SLei Zhang   if (valueBitWidth > targetBitWidth)
134930c74f1SLei Zhang     return rewriter.create<LLVM::TruncOp>(loc, llvmType, value);
135930c74f1SLei Zhang   return value;
136930c74f1SLei Zhang }
137930c74f1SLei Zhang 
138930c74f1SLei Zhang /// Broadcasts the value to vector with `numElements` number of elements.
139930c74f1SLei Zhang static Value broadcast(Location loc, Value toBroadcast, unsigned numElements,
140930c74f1SLei Zhang                        LLVMTypeConverter &typeConverter,
141930c74f1SLei Zhang                        ConversionPatternRewriter &rewriter) {
142930c74f1SLei Zhang   auto vectorType = VectorType::get(numElements, toBroadcast.getType());
143930c74f1SLei Zhang   auto llvmVectorType = typeConverter.convertType(vectorType);
144930c74f1SLei Zhang   auto llvmI32Type = typeConverter.convertType(rewriter.getIntegerType(32));
145930c74f1SLei Zhang   Value broadcasted = rewriter.create<LLVM::UndefOp>(loc, llvmVectorType);
146930c74f1SLei Zhang   for (unsigned i = 0; i < numElements; ++i) {
147930c74f1SLei Zhang     auto index = rewriter.create<LLVM::ConstantOp>(
148930c74f1SLei Zhang         loc, llvmI32Type, rewriter.getI32IntegerAttr(i));
149930c74f1SLei Zhang     broadcasted = rewriter.create<LLVM::InsertElementOp>(
150930c74f1SLei Zhang         loc, llvmVectorType, broadcasted, toBroadcast, index);
151930c74f1SLei Zhang   }
152930c74f1SLei Zhang   return broadcasted;
153930c74f1SLei Zhang }
154930c74f1SLei Zhang 
155930c74f1SLei Zhang /// Broadcasts the value. If `srcType` is a scalar, the value remains unchanged.
156930c74f1SLei Zhang static Value optionallyBroadcast(Location loc, Value value, Type srcType,
157930c74f1SLei Zhang                                  LLVMTypeConverter &typeConverter,
158930c74f1SLei Zhang                                  ConversionPatternRewriter &rewriter) {
159930c74f1SLei Zhang   if (auto vectorType = srcType.dyn_cast<VectorType>()) {
160930c74f1SLei Zhang     unsigned numElements = vectorType.getNumElements();
161930c74f1SLei Zhang     return broadcast(loc, value, numElements, typeConverter, rewriter);
162930c74f1SLei Zhang   }
163930c74f1SLei Zhang   return value;
164930c74f1SLei Zhang }
165930c74f1SLei Zhang 
166930c74f1SLei Zhang /// Utility function for bitfield ops: `BitFieldInsert`, `BitFieldSExtract` and
167930c74f1SLei Zhang /// `BitFieldUExtract`.
168930c74f1SLei Zhang /// Broadcast `Offset` and `Count` to match the type of `Base`. If `Base` is of
169930c74f1SLei Zhang /// a vector type, construct a vector that has:
170930c74f1SLei Zhang ///  - same number of elements as `Base`
171930c74f1SLei Zhang ///  - each element has the type that is the same as the type of `Offset` or
172930c74f1SLei Zhang ///    `Count`
173930c74f1SLei Zhang ///  - each element has the same value as `Offset` or `Count`
174930c74f1SLei Zhang /// Then cast `Offset` and `Count` if their bit width is different
175930c74f1SLei Zhang /// from `Base` bit width.
176930c74f1SLei Zhang static Value processCountOrOffset(Location loc, Value value, Type srcType,
177930c74f1SLei Zhang                                   Type dstType, LLVMTypeConverter &converter,
178930c74f1SLei Zhang                                   ConversionPatternRewriter &rewriter) {
179930c74f1SLei Zhang   Value broadcasted =
180930c74f1SLei Zhang       optionallyBroadcast(loc, value, srcType, converter, rewriter);
181930c74f1SLei Zhang   return optionallyTruncateOrExtend(loc, broadcasted, dstType, rewriter);
182930c74f1SLei Zhang }
183930c74f1SLei Zhang 
184930c74f1SLei Zhang /// Converts SPIR-V struct with a regular (according to `VulkanLayoutUtils`)
185930c74f1SLei Zhang /// offset to LLVM struct. Otherwise, the conversion is not supported.
186930c74f1SLei Zhang static Optional<Type>
187930c74f1SLei Zhang convertStructTypeWithOffset(spirv::StructType type,
188930c74f1SLei Zhang                             LLVMTypeConverter &converter) {
189930c74f1SLei Zhang   if (type != VulkanLayoutUtils::decorateType(type))
190930c74f1SLei Zhang     return llvm::None;
191930c74f1SLei Zhang 
192930c74f1SLei Zhang   auto elementsVector = llvm::to_vector<8>(
193930c74f1SLei Zhang       llvm::map_range(type.getElementTypes(), [&](Type elementType) {
194c69c9e0fSAlex Zinenko         return converter.convertType(elementType);
195930c74f1SLei Zhang       }));
196930c74f1SLei Zhang   return LLVM::LLVMStructType::getLiteral(type.getContext(), elementsVector,
197930c74f1SLei Zhang                                           /*isPacked=*/false);
198930c74f1SLei Zhang }
199930c74f1SLei Zhang 
200930c74f1SLei Zhang /// Converts SPIR-V struct with no offset to packed LLVM struct.
201930c74f1SLei Zhang static Type convertStructTypePacked(spirv::StructType type,
202930c74f1SLei Zhang                                     LLVMTypeConverter &converter) {
203930c74f1SLei Zhang   auto elementsVector = llvm::to_vector<8>(
204930c74f1SLei Zhang       llvm::map_range(type.getElementTypes(), [&](Type elementType) {
205c69c9e0fSAlex Zinenko         return converter.convertType(elementType);
206930c74f1SLei Zhang       }));
207930c74f1SLei Zhang   return LLVM::LLVMStructType::getLiteral(type.getContext(), elementsVector,
208930c74f1SLei Zhang                                           /*isPacked=*/true);
209930c74f1SLei Zhang }
210930c74f1SLei Zhang 
211930c74f1SLei Zhang /// Creates LLVM dialect constant with the given value.
212930c74f1SLei Zhang static Value createI32ConstantOf(Location loc, PatternRewriter &rewriter,
213930c74f1SLei Zhang                                  unsigned value) {
214930c74f1SLei Zhang   return rewriter.create<LLVM::ConstantOp>(
2152230bf99SAlex Zinenko       loc, IntegerType::get(rewriter.getContext(), 32),
216930c74f1SLei Zhang       rewriter.getIntegerAttr(rewriter.getI32Type(), value));
217930c74f1SLei Zhang }
218930c74f1SLei Zhang 
219930c74f1SLei Zhang /// Utility for `spv.Load` and `spv.Store` conversion.
220015192c6SRiver Riddle static LogicalResult replaceWithLoadOrStore(Operation *op, ValueRange operands,
221930c74f1SLei Zhang                                             ConversionPatternRewriter &rewriter,
222930c74f1SLei Zhang                                             LLVMTypeConverter &typeConverter,
223930c74f1SLei Zhang                                             unsigned alignment, bool isVolatile,
224930c74f1SLei Zhang                                             bool isNonTemporal) {
225930c74f1SLei Zhang   if (auto loadOp = dyn_cast<spirv::LoadOp>(op)) {
226930c74f1SLei Zhang     auto dstType = typeConverter.convertType(loadOp.getType());
227930c74f1SLei Zhang     if (!dstType)
228930c74f1SLei Zhang       return failure();
229930c74f1SLei Zhang     rewriter.replaceOpWithNewOp<LLVM::LoadOp>(
230015192c6SRiver Riddle         loadOp, dstType, spirv::LoadOpAdaptor(operands).ptr(), alignment,
231015192c6SRiver Riddle         isVolatile, isNonTemporal);
232930c74f1SLei Zhang     return success();
233930c74f1SLei Zhang   }
234930c74f1SLei Zhang   auto storeOp = cast<spirv::StoreOp>(op);
235015192c6SRiver Riddle   spirv::StoreOpAdaptor adaptor(operands);
236015192c6SRiver Riddle   rewriter.replaceOpWithNewOp<LLVM::StoreOp>(storeOp, adaptor.value(),
237015192c6SRiver Riddle                                              adaptor.ptr(), alignment,
238930c74f1SLei Zhang                                              isVolatile, isNonTemporal);
239930c74f1SLei Zhang   return success();
240930c74f1SLei Zhang }
241930c74f1SLei Zhang 
242930c74f1SLei Zhang //===----------------------------------------------------------------------===//
243930c74f1SLei Zhang // Type conversion
244930c74f1SLei Zhang //===----------------------------------------------------------------------===//
245930c74f1SLei Zhang 
246930c74f1SLei Zhang /// Converts SPIR-V array type to LLVM array. Natural stride (according to
247930c74f1SLei Zhang /// `VulkanLayoutUtils`) is also mapped to LLVM array. This has to be respected
248930c74f1SLei Zhang /// when converting ops that manipulate array types.
249930c74f1SLei Zhang static Optional<Type> convertArrayType(spirv::ArrayType type,
250930c74f1SLei Zhang                                        TypeConverter &converter) {
251930c74f1SLei Zhang   unsigned stride = type.getArrayStride();
252930c74f1SLei Zhang   Type elementType = type.getElementType();
253930c74f1SLei Zhang   auto sizeInBytes = elementType.cast<spirv::SPIRVType>().getSizeInBytes();
254930c74f1SLei Zhang   if (stride != 0 &&
255930c74f1SLei Zhang       !(sizeInBytes.hasValue() && sizeInBytes.getValue() == stride))
256930c74f1SLei Zhang     return llvm::None;
257930c74f1SLei Zhang 
258c69c9e0fSAlex Zinenko   auto llvmElementType = converter.convertType(elementType);
259930c74f1SLei Zhang   unsigned numElements = type.getNumElements();
260930c74f1SLei Zhang   return LLVM::LLVMArrayType::get(llvmElementType, numElements);
261930c74f1SLei Zhang }
262930c74f1SLei Zhang 
263930c74f1SLei Zhang /// Converts SPIR-V pointer type to LLVM pointer. Pointer's storage class is not
264930c74f1SLei Zhang /// modelled at the moment.
265930c74f1SLei Zhang static Type convertPointerType(spirv::PointerType type,
266930c74f1SLei Zhang                                TypeConverter &converter) {
267c69c9e0fSAlex Zinenko   auto pointeeType = converter.convertType(type.getPointeeType());
268930c74f1SLei Zhang   return LLVM::LLVMPointerType::get(pointeeType);
269930c74f1SLei Zhang }
270930c74f1SLei Zhang 
271930c74f1SLei Zhang /// Converts SPIR-V runtime array to LLVM array. Since LLVM allows indexing over
272930c74f1SLei Zhang /// the bounds, the runtime array is converted to a 0-sized LLVM array. There is
273930c74f1SLei Zhang /// no modelling of array stride at the moment.
274930c74f1SLei Zhang static Optional<Type> convertRuntimeArrayType(spirv::RuntimeArrayType type,
275930c74f1SLei Zhang                                               TypeConverter &converter) {
276930c74f1SLei Zhang   if (type.getArrayStride() != 0)
277930c74f1SLei Zhang     return llvm::None;
278c69c9e0fSAlex Zinenko   auto elementType = converter.convertType(type.getElementType());
279930c74f1SLei Zhang   return LLVM::LLVMArrayType::get(elementType, 0);
280930c74f1SLei Zhang }
281930c74f1SLei Zhang 
282930c74f1SLei Zhang /// Converts SPIR-V struct to LLVM struct. There is no support of structs with
283930c74f1SLei Zhang /// member decorations. Also, only natural offset is supported.
284930c74f1SLei Zhang static Optional<Type> convertStructType(spirv::StructType type,
285930c74f1SLei Zhang                                         LLVMTypeConverter &converter) {
286930c74f1SLei Zhang   SmallVector<spirv::StructType::MemberDecorationInfo, 4> memberDecorations;
287930c74f1SLei Zhang   type.getMemberDecorations(memberDecorations);
288930c74f1SLei Zhang   if (!memberDecorations.empty())
289930c74f1SLei Zhang     return llvm::None;
290930c74f1SLei Zhang   if (type.hasOffset())
291930c74f1SLei Zhang     return convertStructTypeWithOffset(type, converter);
292930c74f1SLei Zhang   return convertStructTypePacked(type, converter);
293930c74f1SLei Zhang }
294930c74f1SLei Zhang 
295930c74f1SLei Zhang //===----------------------------------------------------------------------===//
296930c74f1SLei Zhang // Operation conversion
297930c74f1SLei Zhang //===----------------------------------------------------------------------===//
298930c74f1SLei Zhang 
299930c74f1SLei Zhang namespace {
300930c74f1SLei Zhang 
301930c74f1SLei Zhang class AccessChainPattern : public SPIRVToLLVMConversion<spirv::AccessChainOp> {
302930c74f1SLei Zhang public:
303930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::AccessChainOp>::SPIRVToLLVMConversion;
304930c74f1SLei Zhang 
305930c74f1SLei Zhang   LogicalResult
306b54c724bSRiver Riddle   matchAndRewrite(spirv::AccessChainOp op, OpAdaptor adaptor,
307930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
308930c74f1SLei Zhang     auto dstType = typeConverter.convertType(op.component_ptr().getType());
309930c74f1SLei Zhang     if (!dstType)
310930c74f1SLei Zhang       return failure();
311930c74f1SLei Zhang     // To use GEP we need to add a first 0 index to go through the pointer.
312015192c6SRiver Riddle     auto indices = llvm::to_vector<4>(adaptor.indices());
313930c74f1SLei Zhang     Type indexType = op.indices().front().getType();
314930c74f1SLei Zhang     auto llvmIndexType = typeConverter.convertType(indexType);
315930c74f1SLei Zhang     if (!llvmIndexType)
316930c74f1SLei Zhang       return failure();
317930c74f1SLei Zhang     Value zero = rewriter.create<LLVM::ConstantOp>(
318930c74f1SLei Zhang         op.getLoc(), llvmIndexType, rewriter.getIntegerAttr(indexType, 0));
319930c74f1SLei Zhang     indices.insert(indices.begin(), zero);
320015192c6SRiver Riddle     rewriter.replaceOpWithNewOp<LLVM::GEPOp>(op, dstType, adaptor.base_ptr(),
321930c74f1SLei Zhang                                              indices);
322930c74f1SLei Zhang     return success();
323930c74f1SLei Zhang   }
324930c74f1SLei Zhang };
325930c74f1SLei Zhang 
326930c74f1SLei Zhang class AddressOfPattern : public SPIRVToLLVMConversion<spirv::AddressOfOp> {
327930c74f1SLei Zhang public:
328930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::AddressOfOp>::SPIRVToLLVMConversion;
329930c74f1SLei Zhang 
330930c74f1SLei Zhang   LogicalResult
331b54c724bSRiver Riddle   matchAndRewrite(spirv::AddressOfOp op, OpAdaptor adaptor,
332930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
333930c74f1SLei Zhang     auto dstType = typeConverter.convertType(op.pointer().getType());
334930c74f1SLei Zhang     if (!dstType)
335930c74f1SLei Zhang       return failure();
336c69c9e0fSAlex Zinenko     rewriter.replaceOpWithNewOp<LLVM::AddressOfOp>(op, dstType, op.variable());
337930c74f1SLei Zhang     return success();
338930c74f1SLei Zhang   }
339930c74f1SLei Zhang };
340930c74f1SLei Zhang 
341930c74f1SLei Zhang class BitFieldInsertPattern
342930c74f1SLei Zhang     : public SPIRVToLLVMConversion<spirv::BitFieldInsertOp> {
343930c74f1SLei Zhang public:
344930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::BitFieldInsertOp>::SPIRVToLLVMConversion;
345930c74f1SLei Zhang 
346930c74f1SLei Zhang   LogicalResult
347b54c724bSRiver Riddle   matchAndRewrite(spirv::BitFieldInsertOp op, OpAdaptor adaptor,
348930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
349930c74f1SLei Zhang     auto srcType = op.getType();
350930c74f1SLei Zhang     auto dstType = typeConverter.convertType(srcType);
351930c74f1SLei Zhang     if (!dstType)
352930c74f1SLei Zhang       return failure();
353930c74f1SLei Zhang     Location loc = op.getLoc();
354930c74f1SLei Zhang 
355930c74f1SLei Zhang     // Process `Offset` and `Count`: broadcast and extend/truncate if needed.
356930c74f1SLei Zhang     Value offset = processCountOrOffset(loc, op.offset(), srcType, dstType,
357930c74f1SLei Zhang                                         typeConverter, rewriter);
358930c74f1SLei Zhang     Value count = processCountOrOffset(loc, op.count(), srcType, dstType,
359930c74f1SLei Zhang                                        typeConverter, rewriter);
360930c74f1SLei Zhang 
361930c74f1SLei Zhang     // Create a mask with bits set outside [Offset, Offset + Count - 1].
362930c74f1SLei Zhang     Value minusOne = createConstantAllBitsSet(loc, srcType, dstType, rewriter);
363930c74f1SLei Zhang     Value maskShiftedByCount =
364930c74f1SLei Zhang         rewriter.create<LLVM::ShlOp>(loc, dstType, minusOne, count);
365930c74f1SLei Zhang     Value negated = rewriter.create<LLVM::XOrOp>(loc, dstType,
366930c74f1SLei Zhang                                                  maskShiftedByCount, minusOne);
367930c74f1SLei Zhang     Value maskShiftedByCountAndOffset =
368930c74f1SLei Zhang         rewriter.create<LLVM::ShlOp>(loc, dstType, negated, offset);
369930c74f1SLei Zhang     Value mask = rewriter.create<LLVM::XOrOp>(
370930c74f1SLei Zhang         loc, dstType, maskShiftedByCountAndOffset, minusOne);
371930c74f1SLei Zhang 
372930c74f1SLei Zhang     // Extract unchanged bits from the `Base`  that are outside of
373930c74f1SLei Zhang     // [Offset, Offset + Count - 1]. Then `or` with shifted `Insert`.
374930c74f1SLei Zhang     Value baseAndMask =
375930c74f1SLei Zhang         rewriter.create<LLVM::AndOp>(loc, dstType, op.base(), mask);
376930c74f1SLei Zhang     Value insertShiftedByOffset =
377930c74f1SLei Zhang         rewriter.create<LLVM::ShlOp>(loc, dstType, op.insert(), offset);
378930c74f1SLei Zhang     rewriter.replaceOpWithNewOp<LLVM::OrOp>(op, dstType, baseAndMask,
379930c74f1SLei Zhang                                             insertShiftedByOffset);
380930c74f1SLei Zhang     return success();
381930c74f1SLei Zhang   }
382930c74f1SLei Zhang };
383930c74f1SLei Zhang 
384930c74f1SLei Zhang /// Converts SPIR-V ConstantOp with scalar or vector type.
385930c74f1SLei Zhang class ConstantScalarAndVectorPattern
386930c74f1SLei Zhang     : public SPIRVToLLVMConversion<spirv::ConstantOp> {
387930c74f1SLei Zhang public:
388930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::ConstantOp>::SPIRVToLLVMConversion;
389930c74f1SLei Zhang 
390930c74f1SLei Zhang   LogicalResult
391b54c724bSRiver Riddle   matchAndRewrite(spirv::ConstantOp constOp, OpAdaptor adaptor,
392930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
393930c74f1SLei Zhang     auto srcType = constOp.getType();
394930c74f1SLei Zhang     if (!srcType.isa<VectorType>() && !srcType.isIntOrFloat())
395930c74f1SLei Zhang       return failure();
396930c74f1SLei Zhang 
397930c74f1SLei Zhang     auto dstType = typeConverter.convertType(srcType);
398930c74f1SLei Zhang     if (!dstType)
399930c74f1SLei Zhang       return failure();
400930c74f1SLei Zhang 
401930c74f1SLei Zhang     // SPIR-V constant can be a signed/unsigned integer, which has to be
402930c74f1SLei Zhang     // casted to signless integer when converting to LLVM dialect. Removing the
403930c74f1SLei Zhang     // sign bit may have unexpected behaviour. However, it is better to handle
404930c74f1SLei Zhang     // it case-by-case, given that the purpose of the conversion is not to
405930c74f1SLei Zhang     // cover all possible corner cases.
406930c74f1SLei Zhang     if (isSignedIntegerOrVector(srcType) ||
407930c74f1SLei Zhang         isUnsignedIntegerOrVector(srcType)) {
408930c74f1SLei Zhang       auto signlessType = rewriter.getIntegerType(getBitWidth(srcType));
409930c74f1SLei Zhang 
410930c74f1SLei Zhang       if (srcType.isa<VectorType>()) {
411930c74f1SLei Zhang         auto dstElementsAttr = constOp.value().cast<DenseIntElementsAttr>();
412930c74f1SLei Zhang         rewriter.replaceOpWithNewOp<LLVM::ConstantOp>(
413930c74f1SLei Zhang             constOp, dstType,
414930c74f1SLei Zhang             dstElementsAttr.mapValues(
415930c74f1SLei Zhang                 signlessType, [&](const APInt &value) { return value; }));
416930c74f1SLei Zhang         return success();
417930c74f1SLei Zhang       }
418930c74f1SLei Zhang       auto srcAttr = constOp.value().cast<IntegerAttr>();
419930c74f1SLei Zhang       auto dstAttr = rewriter.getIntegerAttr(signlessType, srcAttr.getValue());
420930c74f1SLei Zhang       rewriter.replaceOpWithNewOp<LLVM::ConstantOp>(constOp, dstType, dstAttr);
421930c74f1SLei Zhang       return success();
422930c74f1SLei Zhang     }
423b54c724bSRiver Riddle     rewriter.replaceOpWithNewOp<LLVM::ConstantOp>(
424b54c724bSRiver Riddle         constOp, dstType, adaptor.getOperands(), constOp->getAttrs());
425930c74f1SLei Zhang     return success();
426930c74f1SLei Zhang   }
427930c74f1SLei Zhang };
428930c74f1SLei Zhang 
429930c74f1SLei Zhang class BitFieldSExtractPattern
430930c74f1SLei Zhang     : public SPIRVToLLVMConversion<spirv::BitFieldSExtractOp> {
431930c74f1SLei Zhang public:
432930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::BitFieldSExtractOp>::SPIRVToLLVMConversion;
433930c74f1SLei Zhang 
434930c74f1SLei Zhang   LogicalResult
435b54c724bSRiver Riddle   matchAndRewrite(spirv::BitFieldSExtractOp op, OpAdaptor adaptor,
436930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
437930c74f1SLei Zhang     auto srcType = op.getType();
438930c74f1SLei Zhang     auto dstType = typeConverter.convertType(srcType);
439930c74f1SLei Zhang     if (!dstType)
440930c74f1SLei Zhang       return failure();
441930c74f1SLei Zhang     Location loc = op.getLoc();
442930c74f1SLei Zhang 
443930c74f1SLei Zhang     // Process `Offset` and `Count`: broadcast and extend/truncate if needed.
444930c74f1SLei Zhang     Value offset = processCountOrOffset(loc, op.offset(), srcType, dstType,
445930c74f1SLei Zhang                                         typeConverter, rewriter);
446930c74f1SLei Zhang     Value count = processCountOrOffset(loc, op.count(), srcType, dstType,
447930c74f1SLei Zhang                                        typeConverter, rewriter);
448930c74f1SLei Zhang 
449930c74f1SLei Zhang     // Create a constant that holds the size of the `Base`.
450930c74f1SLei Zhang     IntegerType integerType;
451930c74f1SLei Zhang     if (auto vecType = srcType.dyn_cast<VectorType>())
452930c74f1SLei Zhang       integerType = vecType.getElementType().cast<IntegerType>();
453930c74f1SLei Zhang     else
454930c74f1SLei Zhang       integerType = srcType.cast<IntegerType>();
455930c74f1SLei Zhang 
456930c74f1SLei Zhang     auto baseSize = rewriter.getIntegerAttr(integerType, getBitWidth(srcType));
457930c74f1SLei Zhang     Value size =
458930c74f1SLei Zhang         srcType.isa<VectorType>()
459930c74f1SLei Zhang             ? rewriter.create<LLVM::ConstantOp>(
460930c74f1SLei Zhang                   loc, dstType,
461930c74f1SLei Zhang                   SplatElementsAttr::get(srcType.cast<ShapedType>(), baseSize))
462930c74f1SLei Zhang             : rewriter.create<LLVM::ConstantOp>(loc, dstType, baseSize);
463930c74f1SLei Zhang 
464930c74f1SLei Zhang     // Shift `Base` left by [sizeof(Base) - (Count + Offset)], so that the bit
465930c74f1SLei Zhang     // at Offset + Count - 1 is the most significant bit now.
466930c74f1SLei Zhang     Value countPlusOffset =
467930c74f1SLei Zhang         rewriter.create<LLVM::AddOp>(loc, dstType, count, offset);
468930c74f1SLei Zhang     Value amountToShiftLeft =
469930c74f1SLei Zhang         rewriter.create<LLVM::SubOp>(loc, dstType, size, countPlusOffset);
470930c74f1SLei Zhang     Value baseShiftedLeft = rewriter.create<LLVM::ShlOp>(
471930c74f1SLei Zhang         loc, dstType, op.base(), amountToShiftLeft);
472930c74f1SLei Zhang 
473930c74f1SLei Zhang     // Shift the result right, filling the bits with the sign bit.
474930c74f1SLei Zhang     Value amountToShiftRight =
475930c74f1SLei Zhang         rewriter.create<LLVM::AddOp>(loc, dstType, offset, amountToShiftLeft);
476930c74f1SLei Zhang     rewriter.replaceOpWithNewOp<LLVM::AShrOp>(op, dstType, baseShiftedLeft,
477930c74f1SLei Zhang                                               amountToShiftRight);
478930c74f1SLei Zhang     return success();
479930c74f1SLei Zhang   }
480930c74f1SLei Zhang };
481930c74f1SLei Zhang 
482930c74f1SLei Zhang class BitFieldUExtractPattern
483930c74f1SLei Zhang     : public SPIRVToLLVMConversion<spirv::BitFieldUExtractOp> {
484930c74f1SLei Zhang public:
485930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::BitFieldUExtractOp>::SPIRVToLLVMConversion;
486930c74f1SLei Zhang 
487930c74f1SLei Zhang   LogicalResult
488b54c724bSRiver Riddle   matchAndRewrite(spirv::BitFieldUExtractOp op, OpAdaptor adaptor,
489930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
490930c74f1SLei Zhang     auto srcType = op.getType();
491930c74f1SLei Zhang     auto dstType = typeConverter.convertType(srcType);
492930c74f1SLei Zhang     if (!dstType)
493930c74f1SLei Zhang       return failure();
494930c74f1SLei Zhang     Location loc = op.getLoc();
495930c74f1SLei Zhang 
496930c74f1SLei Zhang     // Process `Offset` and `Count`: broadcast and extend/truncate if needed.
497930c74f1SLei Zhang     Value offset = processCountOrOffset(loc, op.offset(), srcType, dstType,
498930c74f1SLei Zhang                                         typeConverter, rewriter);
499930c74f1SLei Zhang     Value count = processCountOrOffset(loc, op.count(), srcType, dstType,
500930c74f1SLei Zhang                                        typeConverter, rewriter);
501930c74f1SLei Zhang 
502930c74f1SLei Zhang     // Create a mask with bits set at [0, Count - 1].
503930c74f1SLei Zhang     Value minusOne = createConstantAllBitsSet(loc, srcType, dstType, rewriter);
504930c74f1SLei Zhang     Value maskShiftedByCount =
505930c74f1SLei Zhang         rewriter.create<LLVM::ShlOp>(loc, dstType, minusOne, count);
506930c74f1SLei Zhang     Value mask = rewriter.create<LLVM::XOrOp>(loc, dstType, maskShiftedByCount,
507930c74f1SLei Zhang                                               minusOne);
508930c74f1SLei Zhang 
509930c74f1SLei Zhang     // Shift `Base` by `Offset` and apply the mask on it.
510930c74f1SLei Zhang     Value shiftedBase =
511930c74f1SLei Zhang         rewriter.create<LLVM::LShrOp>(loc, dstType, op.base(), offset);
512930c74f1SLei Zhang     rewriter.replaceOpWithNewOp<LLVM::AndOp>(op, dstType, shiftedBase, mask);
513930c74f1SLei Zhang     return success();
514930c74f1SLei Zhang   }
515930c74f1SLei Zhang };
516930c74f1SLei Zhang 
517930c74f1SLei Zhang class BranchConversionPattern : public SPIRVToLLVMConversion<spirv::BranchOp> {
518930c74f1SLei Zhang public:
519930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::BranchOp>::SPIRVToLLVMConversion;
520930c74f1SLei Zhang 
521930c74f1SLei Zhang   LogicalResult
522b54c724bSRiver Riddle   matchAndRewrite(spirv::BranchOp branchOp, OpAdaptor adaptor,
523930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
524b54c724bSRiver Riddle     rewriter.replaceOpWithNewOp<LLVM::BrOp>(branchOp, adaptor.getOperands(),
525930c74f1SLei Zhang                                             branchOp.getTarget());
526930c74f1SLei Zhang     return success();
527930c74f1SLei Zhang   }
528930c74f1SLei Zhang };
529930c74f1SLei Zhang 
530930c74f1SLei Zhang class BranchConditionalConversionPattern
531930c74f1SLei Zhang     : public SPIRVToLLVMConversion<spirv::BranchConditionalOp> {
532930c74f1SLei Zhang public:
533930c74f1SLei Zhang   using SPIRVToLLVMConversion<
534930c74f1SLei Zhang       spirv::BranchConditionalOp>::SPIRVToLLVMConversion;
535930c74f1SLei Zhang 
536930c74f1SLei Zhang   LogicalResult
537b54c724bSRiver Riddle   matchAndRewrite(spirv::BranchConditionalOp op, OpAdaptor adaptor,
538930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
539930c74f1SLei Zhang     // If branch weights exist, map them to 32-bit integer vector.
540930c74f1SLei Zhang     ElementsAttr branchWeights = nullptr;
541930c74f1SLei Zhang     if (auto weights = op.branch_weights()) {
542930c74f1SLei Zhang       VectorType weightType = VectorType::get(2, rewriter.getI32Type());
543930c74f1SLei Zhang       branchWeights =
544930c74f1SLei Zhang           DenseElementsAttr::get(weightType, weights.getValue().getValue());
545930c74f1SLei Zhang     }
546930c74f1SLei Zhang 
547930c74f1SLei Zhang     rewriter.replaceOpWithNewOp<LLVM::CondBrOp>(
548930c74f1SLei Zhang         op, op.condition(), op.getTrueBlockArguments(),
549930c74f1SLei Zhang         op.getFalseBlockArguments(), branchWeights, op.getTrueBlock(),
550930c74f1SLei Zhang         op.getFalseBlock());
551930c74f1SLei Zhang     return success();
552930c74f1SLei Zhang   }
553930c74f1SLei Zhang };
554930c74f1SLei Zhang 
555930c74f1SLei Zhang /// Converts `spv.CompositeExtract` to `llvm.extractvalue` if the container type
556930c74f1SLei Zhang /// is an aggregate type (struct or array). Otherwise, converts to
557930c74f1SLei Zhang /// `llvm.extractelement` that operates on vectors.
558930c74f1SLei Zhang class CompositeExtractPattern
559930c74f1SLei Zhang     : public SPIRVToLLVMConversion<spirv::CompositeExtractOp> {
560930c74f1SLei Zhang public:
561930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::CompositeExtractOp>::SPIRVToLLVMConversion;
562930c74f1SLei Zhang 
563930c74f1SLei Zhang   LogicalResult
564b54c724bSRiver Riddle   matchAndRewrite(spirv::CompositeExtractOp op, OpAdaptor adaptor,
565930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
566930c74f1SLei Zhang     auto dstType = this->typeConverter.convertType(op.getType());
567930c74f1SLei Zhang     if (!dstType)
568930c74f1SLei Zhang       return failure();
569930c74f1SLei Zhang 
570930c74f1SLei Zhang     Type containerType = op.composite().getType();
571930c74f1SLei Zhang     if (containerType.isa<VectorType>()) {
572930c74f1SLei Zhang       Location loc = op.getLoc();
573930c74f1SLei Zhang       IntegerAttr value = op.indices()[0].cast<IntegerAttr>();
574930c74f1SLei Zhang       Value index = createI32ConstantOf(loc, rewriter, value.getInt());
575930c74f1SLei Zhang       rewriter.replaceOpWithNewOp<LLVM::ExtractElementOp>(
576015192c6SRiver Riddle           op, dstType, adaptor.composite(), index);
577930c74f1SLei Zhang       return success();
578930c74f1SLei Zhang     }
579930c74f1SLei Zhang     rewriter.replaceOpWithNewOp<LLVM::ExtractValueOp>(
580015192c6SRiver Riddle         op, dstType, adaptor.composite(), op.indices());
581930c74f1SLei Zhang     return success();
582930c74f1SLei Zhang   }
583930c74f1SLei Zhang };
584930c74f1SLei Zhang 
585930c74f1SLei Zhang /// Converts `spv.CompositeInsert` to `llvm.insertvalue` if the container type
586930c74f1SLei Zhang /// is an aggregate type (struct or array). Otherwise, converts to
587930c74f1SLei Zhang /// `llvm.insertelement` that operates on vectors.
588930c74f1SLei Zhang class CompositeInsertPattern
589930c74f1SLei Zhang     : public SPIRVToLLVMConversion<spirv::CompositeInsertOp> {
590930c74f1SLei Zhang public:
591930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::CompositeInsertOp>::SPIRVToLLVMConversion;
592930c74f1SLei Zhang 
593930c74f1SLei Zhang   LogicalResult
594b54c724bSRiver Riddle   matchAndRewrite(spirv::CompositeInsertOp op, OpAdaptor adaptor,
595930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
596930c74f1SLei Zhang     auto dstType = this->typeConverter.convertType(op.getType());
597930c74f1SLei Zhang     if (!dstType)
598930c74f1SLei Zhang       return failure();
599930c74f1SLei Zhang 
600930c74f1SLei Zhang     Type containerType = op.composite().getType();
601930c74f1SLei Zhang     if (containerType.isa<VectorType>()) {
602930c74f1SLei Zhang       Location loc = op.getLoc();
603930c74f1SLei Zhang       IntegerAttr value = op.indices()[0].cast<IntegerAttr>();
604930c74f1SLei Zhang       Value index = createI32ConstantOf(loc, rewriter, value.getInt());
605930c74f1SLei Zhang       rewriter.replaceOpWithNewOp<LLVM::InsertElementOp>(
606015192c6SRiver Riddle           op, dstType, adaptor.composite(), adaptor.object(), index);
607930c74f1SLei Zhang       return success();
608930c74f1SLei Zhang     }
609930c74f1SLei Zhang     rewriter.replaceOpWithNewOp<LLVM::InsertValueOp>(
610015192c6SRiver Riddle         op, dstType, adaptor.composite(), adaptor.object(), op.indices());
611930c74f1SLei Zhang     return success();
612930c74f1SLei Zhang   }
613930c74f1SLei Zhang };
614930c74f1SLei Zhang 
615930c74f1SLei Zhang /// Converts SPIR-V operations that have straightforward LLVM equivalent
616930c74f1SLei Zhang /// into LLVM dialect operations.
617930c74f1SLei Zhang template <typename SPIRVOp, typename LLVMOp>
618930c74f1SLei Zhang class DirectConversionPattern : public SPIRVToLLVMConversion<SPIRVOp> {
619930c74f1SLei Zhang public:
620930c74f1SLei Zhang   using SPIRVToLLVMConversion<SPIRVOp>::SPIRVToLLVMConversion;
621930c74f1SLei Zhang 
622930c74f1SLei Zhang   LogicalResult
623b54c724bSRiver Riddle   matchAndRewrite(SPIRVOp operation, typename SPIRVOp::Adaptor adaptor,
624930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
625930c74f1SLei Zhang     auto dstType = this->typeConverter.convertType(operation.getType());
626930c74f1SLei Zhang     if (!dstType)
627930c74f1SLei Zhang       return failure();
628b54c724bSRiver Riddle     rewriter.template replaceOpWithNewOp<LLVMOp>(
629b54c724bSRiver Riddle         operation, dstType, adaptor.getOperands(), operation->getAttrs());
630930c74f1SLei Zhang     return success();
631930c74f1SLei Zhang   }
632930c74f1SLei Zhang };
633930c74f1SLei Zhang 
634930c74f1SLei Zhang /// Converts `spv.ExecutionMode` into a global struct constant that holds
635930c74f1SLei Zhang /// execution mode information.
636930c74f1SLei Zhang class ExecutionModePattern
637930c74f1SLei Zhang     : public SPIRVToLLVMConversion<spirv::ExecutionModeOp> {
638930c74f1SLei Zhang public:
639930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::ExecutionModeOp>::SPIRVToLLVMConversion;
640930c74f1SLei Zhang 
641930c74f1SLei Zhang   LogicalResult
642b54c724bSRiver Riddle   matchAndRewrite(spirv::ExecutionModeOp op, OpAdaptor adaptor,
643930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
644930c74f1SLei Zhang     // First, create the global struct's name that would be associated with
645930c74f1SLei Zhang     // this entry point's execution mode. We set it to be:
646c0a6381eSWeiwei Li     //   __spv__{SPIR-V module name}_{function name}_execution_mode_info_{mode}
647930c74f1SLei Zhang     ModuleOp module = op->getParentOfType<ModuleOp>();
648c0a6381eSWeiwei Li     IntegerAttr executionModeAttr = op.execution_modeAttr();
649930c74f1SLei Zhang     std::string moduleName;
650930c74f1SLei Zhang     if (module.getName().hasValue())
651930c74f1SLei Zhang       moduleName = "_" + module.getName().getValue().str();
652930c74f1SLei Zhang     else
653930c74f1SLei Zhang       moduleName = "";
654c0a6381eSWeiwei Li     std::string executionModeInfoName =
655c0a6381eSWeiwei Li         llvm::formatv("__spv_{0}_{1}_execution_mode_info_{2}", moduleName,
656c0a6381eSWeiwei Li                       op.fn().str(), executionModeAttr.getValue());
657930c74f1SLei Zhang 
658930c74f1SLei Zhang     MLIRContext *context = rewriter.getContext();
659930c74f1SLei Zhang     OpBuilder::InsertionGuard guard(rewriter);
660930c74f1SLei Zhang     rewriter.setInsertionPointToStart(module.getBody());
661930c74f1SLei Zhang 
662930c74f1SLei Zhang     // Create a struct type, corresponding to the C struct below.
663930c74f1SLei Zhang     // struct {
664930c74f1SLei Zhang     //   int32_t executionMode;
665930c74f1SLei Zhang     //   int32_t values[];          // optional values
666930c74f1SLei Zhang     // };
6672230bf99SAlex Zinenko     auto llvmI32Type = IntegerType::get(context, 32);
668c69c9e0fSAlex Zinenko     SmallVector<Type, 2> fields;
669930c74f1SLei Zhang     fields.push_back(llvmI32Type);
670930c74f1SLei Zhang     ArrayAttr values = op.values();
671930c74f1SLei Zhang     if (!values.empty()) {
672930c74f1SLei Zhang       auto arrayType = LLVM::LLVMArrayType::get(llvmI32Type, values.size());
673930c74f1SLei Zhang       fields.push_back(arrayType);
674930c74f1SLei Zhang     }
675930c74f1SLei Zhang     auto structType = LLVM::LLVMStructType::getLiteral(context, fields);
676930c74f1SLei Zhang 
677930c74f1SLei Zhang     // Create `llvm.mlir.global` with initializer region containing one block.
678930c74f1SLei Zhang     auto global = rewriter.create<LLVM::GlobalOp>(
679930c74f1SLei Zhang         UnknownLoc::get(context), structType, /*isConstant=*/true,
6809a0ea599SDumitru Potop         LLVM::Linkage::External, executionModeInfoName, Attribute(),
6819a0ea599SDumitru Potop         /*alignment=*/0);
682930c74f1SLei Zhang     Location loc = global.getLoc();
683930c74f1SLei Zhang     Region &region = global.getInitializerRegion();
684930c74f1SLei Zhang     Block *block = rewriter.createBlock(&region);
685930c74f1SLei Zhang 
686930c74f1SLei Zhang     // Initialize the struct and set the execution mode value.
687930c74f1SLei Zhang     rewriter.setInsertionPoint(block, block->begin());
688930c74f1SLei Zhang     Value structValue = rewriter.create<LLVM::UndefOp>(loc, structType);
689930c74f1SLei Zhang     Value executionMode =
690930c74f1SLei Zhang         rewriter.create<LLVM::ConstantOp>(loc, llvmI32Type, executionModeAttr);
691930c74f1SLei Zhang     structValue = rewriter.create<LLVM::InsertValueOp>(
692930c74f1SLei Zhang         loc, structType, structValue, executionMode,
693c2c83e97STres Popp         ArrayAttr::get(context,
694c2c83e97STres Popp                        {rewriter.getIntegerAttr(rewriter.getI32Type(), 0)}));
695930c74f1SLei Zhang 
696930c74f1SLei Zhang     // Insert extra operands if they exist into execution mode info struct.
697930c74f1SLei Zhang     for (unsigned i = 0, e = values.size(); i < e; ++i) {
698930c74f1SLei Zhang       auto attr = values.getValue()[i];
699930c74f1SLei Zhang       Value entry = rewriter.create<LLVM::ConstantOp>(loc, llvmI32Type, attr);
700930c74f1SLei Zhang       structValue = rewriter.create<LLVM::InsertValueOp>(
701930c74f1SLei Zhang           loc, structType, structValue, entry,
702c2c83e97STres Popp           ArrayAttr::get(context,
703c2c83e97STres Popp                          {rewriter.getIntegerAttr(rewriter.getI32Type(), 1),
704c2c83e97STres Popp                           rewriter.getIntegerAttr(rewriter.getI32Type(), i)}));
705930c74f1SLei Zhang     }
706930c74f1SLei Zhang     rewriter.create<LLVM::ReturnOp>(loc, ArrayRef<Value>({structValue}));
707930c74f1SLei Zhang     rewriter.eraseOp(op);
708930c74f1SLei Zhang     return success();
709930c74f1SLei Zhang   }
710930c74f1SLei Zhang };
711930c74f1SLei Zhang 
712c74eb466SKareemErgawy-TomTom /// Converts `spv.GlobalVariable` to `llvm.mlir.global`. Note that SPIR-V global
713930c74f1SLei Zhang /// returns a pointer, whereas in LLVM dialect the global holds an actual value.
714930c74f1SLei Zhang /// This difference is handled by `spv.mlir.addressof` and
715930c74f1SLei Zhang /// `llvm.mlir.addressof`ops that both return a pointer.
716930c74f1SLei Zhang class GlobalVariablePattern
717930c74f1SLei Zhang     : public SPIRVToLLVMConversion<spirv::GlobalVariableOp> {
718930c74f1SLei Zhang public:
719930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::GlobalVariableOp>::SPIRVToLLVMConversion;
720930c74f1SLei Zhang 
721930c74f1SLei Zhang   LogicalResult
722b54c724bSRiver Riddle   matchAndRewrite(spirv::GlobalVariableOp op, OpAdaptor adaptor,
723930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
724930c74f1SLei Zhang     // Currently, there is no support of initialization with a constant value in
725930c74f1SLei Zhang     // SPIR-V dialect. Specialization constants are not considered as well.
726930c74f1SLei Zhang     if (op.initializer())
727930c74f1SLei Zhang       return failure();
728930c74f1SLei Zhang 
729930c74f1SLei Zhang     auto srcType = op.type().cast<spirv::PointerType>();
730930c74f1SLei Zhang     auto dstType = typeConverter.convertType(srcType.getPointeeType());
731930c74f1SLei Zhang     if (!dstType)
732930c74f1SLei Zhang       return failure();
733930c74f1SLei Zhang 
734930c74f1SLei Zhang     // Limit conversion to the current invocation only or `StorageBuffer`
735930c74f1SLei Zhang     // required by SPIR-V runner.
736930c74f1SLei Zhang     // This is okay because multiple invocations are not supported yet.
737930c74f1SLei Zhang     auto storageClass = srcType.getStorageClass();
7381e4cfe5eSWeiwei Li     switch (storageClass) {
7391e4cfe5eSWeiwei Li     case spirv::StorageClass::Input:
7401e4cfe5eSWeiwei Li     case spirv::StorageClass::Private:
7411e4cfe5eSWeiwei Li     case spirv::StorageClass::Output:
7421e4cfe5eSWeiwei Li     case spirv::StorageClass::StorageBuffer:
7431e4cfe5eSWeiwei Li     case spirv::StorageClass::UniformConstant:
7441e4cfe5eSWeiwei Li       break;
7451e4cfe5eSWeiwei Li     default:
746930c74f1SLei Zhang       return failure();
747930c74f1SLei Zhang     }
748930c74f1SLei Zhang 
749930c74f1SLei Zhang     // LLVM dialect spec: "If the global value is a constant, storing into it is
7501e4cfe5eSWeiwei Li     // not allowed.". This corresponds to SPIR-V 'Input' and 'UniformConstant'
7511e4cfe5eSWeiwei Li     // storage class that is read-only.
7521e4cfe5eSWeiwei Li     bool isConstant = (storageClass == spirv::StorageClass::Input) ||
7531e4cfe5eSWeiwei Li                       (storageClass == spirv::StorageClass::UniformConstant);
754930c74f1SLei Zhang     // SPIR-V spec: "By default, functions and global variables are private to a
755930c74f1SLei Zhang     // module and cannot be accessed by other modules. However, a module may be
756930c74f1SLei Zhang     // written to export or import functions and global (module scope)
757930c74f1SLei Zhang     // variables.". Therefore, map 'Private' storage class to private linkage,
758930c74f1SLei Zhang     // 'Input' and 'Output' to external linkage.
759930c74f1SLei Zhang     auto linkage = storageClass == spirv::StorageClass::Private
760930c74f1SLei Zhang                        ? LLVM::Linkage::Private
761930c74f1SLei Zhang                        : LLVM::Linkage::External;
7621e4cfe5eSWeiwei Li     auto newGlobalOp = rewriter.replaceOpWithNewOp<LLVM::GlobalOp>(
7639a0ea599SDumitru Potop         op, dstType, isConstant, linkage, op.sym_name(), Attribute(),
7649a0ea599SDumitru Potop         /*alignment=*/0);
7651e4cfe5eSWeiwei Li 
7661e4cfe5eSWeiwei Li     // Attach location attribute if applicable
7671e4cfe5eSWeiwei Li     if (op.locationAttr())
7681e4cfe5eSWeiwei Li       newGlobalOp->setAttr(op.locationAttrName(), op.locationAttr());
7691e4cfe5eSWeiwei Li 
770930c74f1SLei Zhang     return success();
771930c74f1SLei Zhang   }
772930c74f1SLei Zhang };
773930c74f1SLei Zhang 
774930c74f1SLei Zhang /// Converts SPIR-V cast ops that do not have straightforward LLVM
775930c74f1SLei Zhang /// equivalent in LLVM dialect.
776930c74f1SLei Zhang template <typename SPIRVOp, typename LLVMExtOp, typename LLVMTruncOp>
777930c74f1SLei Zhang class IndirectCastPattern : public SPIRVToLLVMConversion<SPIRVOp> {
778930c74f1SLei Zhang public:
779930c74f1SLei Zhang   using SPIRVToLLVMConversion<SPIRVOp>::SPIRVToLLVMConversion;
780930c74f1SLei Zhang 
781930c74f1SLei Zhang   LogicalResult
782b54c724bSRiver Riddle   matchAndRewrite(SPIRVOp operation, typename SPIRVOp::Adaptor adaptor,
783930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
784930c74f1SLei Zhang 
785930c74f1SLei Zhang     Type fromType = operation.operand().getType();
786930c74f1SLei Zhang     Type toType = operation.getType();
787930c74f1SLei Zhang 
788930c74f1SLei Zhang     auto dstType = this->typeConverter.convertType(toType);
789930c74f1SLei Zhang     if (!dstType)
790930c74f1SLei Zhang       return failure();
791930c74f1SLei Zhang 
792930c74f1SLei Zhang     if (getBitWidth(fromType) < getBitWidth(toType)) {
793930c74f1SLei Zhang       rewriter.template replaceOpWithNewOp<LLVMExtOp>(operation, dstType,
794b54c724bSRiver Riddle                                                       adaptor.getOperands());
795930c74f1SLei Zhang       return success();
796930c74f1SLei Zhang     }
797930c74f1SLei Zhang     if (getBitWidth(fromType) > getBitWidth(toType)) {
798930c74f1SLei Zhang       rewriter.template replaceOpWithNewOp<LLVMTruncOp>(operation, dstType,
799b54c724bSRiver Riddle                                                         adaptor.getOperands());
800930c74f1SLei Zhang       return success();
801930c74f1SLei Zhang     }
802930c74f1SLei Zhang     return failure();
803930c74f1SLei Zhang   }
804930c74f1SLei Zhang };
805930c74f1SLei Zhang 
806930c74f1SLei Zhang class FunctionCallPattern
807930c74f1SLei Zhang     : public SPIRVToLLVMConversion<spirv::FunctionCallOp> {
808930c74f1SLei Zhang public:
809930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::FunctionCallOp>::SPIRVToLLVMConversion;
810930c74f1SLei Zhang 
811930c74f1SLei Zhang   LogicalResult
812b54c724bSRiver Riddle   matchAndRewrite(spirv::FunctionCallOp callOp, OpAdaptor adaptor,
813930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
814930c74f1SLei Zhang     if (callOp.getNumResults() == 0) {
815b54c724bSRiver Riddle       rewriter.replaceOpWithNewOp<LLVM::CallOp>(
816b54c724bSRiver Riddle           callOp, llvm::None, adaptor.getOperands(), callOp->getAttrs());
817930c74f1SLei Zhang       return success();
818930c74f1SLei Zhang     }
819930c74f1SLei Zhang 
820930c74f1SLei Zhang     // Function returns a single result.
821930c74f1SLei Zhang     auto dstType = typeConverter.convertType(callOp.getType(0));
822b54c724bSRiver Riddle     rewriter.replaceOpWithNewOp<LLVM::CallOp>(
823b54c724bSRiver Riddle         callOp, dstType, adaptor.getOperands(), callOp->getAttrs());
824930c74f1SLei Zhang     return success();
825930c74f1SLei Zhang   }
826930c74f1SLei Zhang };
827930c74f1SLei Zhang 
828930c74f1SLei Zhang /// Converts SPIR-V floating-point comparisons to llvm.fcmp "predicate"
829930c74f1SLei Zhang template <typename SPIRVOp, LLVM::FCmpPredicate predicate>
830930c74f1SLei Zhang class FComparePattern : public SPIRVToLLVMConversion<SPIRVOp> {
831930c74f1SLei Zhang public:
832930c74f1SLei Zhang   using SPIRVToLLVMConversion<SPIRVOp>::SPIRVToLLVMConversion;
833930c74f1SLei Zhang 
834930c74f1SLei Zhang   LogicalResult
835b54c724bSRiver Riddle   matchAndRewrite(SPIRVOp operation, typename SPIRVOp::Adaptor adaptor,
836930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
837930c74f1SLei Zhang 
838930c74f1SLei Zhang     auto dstType = this->typeConverter.convertType(operation.getType());
839930c74f1SLei Zhang     if (!dstType)
840930c74f1SLei Zhang       return failure();
841930c74f1SLei Zhang 
842930c74f1SLei Zhang     rewriter.template replaceOpWithNewOp<LLVM::FCmpOp>(
843fee90542SVladislav Vinogradov         operation, dstType, predicate, operation.operand1(),
844fee90542SVladislav Vinogradov         operation.operand2());
845930c74f1SLei Zhang     return success();
846930c74f1SLei Zhang   }
847930c74f1SLei Zhang };
848930c74f1SLei Zhang 
849930c74f1SLei Zhang /// Converts SPIR-V integer comparisons to llvm.icmp "predicate"
850930c74f1SLei Zhang template <typename SPIRVOp, LLVM::ICmpPredicate predicate>
851930c74f1SLei Zhang class IComparePattern : public SPIRVToLLVMConversion<SPIRVOp> {
852930c74f1SLei Zhang public:
853930c74f1SLei Zhang   using SPIRVToLLVMConversion<SPIRVOp>::SPIRVToLLVMConversion;
854930c74f1SLei Zhang 
855930c74f1SLei Zhang   LogicalResult
856b54c724bSRiver Riddle   matchAndRewrite(SPIRVOp operation, typename SPIRVOp::Adaptor adaptor,
857930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
858930c74f1SLei Zhang 
859930c74f1SLei Zhang     auto dstType = this->typeConverter.convertType(operation.getType());
860930c74f1SLei Zhang     if (!dstType)
861930c74f1SLei Zhang       return failure();
862930c74f1SLei Zhang 
863930c74f1SLei Zhang     rewriter.template replaceOpWithNewOp<LLVM::ICmpOp>(
864fee90542SVladislav Vinogradov         operation, dstType, predicate, operation.operand1(),
865fee90542SVladislav Vinogradov         operation.operand2());
866930c74f1SLei Zhang     return success();
867930c74f1SLei Zhang   }
868930c74f1SLei Zhang };
869930c74f1SLei Zhang 
870930c74f1SLei Zhang class InverseSqrtPattern
871930c74f1SLei Zhang     : public SPIRVToLLVMConversion<spirv::GLSLInverseSqrtOp> {
872930c74f1SLei Zhang public:
873930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::GLSLInverseSqrtOp>::SPIRVToLLVMConversion;
874930c74f1SLei Zhang 
875930c74f1SLei Zhang   LogicalResult
876b54c724bSRiver Riddle   matchAndRewrite(spirv::GLSLInverseSqrtOp op, OpAdaptor adaptor,
877930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
878930c74f1SLei Zhang     auto srcType = op.getType();
879930c74f1SLei Zhang     auto dstType = typeConverter.convertType(srcType);
880930c74f1SLei Zhang     if (!dstType)
881930c74f1SLei Zhang       return failure();
882930c74f1SLei Zhang 
883930c74f1SLei Zhang     Location loc = op.getLoc();
884930c74f1SLei Zhang     Value one = createFPConstant(loc, srcType, dstType, rewriter, 1.0);
885930c74f1SLei Zhang     Value sqrt = rewriter.create<LLVM::SqrtOp>(loc, dstType, op.operand());
886930c74f1SLei Zhang     rewriter.replaceOpWithNewOp<LLVM::FDivOp>(op, dstType, one, sqrt);
887930c74f1SLei Zhang     return success();
888930c74f1SLei Zhang   }
889930c74f1SLei Zhang };
890930c74f1SLei Zhang 
891930c74f1SLei Zhang /// Converts `spv.Load` and `spv.Store` to LLVM dialect.
892b54c724bSRiver Riddle template <typename SPIRVOp>
893b54c724bSRiver Riddle class LoadStorePattern : public SPIRVToLLVMConversion<SPIRVOp> {
894930c74f1SLei Zhang public:
895b54c724bSRiver Riddle   using SPIRVToLLVMConversion<SPIRVOp>::SPIRVToLLVMConversion;
896930c74f1SLei Zhang 
897930c74f1SLei Zhang   LogicalResult
898b54c724bSRiver Riddle   matchAndRewrite(SPIRVOp op, typename SPIRVOp::Adaptor adaptor,
899930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
900*037f0995SKazu Hirata     if (!op.memory_access()) {
901015192c6SRiver Riddle       return replaceWithLoadOrStore(op, adaptor.getOperands(), rewriter,
902015192c6SRiver Riddle                                     this->typeConverter, /*alignment=*/0,
903015192c6SRiver Riddle                                     /*isVolatile=*/false,
904015192c6SRiver Riddle                                     /*isNonTemporal=*/false);
905930c74f1SLei Zhang     }
906930c74f1SLei Zhang     auto memoryAccess = op.memory_access().getValue();
907930c74f1SLei Zhang     switch (memoryAccess) {
908930c74f1SLei Zhang     case spirv::MemoryAccess::Aligned:
909930c74f1SLei Zhang     case spirv::MemoryAccess::None:
910930c74f1SLei Zhang     case spirv::MemoryAccess::Nontemporal:
911930c74f1SLei Zhang     case spirv::MemoryAccess::Volatile: {
912930c74f1SLei Zhang       unsigned alignment =
913930c74f1SLei Zhang           memoryAccess == spirv::MemoryAccess::Aligned ? *op.alignment() : 0;
914930c74f1SLei Zhang       bool isNonTemporal = memoryAccess == spirv::MemoryAccess::Nontemporal;
915930c74f1SLei Zhang       bool isVolatile = memoryAccess == spirv::MemoryAccess::Volatile;
916015192c6SRiver Riddle       return replaceWithLoadOrStore(op, adaptor.getOperands(), rewriter,
917015192c6SRiver Riddle                                     this->typeConverter, alignment, isVolatile,
918015192c6SRiver Riddle                                     isNonTemporal);
919930c74f1SLei Zhang     }
920930c74f1SLei Zhang     default:
921930c74f1SLei Zhang       // There is no support of other memory access attributes.
922930c74f1SLei Zhang       return failure();
923930c74f1SLei Zhang     }
924930c74f1SLei Zhang   }
925930c74f1SLei Zhang };
926930c74f1SLei Zhang 
927930c74f1SLei Zhang /// Converts `spv.Not` and `spv.LogicalNot` into LLVM dialect.
928930c74f1SLei Zhang template <typename SPIRVOp>
929930c74f1SLei Zhang class NotPattern : public SPIRVToLLVMConversion<SPIRVOp> {
930930c74f1SLei Zhang public:
931930c74f1SLei Zhang   using SPIRVToLLVMConversion<SPIRVOp>::SPIRVToLLVMConversion;
932930c74f1SLei Zhang 
933930c74f1SLei Zhang   LogicalResult
934b54c724bSRiver Riddle   matchAndRewrite(SPIRVOp notOp, typename SPIRVOp::Adaptor adaptor,
935930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
936930c74f1SLei Zhang     auto srcType = notOp.getType();
937930c74f1SLei Zhang     auto dstType = this->typeConverter.convertType(srcType);
938930c74f1SLei Zhang     if (!dstType)
939930c74f1SLei Zhang       return failure();
940930c74f1SLei Zhang 
941930c74f1SLei Zhang     Location loc = notOp.getLoc();
942930c74f1SLei Zhang     IntegerAttr minusOne = minusOneIntegerAttribute(srcType, rewriter);
943930c74f1SLei Zhang     auto mask = srcType.template isa<VectorType>()
944930c74f1SLei Zhang                     ? rewriter.create<LLVM::ConstantOp>(
945930c74f1SLei Zhang                           loc, dstType,
946930c74f1SLei Zhang                           SplatElementsAttr::get(
947930c74f1SLei Zhang                               srcType.template cast<VectorType>(), minusOne))
948930c74f1SLei Zhang                     : rewriter.create<LLVM::ConstantOp>(loc, dstType, minusOne);
949930c74f1SLei Zhang     rewriter.template replaceOpWithNewOp<LLVM::XOrOp>(notOp, dstType,
950930c74f1SLei Zhang                                                       notOp.operand(), mask);
951930c74f1SLei Zhang     return success();
952930c74f1SLei Zhang   }
953930c74f1SLei Zhang };
954930c74f1SLei Zhang 
955930c74f1SLei Zhang /// A template pattern that erases the given `SPIRVOp`.
956930c74f1SLei Zhang template <typename SPIRVOp>
957930c74f1SLei Zhang class ErasePattern : public SPIRVToLLVMConversion<SPIRVOp> {
958930c74f1SLei Zhang public:
959930c74f1SLei Zhang   using SPIRVToLLVMConversion<SPIRVOp>::SPIRVToLLVMConversion;
960930c74f1SLei Zhang 
961930c74f1SLei Zhang   LogicalResult
962b54c724bSRiver Riddle   matchAndRewrite(SPIRVOp op, typename SPIRVOp::Adaptor adaptor,
963930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
964930c74f1SLei Zhang     rewriter.eraseOp(op);
965930c74f1SLei Zhang     return success();
966930c74f1SLei Zhang   }
967930c74f1SLei Zhang };
968930c74f1SLei Zhang 
969930c74f1SLei Zhang class ReturnPattern : public SPIRVToLLVMConversion<spirv::ReturnOp> {
970930c74f1SLei Zhang public:
971930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::ReturnOp>::SPIRVToLLVMConversion;
972930c74f1SLei Zhang 
973930c74f1SLei Zhang   LogicalResult
974b54c724bSRiver Riddle   matchAndRewrite(spirv::ReturnOp returnOp, OpAdaptor adaptor,
975930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
976930c74f1SLei Zhang     rewriter.replaceOpWithNewOp<LLVM::ReturnOp>(returnOp, ArrayRef<Type>(),
977930c74f1SLei Zhang                                                 ArrayRef<Value>());
978930c74f1SLei Zhang     return success();
979930c74f1SLei Zhang   }
980930c74f1SLei Zhang };
981930c74f1SLei Zhang 
982930c74f1SLei Zhang class ReturnValuePattern : public SPIRVToLLVMConversion<spirv::ReturnValueOp> {
983930c74f1SLei Zhang public:
984930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::ReturnValueOp>::SPIRVToLLVMConversion;
985930c74f1SLei Zhang 
986930c74f1SLei Zhang   LogicalResult
987b54c724bSRiver Riddle   matchAndRewrite(spirv::ReturnValueOp returnValueOp, OpAdaptor adaptor,
988930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
989930c74f1SLei Zhang     rewriter.replaceOpWithNewOp<LLVM::ReturnOp>(returnValueOp, ArrayRef<Type>(),
990b54c724bSRiver Riddle                                                 adaptor.getOperands());
991930c74f1SLei Zhang     return success();
992930c74f1SLei Zhang   }
993930c74f1SLei Zhang };
994930c74f1SLei Zhang 
99529812a61SKareemErgawy-TomTom /// Converts `spv.mlir.loop` to LLVM dialect. All blocks within selection should
99629812a61SKareemErgawy-TomTom /// be reachable for conversion to succeed. The structure of the loop in LLVM
99729812a61SKareemErgawy-TomTom /// dialect will be the following:
998930c74f1SLei Zhang ///
999930c74f1SLei Zhang ///      +------------------------------------+
100029812a61SKareemErgawy-TomTom ///      | <code before spv.mlir.loop>        |
1001930c74f1SLei Zhang ///      | llvm.br ^header                    |
1002930c74f1SLei Zhang ///      +------------------------------------+
1003930c74f1SLei Zhang ///                           |
1004930c74f1SLei Zhang ///   +----------------+      |
1005930c74f1SLei Zhang ///   |                |      |
1006930c74f1SLei Zhang ///   |                V      V
1007930c74f1SLei Zhang ///   |  +------------------------------------+
1008930c74f1SLei Zhang ///   |  | ^header:                           |
1009930c74f1SLei Zhang ///   |  |   <header code>                    |
1010930c74f1SLei Zhang ///   |  |   llvm.cond_br %cond, ^body, ^exit |
1011930c74f1SLei Zhang ///   |  +------------------------------------+
1012930c74f1SLei Zhang ///   |                    |
1013930c74f1SLei Zhang ///   |                    |----------------------+
1014930c74f1SLei Zhang ///   |                    |                      |
1015930c74f1SLei Zhang ///   |                    V                      |
1016930c74f1SLei Zhang ///   |  +------------------------------------+   |
1017930c74f1SLei Zhang ///   |  | ^body:                             |   |
1018930c74f1SLei Zhang ///   |  |   <body code>                      |   |
1019930c74f1SLei Zhang ///   |  |   llvm.br ^continue                |   |
1020930c74f1SLei Zhang ///   |  +------------------------------------+   |
1021930c74f1SLei Zhang ///   |                    |                      |
1022930c74f1SLei Zhang ///   |                    V                      |
1023930c74f1SLei Zhang ///   |  +------------------------------------+   |
1024930c74f1SLei Zhang ///   |  | ^continue:                         |   |
1025930c74f1SLei Zhang ///   |  |   <continue code>                  |   |
1026930c74f1SLei Zhang ///   |  |   llvm.br ^header                  |   |
1027930c74f1SLei Zhang ///   |  +------------------------------------+   |
1028930c74f1SLei Zhang ///   |               |                           |
1029930c74f1SLei Zhang ///   +---------------+    +----------------------+
1030930c74f1SLei Zhang ///                        |
1031930c74f1SLei Zhang ///                        V
1032930c74f1SLei Zhang ///      +------------------------------------+
1033930c74f1SLei Zhang ///      | ^exit:                             |
1034930c74f1SLei Zhang ///      |   llvm.br ^remaining               |
1035930c74f1SLei Zhang ///      +------------------------------------+
1036930c74f1SLei Zhang ///                        |
1037930c74f1SLei Zhang ///                        V
1038930c74f1SLei Zhang ///      +------------------------------------+
1039930c74f1SLei Zhang ///      | ^remaining:                        |
104029812a61SKareemErgawy-TomTom ///      |   <code after spv.mlir.loop>       |
1041930c74f1SLei Zhang ///      +------------------------------------+
1042930c74f1SLei Zhang ///
1043930c74f1SLei Zhang class LoopPattern : public SPIRVToLLVMConversion<spirv::LoopOp> {
1044930c74f1SLei Zhang public:
1045930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::LoopOp>::SPIRVToLLVMConversion;
1046930c74f1SLei Zhang 
1047930c74f1SLei Zhang   LogicalResult
1048b54c724bSRiver Riddle   matchAndRewrite(spirv::LoopOp loopOp, OpAdaptor adaptor,
1049930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
1050930c74f1SLei Zhang     // There is no support of loop control at the moment.
1051930c74f1SLei Zhang     if (loopOp.loop_control() != spirv::LoopControl::None)
1052930c74f1SLei Zhang       return failure();
1053930c74f1SLei Zhang 
1054930c74f1SLei Zhang     Location loc = loopOp.getLoc();
1055930c74f1SLei Zhang 
105629812a61SKareemErgawy-TomTom     // Split the current block after `spv.mlir.loop`. The remaining ops will be
105729812a61SKareemErgawy-TomTom     // used in `endBlock`.
1058930c74f1SLei Zhang     Block *currentBlock = rewriter.getBlock();
1059930c74f1SLei Zhang     auto position = Block::iterator(loopOp);
1060930c74f1SLei Zhang     Block *endBlock = rewriter.splitBlock(currentBlock, position);
1061930c74f1SLei Zhang 
1062930c74f1SLei Zhang     // Remove entry block and create a branch in the current block going to the
1063930c74f1SLei Zhang     // header block.
1064930c74f1SLei Zhang     Block *entryBlock = loopOp.getEntryBlock();
1065930c74f1SLei Zhang     assert(entryBlock->getOperations().size() == 1);
1066930c74f1SLei Zhang     auto brOp = dyn_cast<spirv::BranchOp>(entryBlock->getOperations().front());
1067930c74f1SLei Zhang     if (!brOp)
1068930c74f1SLei Zhang       return failure();
1069930c74f1SLei Zhang     Block *headerBlock = loopOp.getHeaderBlock();
1070930c74f1SLei Zhang     rewriter.setInsertionPointToEnd(currentBlock);
1071930c74f1SLei Zhang     rewriter.create<LLVM::BrOp>(loc, brOp.getBlockArguments(), headerBlock);
1072930c74f1SLei Zhang     rewriter.eraseBlock(entryBlock);
1073930c74f1SLei Zhang 
1074930c74f1SLei Zhang     // Branch from merge block to end block.
1075930c74f1SLei Zhang     Block *mergeBlock = loopOp.getMergeBlock();
1076930c74f1SLei Zhang     Operation *terminator = mergeBlock->getTerminator();
1077930c74f1SLei Zhang     ValueRange terminatorOperands = terminator->getOperands();
1078930c74f1SLei Zhang     rewriter.setInsertionPointToEnd(mergeBlock);
1079930c74f1SLei Zhang     rewriter.create<LLVM::BrOp>(loc, terminatorOperands, endBlock);
1080930c74f1SLei Zhang 
1081930c74f1SLei Zhang     rewriter.inlineRegionBefore(loopOp.body(), endBlock);
1082930c74f1SLei Zhang     rewriter.replaceOp(loopOp, endBlock->getArguments());
1083930c74f1SLei Zhang     return success();
1084930c74f1SLei Zhang   }
1085930c74f1SLei Zhang };
1086930c74f1SLei Zhang 
10873fb384d5SKareemErgawy-TomTom /// Converts `spv.mlir.selection` with `spv.BranchConditional` in its header
10883fb384d5SKareemErgawy-TomTom /// block. All blocks within selection should be reachable for conversion to
10893fb384d5SKareemErgawy-TomTom /// succeed.
1090930c74f1SLei Zhang class SelectionPattern : public SPIRVToLLVMConversion<spirv::SelectionOp> {
1091930c74f1SLei Zhang public:
1092930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::SelectionOp>::SPIRVToLLVMConversion;
1093930c74f1SLei Zhang 
1094930c74f1SLei Zhang   LogicalResult
1095b54c724bSRiver Riddle   matchAndRewrite(spirv::SelectionOp op, OpAdaptor adaptor,
1096930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
1097930c74f1SLei Zhang     // There is no support for `Flatten` or `DontFlatten` selection control at
1098930c74f1SLei Zhang     // the moment. This are just compiler hints and can be performed during the
1099930c74f1SLei Zhang     // optimization passes.
1100930c74f1SLei Zhang     if (op.selection_control() != spirv::SelectionControl::None)
1101930c74f1SLei Zhang       return failure();
1102930c74f1SLei Zhang 
11033fb384d5SKareemErgawy-TomTom     // `spv.mlir.selection` should have at least two blocks: one selection
11043fb384d5SKareemErgawy-TomTom     // header block and one merge block. If no blocks are present, or control
11053fb384d5SKareemErgawy-TomTom     // flow branches straight to merge block (two blocks are present), the op is
1106930c74f1SLei Zhang     // redundant and it is erased.
1107930c74f1SLei Zhang     if (op.body().getBlocks().size() <= 2) {
1108930c74f1SLei Zhang       rewriter.eraseOp(op);
1109930c74f1SLei Zhang       return success();
1110930c74f1SLei Zhang     }
1111930c74f1SLei Zhang 
1112930c74f1SLei Zhang     Location loc = op.getLoc();
1113930c74f1SLei Zhang 
11143fb384d5SKareemErgawy-TomTom     // Split the current block after `spv.mlir.selection`. The remaining ops
11153fb384d5SKareemErgawy-TomTom     // will be used in `continueBlock`.
1116930c74f1SLei Zhang     auto *currentBlock = rewriter.getInsertionBlock();
1117930c74f1SLei Zhang     rewriter.setInsertionPointAfter(op);
1118930c74f1SLei Zhang     auto position = rewriter.getInsertionPoint();
1119930c74f1SLei Zhang     auto *continueBlock = rewriter.splitBlock(currentBlock, position);
1120930c74f1SLei Zhang 
1121930c74f1SLei Zhang     // Extract conditional branch information from the header block. By SPIR-V
1122930c74f1SLei Zhang     // dialect spec, it should contain `spv.BranchConditional` or `spv.Switch`
1123930c74f1SLei Zhang     // op. Note that `spv.Switch op` is not supported at the moment in the
1124930c74f1SLei Zhang     // SPIR-V dialect. Remove this block when finished.
1125930c74f1SLei Zhang     auto *headerBlock = op.getHeaderBlock();
1126930c74f1SLei Zhang     assert(headerBlock->getOperations().size() == 1);
1127930c74f1SLei Zhang     auto condBrOp = dyn_cast<spirv::BranchConditionalOp>(
1128930c74f1SLei Zhang         headerBlock->getOperations().front());
1129930c74f1SLei Zhang     if (!condBrOp)
1130930c74f1SLei Zhang       return failure();
1131930c74f1SLei Zhang     rewriter.eraseBlock(headerBlock);
1132930c74f1SLei Zhang 
1133930c74f1SLei Zhang     // Branch from merge block to continue block.
1134930c74f1SLei Zhang     auto *mergeBlock = op.getMergeBlock();
1135930c74f1SLei Zhang     Operation *terminator = mergeBlock->getTerminator();
1136930c74f1SLei Zhang     ValueRange terminatorOperands = terminator->getOperands();
1137930c74f1SLei Zhang     rewriter.setInsertionPointToEnd(mergeBlock);
1138930c74f1SLei Zhang     rewriter.create<LLVM::BrOp>(loc, terminatorOperands, continueBlock);
1139930c74f1SLei Zhang 
1140930c74f1SLei Zhang     // Link current block to `true` and `false` blocks within the selection.
1141930c74f1SLei Zhang     Block *trueBlock = condBrOp.getTrueBlock();
1142930c74f1SLei Zhang     Block *falseBlock = condBrOp.getFalseBlock();
1143930c74f1SLei Zhang     rewriter.setInsertionPointToEnd(currentBlock);
1144930c74f1SLei Zhang     rewriter.create<LLVM::CondBrOp>(loc, condBrOp.condition(), trueBlock,
1145930c74f1SLei Zhang                                     condBrOp.trueTargetOperands(), falseBlock,
1146930c74f1SLei Zhang                                     condBrOp.falseTargetOperands());
1147930c74f1SLei Zhang 
1148930c74f1SLei Zhang     rewriter.inlineRegionBefore(op.body(), continueBlock);
1149930c74f1SLei Zhang     rewriter.replaceOp(op, continueBlock->getArguments());
1150930c74f1SLei Zhang     return success();
1151930c74f1SLei Zhang   }
1152930c74f1SLei Zhang };
1153930c74f1SLei Zhang 
1154930c74f1SLei Zhang /// Converts SPIR-V shift ops to LLVM shift ops. Since LLVM dialect
1155930c74f1SLei Zhang /// puts a restriction on `Shift` and `Base` to have the same bit width,
1156930c74f1SLei Zhang /// `Shift` is zero or sign extended to match this specification. Cases when
1157930c74f1SLei Zhang /// `Shift` bit width > `Base` bit width are considered to be illegal.
1158930c74f1SLei Zhang template <typename SPIRVOp, typename LLVMOp>
1159930c74f1SLei Zhang class ShiftPattern : public SPIRVToLLVMConversion<SPIRVOp> {
1160930c74f1SLei Zhang public:
1161930c74f1SLei Zhang   using SPIRVToLLVMConversion<SPIRVOp>::SPIRVToLLVMConversion;
1162930c74f1SLei Zhang 
1163930c74f1SLei Zhang   LogicalResult
1164b54c724bSRiver Riddle   matchAndRewrite(SPIRVOp operation, typename SPIRVOp::Adaptor adaptor,
1165930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
1166930c74f1SLei Zhang 
1167930c74f1SLei Zhang     auto dstType = this->typeConverter.convertType(operation.getType());
1168930c74f1SLei Zhang     if (!dstType)
1169930c74f1SLei Zhang       return failure();
1170930c74f1SLei Zhang 
1171930c74f1SLei Zhang     Type op1Type = operation.operand1().getType();
1172930c74f1SLei Zhang     Type op2Type = operation.operand2().getType();
1173930c74f1SLei Zhang 
1174930c74f1SLei Zhang     if (op1Type == op2Type) {
1175930c74f1SLei Zhang       rewriter.template replaceOpWithNewOp<LLVMOp>(operation, dstType,
1176b54c724bSRiver Riddle                                                    adaptor.getOperands());
1177930c74f1SLei Zhang       return success();
1178930c74f1SLei Zhang     }
1179930c74f1SLei Zhang 
1180930c74f1SLei Zhang     Location loc = operation.getLoc();
1181930c74f1SLei Zhang     Value extended;
1182930c74f1SLei Zhang     if (isUnsignedIntegerOrVector(op2Type)) {
1183930c74f1SLei Zhang       extended = rewriter.template create<LLVM::ZExtOp>(loc, dstType,
1184015192c6SRiver Riddle                                                         adaptor.operand2());
1185930c74f1SLei Zhang     } else {
1186930c74f1SLei Zhang       extended = rewriter.template create<LLVM::SExtOp>(loc, dstType,
1187015192c6SRiver Riddle                                                         adaptor.operand2());
1188930c74f1SLei Zhang     }
1189930c74f1SLei Zhang     Value result = rewriter.template create<LLVMOp>(
1190015192c6SRiver Riddle         loc, dstType, adaptor.operand1(), extended);
1191930c74f1SLei Zhang     rewriter.replaceOp(operation, result);
1192930c74f1SLei Zhang     return success();
1193930c74f1SLei Zhang   }
1194930c74f1SLei Zhang };
1195930c74f1SLei Zhang 
1196930c74f1SLei Zhang class TanPattern : public SPIRVToLLVMConversion<spirv::GLSLTanOp> {
1197930c74f1SLei Zhang public:
1198930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::GLSLTanOp>::SPIRVToLLVMConversion;
1199930c74f1SLei Zhang 
1200930c74f1SLei Zhang   LogicalResult
1201b54c724bSRiver Riddle   matchAndRewrite(spirv::GLSLTanOp tanOp, OpAdaptor adaptor,
1202930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
1203930c74f1SLei Zhang     auto dstType = typeConverter.convertType(tanOp.getType());
1204930c74f1SLei Zhang     if (!dstType)
1205930c74f1SLei Zhang       return failure();
1206930c74f1SLei Zhang 
1207930c74f1SLei Zhang     Location loc = tanOp.getLoc();
1208930c74f1SLei Zhang     Value sin = rewriter.create<LLVM::SinOp>(loc, dstType, tanOp.operand());
1209930c74f1SLei Zhang     Value cos = rewriter.create<LLVM::CosOp>(loc, dstType, tanOp.operand());
1210930c74f1SLei Zhang     rewriter.replaceOpWithNewOp<LLVM::FDivOp>(tanOp, dstType, sin, cos);
1211930c74f1SLei Zhang     return success();
1212930c74f1SLei Zhang   }
1213930c74f1SLei Zhang };
1214930c74f1SLei Zhang 
1215930c74f1SLei Zhang /// Convert `spv.Tanh` to
1216930c74f1SLei Zhang ///
1217930c74f1SLei Zhang ///   exp(2x) - 1
1218930c74f1SLei Zhang ///   -----------
1219930c74f1SLei Zhang ///   exp(2x) + 1
1220930c74f1SLei Zhang ///
1221930c74f1SLei Zhang class TanhPattern : public SPIRVToLLVMConversion<spirv::GLSLTanhOp> {
1222930c74f1SLei Zhang public:
1223930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::GLSLTanhOp>::SPIRVToLLVMConversion;
1224930c74f1SLei Zhang 
1225930c74f1SLei Zhang   LogicalResult
1226b54c724bSRiver Riddle   matchAndRewrite(spirv::GLSLTanhOp tanhOp, OpAdaptor adaptor,
1227930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
1228930c74f1SLei Zhang     auto srcType = tanhOp.getType();
1229930c74f1SLei Zhang     auto dstType = typeConverter.convertType(srcType);
1230930c74f1SLei Zhang     if (!dstType)
1231930c74f1SLei Zhang       return failure();
1232930c74f1SLei Zhang 
1233930c74f1SLei Zhang     Location loc = tanhOp.getLoc();
1234930c74f1SLei Zhang     Value two = createFPConstant(loc, srcType, dstType, rewriter, 2.0);
1235930c74f1SLei Zhang     Value multiplied =
1236930c74f1SLei Zhang         rewriter.create<LLVM::FMulOp>(loc, dstType, two, tanhOp.operand());
1237930c74f1SLei Zhang     Value exponential = rewriter.create<LLVM::ExpOp>(loc, dstType, multiplied);
1238930c74f1SLei Zhang     Value one = createFPConstant(loc, srcType, dstType, rewriter, 1.0);
1239930c74f1SLei Zhang     Value numerator =
1240930c74f1SLei Zhang         rewriter.create<LLVM::FSubOp>(loc, dstType, exponential, one);
1241930c74f1SLei Zhang     Value denominator =
1242930c74f1SLei Zhang         rewriter.create<LLVM::FAddOp>(loc, dstType, exponential, one);
1243930c74f1SLei Zhang     rewriter.replaceOpWithNewOp<LLVM::FDivOp>(tanhOp, dstType, numerator,
1244930c74f1SLei Zhang                                               denominator);
1245930c74f1SLei Zhang     return success();
1246930c74f1SLei Zhang   }
1247930c74f1SLei Zhang };
1248930c74f1SLei Zhang 
1249930c74f1SLei Zhang class VariablePattern : public SPIRVToLLVMConversion<spirv::VariableOp> {
1250930c74f1SLei Zhang public:
1251930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::VariableOp>::SPIRVToLLVMConversion;
1252930c74f1SLei Zhang 
1253930c74f1SLei Zhang   LogicalResult
1254b54c724bSRiver Riddle   matchAndRewrite(spirv::VariableOp varOp, OpAdaptor adaptor,
1255930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
1256930c74f1SLei Zhang     auto srcType = varOp.getType();
1257930c74f1SLei Zhang     // Initialization is supported for scalars and vectors only.
1258930c74f1SLei Zhang     auto pointerTo = srcType.cast<spirv::PointerType>().getPointeeType();
1259930c74f1SLei Zhang     auto init = varOp.initializer();
1260930c74f1SLei Zhang     if (init && !pointerTo.isIntOrFloat() && !pointerTo.isa<VectorType>())
1261930c74f1SLei Zhang       return failure();
1262930c74f1SLei Zhang 
1263930c74f1SLei Zhang     auto dstType = typeConverter.convertType(srcType);
1264930c74f1SLei Zhang     if (!dstType)
1265930c74f1SLei Zhang       return failure();
1266930c74f1SLei Zhang 
1267930c74f1SLei Zhang     Location loc = varOp.getLoc();
1268930c74f1SLei Zhang     Value size = createI32ConstantOf(loc, rewriter, 1);
1269930c74f1SLei Zhang     if (!init) {
1270930c74f1SLei Zhang       rewriter.replaceOpWithNewOp<LLVM::AllocaOp>(varOp, dstType, size);
1271930c74f1SLei Zhang       return success();
1272930c74f1SLei Zhang     }
1273930c74f1SLei Zhang     Value allocated = rewriter.create<LLVM::AllocaOp>(loc, dstType, size);
1274015192c6SRiver Riddle     rewriter.create<LLVM::StoreOp>(loc, adaptor.initializer(), allocated);
1275930c74f1SLei Zhang     rewriter.replaceOp(varOp, allocated);
1276930c74f1SLei Zhang     return success();
1277930c74f1SLei Zhang   }
1278930c74f1SLei Zhang };
1279930c74f1SLei Zhang 
1280930c74f1SLei Zhang //===----------------------------------------------------------------------===//
1281930c74f1SLei Zhang // FuncOp conversion
1282930c74f1SLei Zhang //===----------------------------------------------------------------------===//
1283930c74f1SLei Zhang 
1284930c74f1SLei Zhang class FuncConversionPattern : public SPIRVToLLVMConversion<spirv::FuncOp> {
1285930c74f1SLei Zhang public:
1286930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::FuncOp>::SPIRVToLLVMConversion;
1287930c74f1SLei Zhang 
1288930c74f1SLei Zhang   LogicalResult
1289b54c724bSRiver Riddle   matchAndRewrite(spirv::FuncOp funcOp, OpAdaptor adaptor,
1290930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
1291930c74f1SLei Zhang 
1292930c74f1SLei Zhang     // Convert function signature. At the moment LLVMType converter is enough
1293930c74f1SLei Zhang     // for currently supported types.
12944a3460a7SRiver Riddle     auto funcType = funcOp.getFunctionType();
1295930c74f1SLei Zhang     TypeConverter::SignatureConversion signatureConverter(
1296930c74f1SLei Zhang         funcType.getNumInputs());
1297930c74f1SLei Zhang     auto llvmType = typeConverter.convertFunctionSignature(
12984a3460a7SRiver Riddle         funcType, /*isVariadic=*/false, signatureConverter);
1299930c74f1SLei Zhang     if (!llvmType)
1300930c74f1SLei Zhang       return failure();
1301930c74f1SLei Zhang 
1302930c74f1SLei Zhang     // Create a new `LLVMFuncOp`
1303930c74f1SLei Zhang     Location loc = funcOp.getLoc();
1304930c74f1SLei Zhang     StringRef name = funcOp.getName();
1305930c74f1SLei Zhang     auto newFuncOp = rewriter.create<LLVM::LLVMFuncOp>(loc, name, llvmType);
1306930c74f1SLei Zhang 
1307930c74f1SLei Zhang     // Convert SPIR-V Function Control to equivalent LLVM function attribute
1308930c74f1SLei Zhang     MLIRContext *context = funcOp.getContext();
1309930c74f1SLei Zhang     switch (funcOp.function_control()) {
1310930c74f1SLei Zhang #define DISPATCH(functionControl, llvmAttr)                                    \
1311930c74f1SLei Zhang   case functionControl:                                                        \
1312c2c83e97STres Popp     newFuncOp->setAttr("passthrough", ArrayAttr::get(context, {llvmAttr}));    \
1313930c74f1SLei Zhang     break;
1314930c74f1SLei Zhang 
1315930c74f1SLei Zhang       DISPATCH(spirv::FunctionControl::Inline,
1316c2c83e97STres Popp                StringAttr::get(context, "alwaysinline"));
1317930c74f1SLei Zhang       DISPATCH(spirv::FunctionControl::DontInline,
1318c2c83e97STres Popp                StringAttr::get(context, "noinline"));
1319930c74f1SLei Zhang       DISPATCH(spirv::FunctionControl::Pure,
1320c2c83e97STres Popp                StringAttr::get(context, "readonly"));
1321930c74f1SLei Zhang       DISPATCH(spirv::FunctionControl::Const,
1322c2c83e97STres Popp                StringAttr::get(context, "readnone"));
1323930c74f1SLei Zhang 
1324930c74f1SLei Zhang #undef DISPATCH
1325930c74f1SLei Zhang 
1326930c74f1SLei Zhang     // Default: if `spirv::FunctionControl::None`, then no attributes are
1327930c74f1SLei Zhang     // needed.
1328930c74f1SLei Zhang     default:
1329930c74f1SLei Zhang       break;
1330930c74f1SLei Zhang     }
1331930c74f1SLei Zhang 
1332930c74f1SLei Zhang     rewriter.inlineRegionBefore(funcOp.getBody(), newFuncOp.getBody(),
1333930c74f1SLei Zhang                                 newFuncOp.end());
1334930c74f1SLei Zhang     if (failed(rewriter.convertRegionTypes(&newFuncOp.getBody(), typeConverter,
1335930c74f1SLei Zhang                                            &signatureConverter))) {
1336930c74f1SLei Zhang       return failure();
1337930c74f1SLei Zhang     }
1338930c74f1SLei Zhang     rewriter.eraseOp(funcOp);
1339930c74f1SLei Zhang     return success();
1340930c74f1SLei Zhang   }
1341930c74f1SLei Zhang };
1342930c74f1SLei Zhang 
1343930c74f1SLei Zhang //===----------------------------------------------------------------------===//
1344930c74f1SLei Zhang // ModuleOp conversion
1345930c74f1SLei Zhang //===----------------------------------------------------------------------===//
1346930c74f1SLei Zhang 
1347930c74f1SLei Zhang class ModuleConversionPattern : public SPIRVToLLVMConversion<spirv::ModuleOp> {
1348930c74f1SLei Zhang public:
1349930c74f1SLei Zhang   using SPIRVToLLVMConversion<spirv::ModuleOp>::SPIRVToLLVMConversion;
1350930c74f1SLei Zhang 
1351930c74f1SLei Zhang   LogicalResult
1352b54c724bSRiver Riddle   matchAndRewrite(spirv::ModuleOp spvModuleOp, OpAdaptor adaptor,
1353930c74f1SLei Zhang                   ConversionPatternRewriter &rewriter) const override {
1354930c74f1SLei Zhang 
1355930c74f1SLei Zhang     auto newModuleOp =
1356930c74f1SLei Zhang         rewriter.create<ModuleOp>(spvModuleOp.getLoc(), spvModuleOp.getName());
135756f60a1cSLei Zhang     rewriter.inlineRegionBefore(spvModuleOp.getRegion(), newModuleOp.getBody());
1358930c74f1SLei Zhang 
1359930c74f1SLei Zhang     // Remove the terminator block that was automatically added by builder
1360930c74f1SLei Zhang     rewriter.eraseBlock(&newModuleOp.getBodyRegion().back());
1361930c74f1SLei Zhang     rewriter.eraseOp(spvModuleOp);
1362930c74f1SLei Zhang     return success();
1363930c74f1SLei Zhang   }
1364930c74f1SLei Zhang };
1365930c74f1SLei Zhang 
13663483fc5aSWeiwei Li //===----------------------------------------------------------------------===//
13673483fc5aSWeiwei Li // VectorShuffleOp conversion
13683483fc5aSWeiwei Li //===----------------------------------------------------------------------===//
13693483fc5aSWeiwei Li 
13703483fc5aSWeiwei Li class VectorShufflePattern
13713483fc5aSWeiwei Li     : public SPIRVToLLVMConversion<spirv::VectorShuffleOp> {
13723483fc5aSWeiwei Li public:
13733483fc5aSWeiwei Li   using SPIRVToLLVMConversion<spirv::VectorShuffleOp>::SPIRVToLLVMConversion;
13743483fc5aSWeiwei Li   LogicalResult
13753483fc5aSWeiwei Li   matchAndRewrite(spirv::VectorShuffleOp op, OpAdaptor adaptor,
13763483fc5aSWeiwei Li                   ConversionPatternRewriter &rewriter) const override {
13773483fc5aSWeiwei Li     Location loc = op.getLoc();
13783483fc5aSWeiwei Li     auto components = adaptor.components();
13793483fc5aSWeiwei Li     auto vector1 = adaptor.vector1();
13803483fc5aSWeiwei Li     auto vector2 = adaptor.vector2();
13813483fc5aSWeiwei Li     int vector1Size = vector1.getType().cast<VectorType>().getNumElements();
13823483fc5aSWeiwei Li     int vector2Size = vector2.getType().cast<VectorType>().getNumElements();
13833483fc5aSWeiwei Li     if (vector1Size == vector2Size) {
13843483fc5aSWeiwei Li       rewriter.replaceOpWithNewOp<LLVM::ShuffleVectorOp>(op, vector1, vector2,
13853483fc5aSWeiwei Li                                                          components);
13863483fc5aSWeiwei Li       return success();
13873483fc5aSWeiwei Li     }
13883483fc5aSWeiwei Li 
13893483fc5aSWeiwei Li     auto dstType = typeConverter.convertType(op.getType());
13903483fc5aSWeiwei Li     auto scalarType = dstType.cast<VectorType>().getElementType();
13913483fc5aSWeiwei Li     auto componentsArray = components.getValue();
139202b6fb21SMehdi Amini     auto *context = rewriter.getContext();
13933483fc5aSWeiwei Li     auto llvmI32Type = IntegerType::get(context, 32);
13943483fc5aSWeiwei Li     Value targetOp = rewriter.create<LLVM::UndefOp>(loc, dstType);
13953483fc5aSWeiwei Li     for (unsigned i = 0; i < componentsArray.size(); i++) {
13963483fc5aSWeiwei Li       if (componentsArray[i].isa<IntegerAttr>())
13973483fc5aSWeiwei Li         op.emitError("unable to support non-constant component");
13983483fc5aSWeiwei Li 
13993483fc5aSWeiwei Li       int indexVal = componentsArray[i].cast<IntegerAttr>().getInt();
14003483fc5aSWeiwei Li       if (indexVal == -1)
14013483fc5aSWeiwei Li         continue;
14023483fc5aSWeiwei Li 
14033483fc5aSWeiwei Li       int offsetVal = 0;
14043483fc5aSWeiwei Li       Value baseVector = vector1;
14053483fc5aSWeiwei Li       if (indexVal >= vector1Size) {
14063483fc5aSWeiwei Li         offsetVal = vector1Size;
14073483fc5aSWeiwei Li         baseVector = vector2;
14083483fc5aSWeiwei Li       }
14093483fc5aSWeiwei Li 
14103483fc5aSWeiwei Li       Value dstIndex = rewriter.create<LLVM::ConstantOp>(
14113483fc5aSWeiwei Li           loc, llvmI32Type, rewriter.getIntegerAttr(rewriter.getI32Type(), i));
14123483fc5aSWeiwei Li       Value index = rewriter.create<LLVM::ConstantOp>(
14133483fc5aSWeiwei Li           loc, llvmI32Type,
14143483fc5aSWeiwei Li           rewriter.getIntegerAttr(rewriter.getI32Type(), indexVal - offsetVal));
14153483fc5aSWeiwei Li 
14163483fc5aSWeiwei Li       auto extractOp = rewriter.create<LLVM::ExtractElementOp>(
14173483fc5aSWeiwei Li           loc, scalarType, baseVector, index);
14183483fc5aSWeiwei Li       targetOp = rewriter.create<LLVM::InsertElementOp>(loc, dstType, targetOp,
14193483fc5aSWeiwei Li                                                         extractOp, dstIndex);
14203483fc5aSWeiwei Li     }
14213483fc5aSWeiwei Li     rewriter.replaceOp(op, targetOp);
14223483fc5aSWeiwei Li     return success();
14233483fc5aSWeiwei Li   }
14243483fc5aSWeiwei Li };
1425930c74f1SLei Zhang } // namespace
1426930c74f1SLei Zhang 
1427930c74f1SLei Zhang //===----------------------------------------------------------------------===//
1428930c74f1SLei Zhang // Pattern population
1429930c74f1SLei Zhang //===----------------------------------------------------------------------===//
1430930c74f1SLei Zhang 
1431930c74f1SLei Zhang void mlir::populateSPIRVToLLVMTypeConversion(LLVMTypeConverter &typeConverter) {
1432930c74f1SLei Zhang   typeConverter.addConversion([&](spirv::ArrayType type) {
1433930c74f1SLei Zhang     return convertArrayType(type, typeConverter);
1434930c74f1SLei Zhang   });
1435930c74f1SLei Zhang   typeConverter.addConversion([&](spirv::PointerType type) {
1436930c74f1SLei Zhang     return convertPointerType(type, typeConverter);
1437930c74f1SLei Zhang   });
1438930c74f1SLei Zhang   typeConverter.addConversion([&](spirv::RuntimeArrayType type) {
1439930c74f1SLei Zhang     return convertRuntimeArrayType(type, typeConverter);
1440930c74f1SLei Zhang   });
1441930c74f1SLei Zhang   typeConverter.addConversion([&](spirv::StructType type) {
1442930c74f1SLei Zhang     return convertStructType(type, typeConverter);
1443930c74f1SLei Zhang   });
1444930c74f1SLei Zhang }
1445930c74f1SLei Zhang 
1446930c74f1SLei Zhang void mlir::populateSPIRVToLLVMConversionPatterns(
1447dc4e913bSChris Lattner     LLVMTypeConverter &typeConverter, RewritePatternSet &patterns) {
1448dc4e913bSChris Lattner   patterns.add<
1449930c74f1SLei Zhang       // Arithmetic ops
1450930c74f1SLei Zhang       DirectConversionPattern<spirv::IAddOp, LLVM::AddOp>,
1451930c74f1SLei Zhang       DirectConversionPattern<spirv::IMulOp, LLVM::MulOp>,
1452930c74f1SLei Zhang       DirectConversionPattern<spirv::ISubOp, LLVM::SubOp>,
1453930c74f1SLei Zhang       DirectConversionPattern<spirv::FAddOp, LLVM::FAddOp>,
1454930c74f1SLei Zhang       DirectConversionPattern<spirv::FDivOp, LLVM::FDivOp>,
1455930c74f1SLei Zhang       DirectConversionPattern<spirv::FMulOp, LLVM::FMulOp>,
1456930c74f1SLei Zhang       DirectConversionPattern<spirv::FNegateOp, LLVM::FNegOp>,
1457930c74f1SLei Zhang       DirectConversionPattern<spirv::FRemOp, LLVM::FRemOp>,
1458930c74f1SLei Zhang       DirectConversionPattern<spirv::FSubOp, LLVM::FSubOp>,
1459930c74f1SLei Zhang       DirectConversionPattern<spirv::SDivOp, LLVM::SDivOp>,
1460930c74f1SLei Zhang       DirectConversionPattern<spirv::SRemOp, LLVM::SRemOp>,
1461930c74f1SLei Zhang       DirectConversionPattern<spirv::UDivOp, LLVM::UDivOp>,
1462930c74f1SLei Zhang       DirectConversionPattern<spirv::UModOp, LLVM::URemOp>,
1463930c74f1SLei Zhang 
1464930c74f1SLei Zhang       // Bitwise ops
1465930c74f1SLei Zhang       BitFieldInsertPattern, BitFieldUExtractPattern, BitFieldSExtractPattern,
1466930c74f1SLei Zhang       DirectConversionPattern<spirv::BitCountOp, LLVM::CtPopOp>,
1467930c74f1SLei Zhang       DirectConversionPattern<spirv::BitReverseOp, LLVM::BitReverseOp>,
1468930c74f1SLei Zhang       DirectConversionPattern<spirv::BitwiseAndOp, LLVM::AndOp>,
1469930c74f1SLei Zhang       DirectConversionPattern<spirv::BitwiseOrOp, LLVM::OrOp>,
1470930c74f1SLei Zhang       DirectConversionPattern<spirv::BitwiseXorOp, LLVM::XOrOp>,
1471930c74f1SLei Zhang       NotPattern<spirv::NotOp>,
1472930c74f1SLei Zhang 
1473930c74f1SLei Zhang       // Cast ops
1474930c74f1SLei Zhang       DirectConversionPattern<spirv::BitcastOp, LLVM::BitcastOp>,
1475930c74f1SLei Zhang       DirectConversionPattern<spirv::ConvertFToSOp, LLVM::FPToSIOp>,
1476930c74f1SLei Zhang       DirectConversionPattern<spirv::ConvertFToUOp, LLVM::FPToUIOp>,
1477930c74f1SLei Zhang       DirectConversionPattern<spirv::ConvertSToFOp, LLVM::SIToFPOp>,
1478930c74f1SLei Zhang       DirectConversionPattern<spirv::ConvertUToFOp, LLVM::UIToFPOp>,
1479930c74f1SLei Zhang       IndirectCastPattern<spirv::FConvertOp, LLVM::FPExtOp, LLVM::FPTruncOp>,
1480930c74f1SLei Zhang       IndirectCastPattern<spirv::SConvertOp, LLVM::SExtOp, LLVM::TruncOp>,
1481930c74f1SLei Zhang       IndirectCastPattern<spirv::UConvertOp, LLVM::ZExtOp, LLVM::TruncOp>,
1482930c74f1SLei Zhang 
1483930c74f1SLei Zhang       // Comparison ops
1484930c74f1SLei Zhang       IComparePattern<spirv::IEqualOp, LLVM::ICmpPredicate::eq>,
1485930c74f1SLei Zhang       IComparePattern<spirv::INotEqualOp, LLVM::ICmpPredicate::ne>,
1486930c74f1SLei Zhang       FComparePattern<spirv::FOrdEqualOp, LLVM::FCmpPredicate::oeq>,
1487930c74f1SLei Zhang       FComparePattern<spirv::FOrdGreaterThanOp, LLVM::FCmpPredicate::ogt>,
1488930c74f1SLei Zhang       FComparePattern<spirv::FOrdGreaterThanEqualOp, LLVM::FCmpPredicate::oge>,
1489930c74f1SLei Zhang       FComparePattern<spirv::FOrdLessThanEqualOp, LLVM::FCmpPredicate::ole>,
1490930c74f1SLei Zhang       FComparePattern<spirv::FOrdLessThanOp, LLVM::FCmpPredicate::olt>,
1491930c74f1SLei Zhang       FComparePattern<spirv::FOrdNotEqualOp, LLVM::FCmpPredicate::one>,
1492930c74f1SLei Zhang       FComparePattern<spirv::FUnordEqualOp, LLVM::FCmpPredicate::ueq>,
1493930c74f1SLei Zhang       FComparePattern<spirv::FUnordGreaterThanOp, LLVM::FCmpPredicate::ugt>,
1494930c74f1SLei Zhang       FComparePattern<spirv::FUnordGreaterThanEqualOp,
1495930c74f1SLei Zhang                       LLVM::FCmpPredicate::uge>,
1496930c74f1SLei Zhang       FComparePattern<spirv::FUnordLessThanEqualOp, LLVM::FCmpPredicate::ule>,
1497930c74f1SLei Zhang       FComparePattern<spirv::FUnordLessThanOp, LLVM::FCmpPredicate::ult>,
1498930c74f1SLei Zhang       FComparePattern<spirv::FUnordNotEqualOp, LLVM::FCmpPredicate::une>,
1499930c74f1SLei Zhang       IComparePattern<spirv::SGreaterThanOp, LLVM::ICmpPredicate::sgt>,
1500930c74f1SLei Zhang       IComparePattern<spirv::SGreaterThanEqualOp, LLVM::ICmpPredicate::sge>,
1501930c74f1SLei Zhang       IComparePattern<spirv::SLessThanEqualOp, LLVM::ICmpPredicate::sle>,
1502930c74f1SLei Zhang       IComparePattern<spirv::SLessThanOp, LLVM::ICmpPredicate::slt>,
1503930c74f1SLei Zhang       IComparePattern<spirv::UGreaterThanOp, LLVM::ICmpPredicate::ugt>,
1504930c74f1SLei Zhang       IComparePattern<spirv::UGreaterThanEqualOp, LLVM::ICmpPredicate::uge>,
1505930c74f1SLei Zhang       IComparePattern<spirv::ULessThanEqualOp, LLVM::ICmpPredicate::ule>,
1506930c74f1SLei Zhang       IComparePattern<spirv::ULessThanOp, LLVM::ICmpPredicate::ult>,
1507930c74f1SLei Zhang 
1508930c74f1SLei Zhang       // Constant op
1509930c74f1SLei Zhang       ConstantScalarAndVectorPattern,
1510930c74f1SLei Zhang 
1511930c74f1SLei Zhang       // Control Flow ops
1512930c74f1SLei Zhang       BranchConversionPattern, BranchConditionalConversionPattern,
1513930c74f1SLei Zhang       FunctionCallPattern, LoopPattern, SelectionPattern,
1514930c74f1SLei Zhang       ErasePattern<spirv::MergeOp>,
1515930c74f1SLei Zhang 
1516930c74f1SLei Zhang       // Entry points and execution mode are handled separately.
1517930c74f1SLei Zhang       ErasePattern<spirv::EntryPointOp>, ExecutionModePattern,
1518930c74f1SLei Zhang 
1519930c74f1SLei Zhang       // GLSL extended instruction set ops
1520930c74f1SLei Zhang       DirectConversionPattern<spirv::GLSLCeilOp, LLVM::FCeilOp>,
1521930c74f1SLei Zhang       DirectConversionPattern<spirv::GLSLCosOp, LLVM::CosOp>,
1522930c74f1SLei Zhang       DirectConversionPattern<spirv::GLSLExpOp, LLVM::ExpOp>,
1523930c74f1SLei Zhang       DirectConversionPattern<spirv::GLSLFAbsOp, LLVM::FAbsOp>,
1524930c74f1SLei Zhang       DirectConversionPattern<spirv::GLSLFloorOp, LLVM::FFloorOp>,
1525930c74f1SLei Zhang       DirectConversionPattern<spirv::GLSLFMaxOp, LLVM::MaxNumOp>,
1526930c74f1SLei Zhang       DirectConversionPattern<spirv::GLSLFMinOp, LLVM::MinNumOp>,
1527930c74f1SLei Zhang       DirectConversionPattern<spirv::GLSLLogOp, LLVM::LogOp>,
1528930c74f1SLei Zhang       DirectConversionPattern<spirv::GLSLSinOp, LLVM::SinOp>,
1529930c74f1SLei Zhang       DirectConversionPattern<spirv::GLSLSMaxOp, LLVM::SMaxOp>,
1530930c74f1SLei Zhang       DirectConversionPattern<spirv::GLSLSMinOp, LLVM::SMinOp>,
1531930c74f1SLei Zhang       DirectConversionPattern<spirv::GLSLSqrtOp, LLVM::SqrtOp>,
1532930c74f1SLei Zhang       InverseSqrtPattern, TanPattern, TanhPattern,
1533930c74f1SLei Zhang 
1534930c74f1SLei Zhang       // Logical ops
1535930c74f1SLei Zhang       DirectConversionPattern<spirv::LogicalAndOp, LLVM::AndOp>,
1536930c74f1SLei Zhang       DirectConversionPattern<spirv::LogicalOrOp, LLVM::OrOp>,
1537930c74f1SLei Zhang       IComparePattern<spirv::LogicalEqualOp, LLVM::ICmpPredicate::eq>,
1538930c74f1SLei Zhang       IComparePattern<spirv::LogicalNotEqualOp, LLVM::ICmpPredicate::ne>,
1539930c74f1SLei Zhang       NotPattern<spirv::LogicalNotOp>,
1540930c74f1SLei Zhang 
1541930c74f1SLei Zhang       // Memory ops
1542930c74f1SLei Zhang       AccessChainPattern, AddressOfPattern, GlobalVariablePattern,
1543930c74f1SLei Zhang       LoadStorePattern<spirv::LoadOp>, LoadStorePattern<spirv::StoreOp>,
1544930c74f1SLei Zhang       VariablePattern,
1545930c74f1SLei Zhang 
1546930c74f1SLei Zhang       // Miscellaneous ops
1547930c74f1SLei Zhang       CompositeExtractPattern, CompositeInsertPattern,
1548930c74f1SLei Zhang       DirectConversionPattern<spirv::SelectOp, LLVM::SelectOp>,
1549930c74f1SLei Zhang       DirectConversionPattern<spirv::UndefOp, LLVM::UndefOp>,
15503483fc5aSWeiwei Li       VectorShufflePattern,
1551930c74f1SLei Zhang 
1552930c74f1SLei Zhang       // Shift ops
1553930c74f1SLei Zhang       ShiftPattern<spirv::ShiftRightArithmeticOp, LLVM::AShrOp>,
1554930c74f1SLei Zhang       ShiftPattern<spirv::ShiftRightLogicalOp, LLVM::LShrOp>,
1555930c74f1SLei Zhang       ShiftPattern<spirv::ShiftLeftLogicalOp, LLVM::ShlOp>,
1556930c74f1SLei Zhang 
1557930c74f1SLei Zhang       // Return ops
15583a506b31SChris Lattner       ReturnPattern, ReturnValuePattern>(patterns.getContext(), typeConverter);
1559930c74f1SLei Zhang }
1560930c74f1SLei Zhang 
1561930c74f1SLei Zhang void mlir::populateSPIRVToLLVMFunctionConversionPatterns(
1562dc4e913bSChris Lattner     LLVMTypeConverter &typeConverter, RewritePatternSet &patterns) {
1563dc4e913bSChris Lattner   patterns.add<FuncConversionPattern>(patterns.getContext(), typeConverter);
1564930c74f1SLei Zhang }
1565930c74f1SLei Zhang 
1566930c74f1SLei Zhang void mlir::populateSPIRVToLLVMModuleConversionPatterns(
1567dc4e913bSChris Lattner     LLVMTypeConverter &typeConverter, RewritePatternSet &patterns) {
156856f60a1cSLei Zhang   patterns.add<ModuleConversionPattern>(patterns.getContext(), typeConverter);
1569930c74f1SLei Zhang }
1570930c74f1SLei Zhang 
1571930c74f1SLei Zhang //===----------------------------------------------------------------------===//
1572930c74f1SLei Zhang // Pre-conversion hooks
1573930c74f1SLei Zhang //===----------------------------------------------------------------------===//
1574930c74f1SLei Zhang 
1575930c74f1SLei Zhang /// Hook for descriptor set and binding number encoding.
1576930c74f1SLei Zhang static constexpr StringRef kBinding = "binding";
1577930c74f1SLei Zhang static constexpr StringRef kDescriptorSet = "descriptor_set";
1578930c74f1SLei Zhang void mlir::encodeBindAttribute(ModuleOp module) {
1579930c74f1SLei Zhang   auto spvModules = module.getOps<spirv::ModuleOp>();
1580930c74f1SLei Zhang   for (auto spvModule : spvModules) {
1581930c74f1SLei Zhang     spvModule.walk([&](spirv::GlobalVariableOp op) {
1582930c74f1SLei Zhang       IntegerAttr descriptorSet =
1583930c74f1SLei Zhang           op->getAttrOfType<IntegerAttr>(kDescriptorSet);
1584930c74f1SLei Zhang       IntegerAttr binding = op->getAttrOfType<IntegerAttr>(kBinding);
1585930c74f1SLei Zhang       // For every global variable in the module, get the ones with descriptor
1586930c74f1SLei Zhang       // set and binding numbers.
1587930c74f1SLei Zhang       if (descriptorSet && binding) {
1588930c74f1SLei Zhang         // Encode these numbers into the variable's symbolic name. If the
1589930c74f1SLei Zhang         // SPIR-V module has a name, add it at the beginning.
1590930c74f1SLei Zhang         auto moduleAndName = spvModule.getName().hasValue()
1591930c74f1SLei Zhang                                  ? spvModule.getName().getValue().str() + "_" +
1592930c74f1SLei Zhang                                        op.sym_name().str()
1593930c74f1SLei Zhang                                  : op.sym_name().str();
1594930c74f1SLei Zhang         std::string name =
1595930c74f1SLei Zhang             llvm::formatv("{0}_descriptor_set{1}_binding{2}", moduleAndName,
1596930c74f1SLei Zhang                           std::to_string(descriptorSet.getInt()),
1597930c74f1SLei Zhang                           std::to_string(binding.getInt()));
159841d4aa7dSChris Lattner         auto nameAttr = StringAttr::get(op->getContext(), name);
1599930c74f1SLei Zhang 
1600930c74f1SLei Zhang         // Replace all symbol uses and set the new symbol name. Finally, remove
1601930c74f1SLei Zhang         // descriptor set and binding attributes.
160241d4aa7dSChris Lattner         if (failed(SymbolTable::replaceAllSymbolUses(op, nameAttr, spvModule)))
1603930c74f1SLei Zhang           op.emitError("unable to replace all symbol uses for ") << name;
160441d4aa7dSChris Lattner         SymbolTable::setSymbolName(op, nameAttr);
1605dffc487bSChristian Sigg         op->removeAttr(kDescriptorSet);
1606dffc487bSChristian Sigg         op->removeAttr(kBinding);
1607930c74f1SLei Zhang       }
1608930c74f1SLei Zhang     });
1609930c74f1SLei Zhang   }
1610930c74f1SLei Zhang }
1611