1 //===- SPIRVOps.cpp - MLIR SPIR-V operations ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the operations in the SPIR-V dialect.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
14 
15 #include "mlir/Dialect/SPIRV/IR/ParserUtils.h"
16 #include "mlir/Dialect/SPIRV/IR/SPIRVAttributes.h"
17 #include "mlir/Dialect/SPIRV/IR/SPIRVDialect.h"
18 #include "mlir/Dialect/SPIRV/IR/SPIRVOpTraits.h"
19 #include "mlir/Dialect/SPIRV/IR/SPIRVTypes.h"
20 #include "mlir/Dialect/SPIRV/IR/TargetAndABI.h"
21 #include "mlir/IR/Builders.h"
22 #include "mlir/IR/BuiltinOps.h"
23 #include "mlir/IR/BuiltinTypes.h"
24 #include "mlir/IR/FunctionImplementation.h"
25 #include "mlir/IR/OpDefinition.h"
26 #include "mlir/IR/OpImplementation.h"
27 #include "mlir/IR/TypeUtilities.h"
28 #include "mlir/Interfaces/CallInterfaces.h"
29 #include "llvm/ADT/APFloat.h"
30 #include "llvm/ADT/APInt.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/bit.h"
33 
34 using namespace mlir;
35 
36 // TODO: generate these strings using ODS.
37 static constexpr const char kMemoryAccessAttrName[] = "memory_access";
38 static constexpr const char kSourceMemoryAccessAttrName[] =
39     "source_memory_access";
40 static constexpr const char kAlignmentAttrName[] = "alignment";
41 static constexpr const char kSourceAlignmentAttrName[] = "source_alignment";
42 static constexpr const char kBranchWeightAttrName[] = "branch_weights";
43 static constexpr const char kCallee[] = "callee";
44 static constexpr const char kClusterSize[] = "cluster_size";
45 static constexpr const char kControl[] = "control";
46 static constexpr const char kDefaultValueAttrName[] = "default_value";
47 static constexpr const char kExecutionScopeAttrName[] = "execution_scope";
48 static constexpr const char kEqualSemanticsAttrName[] = "equal_semantics";
49 static constexpr const char kFnNameAttrName[] = "fn";
50 static constexpr const char kGroupOperationAttrName[] = "group_operation";
51 static constexpr const char kIndicesAttrName[] = "indices";
52 static constexpr const char kInitializerAttrName[] = "initializer";
53 static constexpr const char kInterfaceAttrName[] = "interface";
54 static constexpr const char kMemoryScopeAttrName[] = "memory_scope";
55 static constexpr const char kSemanticsAttrName[] = "semantics";
56 static constexpr const char kSpecIdAttrName[] = "spec_id";
57 static constexpr const char kTypeAttrName[] = "type";
58 static constexpr const char kUnequalSemanticsAttrName[] = "unequal_semantics";
59 static constexpr const char kValueAttrName[] = "value";
60 static constexpr const char kValuesAttrName[] = "values";
61 static constexpr const char kCompositeSpecConstituentsName[] = "constituents";
62 
63 //===----------------------------------------------------------------------===//
64 // Common utility functions
65 //===----------------------------------------------------------------------===//
66 
67 static ParseResult parseOneResultSameOperandTypeOp(OpAsmParser &parser,
68                                                    OperationState &result) {
69   SmallVector<OpAsmParser::UnresolvedOperand, 2> ops;
70   Type type;
71   // If the operand list is in-between parentheses, then we have a generic form.
72   // (see the fallback in `printOneResultOp`).
73   SMLoc loc = parser.getCurrentLocation();
74   if (!parser.parseOptionalLParen()) {
75     if (parser.parseOperandList(ops) || parser.parseRParen() ||
76         parser.parseOptionalAttrDict(result.attributes) ||
77         parser.parseColon() || parser.parseType(type))
78       return failure();
79     auto fnType = type.dyn_cast<FunctionType>();
80     if (!fnType) {
81       parser.emitError(loc, "expected function type");
82       return failure();
83     }
84     if (parser.resolveOperands(ops, fnType.getInputs(), loc, result.operands))
85       return failure();
86     result.addTypes(fnType.getResults());
87     return success();
88   }
89   return failure(parser.parseOperandList(ops) ||
90                  parser.parseOptionalAttrDict(result.attributes) ||
91                  parser.parseColonType(type) ||
92                  parser.resolveOperands(ops, type, result.operands) ||
93                  parser.addTypeToList(type, result.types));
94 }
95 
96 static void printOneResultOp(Operation *op, OpAsmPrinter &p) {
97   assert(op->getNumResults() == 1 && "op should have one result");
98 
99   // If not all the operand and result types are the same, just use the
100   // generic assembly form to avoid omitting information in printing.
101   auto resultType = op->getResult(0).getType();
102   if (llvm::any_of(op->getOperandTypes(),
103                    [&](Type type) { return type != resultType; })) {
104     p.printGenericOp(op, /*printOpName=*/false);
105     return;
106   }
107 
108   p << ' ';
109   p.printOperands(op->getOperands());
110   p.printOptionalAttrDict(op->getAttrs());
111   // Now we can output only one type for all operands and the result.
112   p << " : " << resultType;
113 }
114 
115 /// Returns true if the given op is a function-like op or nested in a
116 /// function-like op without a module-like op in the middle.
117 static bool isNestedInFunctionOpInterface(Operation *op) {
118   if (!op)
119     return false;
120   if (op->hasTrait<OpTrait::SymbolTable>())
121     return false;
122   if (isa<FunctionOpInterface>(op))
123     return true;
124   return isNestedInFunctionOpInterface(op->getParentOp());
125 }
126 
127 /// Returns true if the given op is an module-like op that maintains a symbol
128 /// table.
129 static bool isDirectInModuleLikeOp(Operation *op) {
130   return op && op->hasTrait<OpTrait::SymbolTable>();
131 }
132 
133 static LogicalResult extractValueFromConstOp(Operation *op, int32_t &value) {
134   auto constOp = dyn_cast_or_null<spirv::ConstantOp>(op);
135   if (!constOp) {
136     return failure();
137   }
138   auto valueAttr = constOp.value();
139   auto integerValueAttr = valueAttr.dyn_cast<IntegerAttr>();
140   if (!integerValueAttr) {
141     return failure();
142   }
143 
144   if (integerValueAttr.getType().isSignlessInteger())
145     value = integerValueAttr.getInt();
146   else
147     value = integerValueAttr.getSInt();
148 
149   return success();
150 }
151 
152 template <typename Ty>
153 static ArrayAttr
154 getStrArrayAttrForEnumList(Builder &builder, ArrayRef<Ty> enumValues,
155                            function_ref<StringRef(Ty)> stringifyFn) {
156   if (enumValues.empty()) {
157     return nullptr;
158   }
159   SmallVector<StringRef, 1> enumValStrs;
160   enumValStrs.reserve(enumValues.size());
161   for (auto val : enumValues) {
162     enumValStrs.emplace_back(stringifyFn(val));
163   }
164   return builder.getStrArrayAttr(enumValStrs);
165 }
166 
167 /// Parses the next string attribute in `parser` as an enumerant of the given
168 /// `EnumClass`.
169 template <typename EnumClass>
170 static ParseResult
171 parseEnumStrAttr(EnumClass &value, OpAsmParser &parser,
172                  StringRef attrName = spirv::attributeName<EnumClass>()) {
173   Attribute attrVal;
174   NamedAttrList attr;
175   auto loc = parser.getCurrentLocation();
176   if (parser.parseAttribute(attrVal, parser.getBuilder().getNoneType(),
177                             attrName, attr)) {
178     return failure();
179   }
180   if (!attrVal.isa<StringAttr>()) {
181     return parser.emitError(loc, "expected ")
182            << attrName << " attribute specified as string";
183   }
184   auto attrOptional =
185       spirv::symbolizeEnum<EnumClass>(attrVal.cast<StringAttr>().getValue());
186   if (!attrOptional) {
187     return parser.emitError(loc, "invalid ")
188            << attrName << " attribute specification: " << attrVal;
189   }
190   value = attrOptional.getValue();
191   return success();
192 }
193 
194 /// Parses the next string attribute in `parser` as an enumerant of the given
195 /// `EnumClass` and inserts the enumerant into `state` as an 32-bit integer
196 /// attribute with the enum class's name as attribute name.
197 template <typename EnumClass>
198 static ParseResult
199 parseEnumStrAttr(EnumClass &value, OpAsmParser &parser, OperationState &state,
200                  StringRef attrName = spirv::attributeName<EnumClass>()) {
201   if (parseEnumStrAttr(value, parser)) {
202     return failure();
203   }
204   state.addAttribute(attrName, parser.getBuilder().getI32IntegerAttr(
205                                    llvm::bit_cast<int32_t>(value)));
206   return success();
207 }
208 
209 /// Parses the next keyword in `parser` as an enumerant of the given `EnumClass`
210 /// and inserts the enumerant into `state` as an 32-bit integer attribute with
211 /// the enum class's name as attribute name.
212 template <typename EnumClass>
213 static ParseResult
214 parseEnumKeywordAttr(EnumClass &value, OpAsmParser &parser,
215                      OperationState &state,
216                      StringRef attrName = spirv::attributeName<EnumClass>()) {
217   if (parseEnumKeywordAttr(value, parser)) {
218     return failure();
219   }
220   state.addAttribute(attrName, parser.getBuilder().getI32IntegerAttr(
221                                    llvm::bit_cast<int32_t>(value)));
222   return success();
223 }
224 
225 /// Parses Function, Selection and Loop control attributes. If no control is
226 /// specified, "None" is used as a default.
227 template <typename EnumClass>
228 static ParseResult
229 parseControlAttribute(OpAsmParser &parser, OperationState &state,
230                       StringRef attrName = spirv::attributeName<EnumClass>()) {
231   if (succeeded(parser.parseOptionalKeyword(kControl))) {
232     EnumClass control;
233     if (parser.parseLParen() || parseEnumKeywordAttr(control, parser, state) ||
234         parser.parseRParen())
235       return failure();
236     return success();
237   }
238   // Set control to "None" otherwise.
239   Builder builder = parser.getBuilder();
240   state.addAttribute(attrName, builder.getI32IntegerAttr(0));
241   return success();
242 }
243 
244 /// Parses optional memory access attributes attached to a memory access
245 /// operand/pointer. Specifically, parses the following syntax:
246 ///     (`[` memory-access `]`)?
247 /// where:
248 ///     memory-access ::= `"None"` | `"Volatile"` | `"Aligned", `
249 ///         integer-literal | `"NonTemporal"`
250 static ParseResult parseMemoryAccessAttributes(OpAsmParser &parser,
251                                                OperationState &state) {
252   // Parse an optional list of attributes staring with '['
253   if (parser.parseOptionalLSquare()) {
254     // Nothing to do
255     return success();
256   }
257 
258   spirv::MemoryAccess memoryAccessAttr;
259   if (parseEnumStrAttr(memoryAccessAttr, parser, state,
260                        kMemoryAccessAttrName)) {
261     return failure();
262   }
263 
264   if (spirv::bitEnumContains(memoryAccessAttr, spirv::MemoryAccess::Aligned)) {
265     // Parse integer attribute for alignment.
266     Attribute alignmentAttr;
267     Type i32Type = parser.getBuilder().getIntegerType(32);
268     if (parser.parseComma() ||
269         parser.parseAttribute(alignmentAttr, i32Type, kAlignmentAttrName,
270                               state.attributes)) {
271       return failure();
272     }
273   }
274   return parser.parseRSquare();
275 }
276 
277 // TODO Make sure to merge this and the previous function into one template
278 // parameterized by memory access attribute name and alignment. Doing so now
279 // results in VS2017 in producing an internal error (at the call site) that's
280 // not detailed enough to understand what is happening.
281 static ParseResult parseSourceMemoryAccessAttributes(OpAsmParser &parser,
282                                                      OperationState &state) {
283   // Parse an optional list of attributes staring with '['
284   if (parser.parseOptionalLSquare()) {
285     // Nothing to do
286     return success();
287   }
288 
289   spirv::MemoryAccess memoryAccessAttr;
290   if (parseEnumStrAttr(memoryAccessAttr, parser, state,
291                        kSourceMemoryAccessAttrName)) {
292     return failure();
293   }
294 
295   if (spirv::bitEnumContains(memoryAccessAttr, spirv::MemoryAccess::Aligned)) {
296     // Parse integer attribute for alignment.
297     Attribute alignmentAttr;
298     Type i32Type = parser.getBuilder().getIntegerType(32);
299     if (parser.parseComma() ||
300         parser.parseAttribute(alignmentAttr, i32Type, kSourceAlignmentAttrName,
301                               state.attributes)) {
302       return failure();
303     }
304   }
305   return parser.parseRSquare();
306 }
307 
308 template <typename MemoryOpTy>
309 static void printMemoryAccessAttribute(
310     MemoryOpTy memoryOp, OpAsmPrinter &printer,
311     SmallVectorImpl<StringRef> &elidedAttrs,
312     Optional<spirv::MemoryAccess> memoryAccessAtrrValue = None,
313     Optional<uint32_t> alignmentAttrValue = None) {
314   // Print optional memory access attribute.
315   if (auto memAccess = (memoryAccessAtrrValue ? memoryAccessAtrrValue
316                                               : memoryOp.memory_access())) {
317     elidedAttrs.push_back(kMemoryAccessAttrName);
318 
319     printer << " [\"" << stringifyMemoryAccess(*memAccess) << "\"";
320 
321     if (spirv::bitEnumContains(*memAccess, spirv::MemoryAccess::Aligned)) {
322       // Print integer alignment attribute.
323       if (auto alignment = (alignmentAttrValue ? alignmentAttrValue
324                                                : memoryOp.alignment())) {
325         elidedAttrs.push_back(kAlignmentAttrName);
326         printer << ", " << alignment;
327       }
328     }
329     printer << "]";
330   }
331   elidedAttrs.push_back(spirv::attributeName<spirv::StorageClass>());
332 }
333 
334 // TODO Make sure to merge this and the previous function into one template
335 // parameterized by memory access attribute name and alignment. Doing so now
336 // results in VS2017 in producing an internal error (at the call site) that's
337 // not detailed enough to understand what is happening.
338 template <typename MemoryOpTy>
339 static void printSourceMemoryAccessAttribute(
340     MemoryOpTy memoryOp, OpAsmPrinter &printer,
341     SmallVectorImpl<StringRef> &elidedAttrs,
342     Optional<spirv::MemoryAccess> memoryAccessAtrrValue = None,
343     Optional<uint32_t> alignmentAttrValue = None) {
344 
345   printer << ", ";
346 
347   // Print optional memory access attribute.
348   if (auto memAccess = (memoryAccessAtrrValue ? memoryAccessAtrrValue
349                                               : memoryOp.memory_access())) {
350     elidedAttrs.push_back(kSourceMemoryAccessAttrName);
351 
352     printer << " [\"" << stringifyMemoryAccess(*memAccess) << "\"";
353 
354     if (spirv::bitEnumContains(*memAccess, spirv::MemoryAccess::Aligned)) {
355       // Print integer alignment attribute.
356       if (auto alignment = (alignmentAttrValue ? alignmentAttrValue
357                                                : memoryOp.alignment())) {
358         elidedAttrs.push_back(kSourceAlignmentAttrName);
359         printer << ", " << alignment;
360       }
361     }
362     printer << "]";
363   }
364   elidedAttrs.push_back(spirv::attributeName<spirv::StorageClass>());
365 }
366 
367 static ParseResult parseImageOperands(OpAsmParser &parser,
368                                       spirv::ImageOperandsAttr &attr) {
369   // Expect image operands
370   if (parser.parseOptionalLSquare())
371     return success();
372 
373   spirv::ImageOperands imageOperands;
374   if (parseEnumStrAttr(imageOperands, parser))
375     return failure();
376 
377   attr = spirv::ImageOperandsAttr::get(parser.getContext(), imageOperands);
378 
379   return parser.parseRSquare();
380 }
381 
382 static void printImageOperands(OpAsmPrinter &printer, Operation *imageOp,
383                                spirv::ImageOperandsAttr attr) {
384   if (attr) {
385     auto strImageOperands = stringifyImageOperands(attr.getValue());
386     printer << "[\"" << strImageOperands << "\"]";
387   }
388 }
389 
390 template <typename Op>
391 static LogicalResult verifyImageOperands(Op imageOp,
392                                          spirv::ImageOperandsAttr attr,
393                                          Operation::operand_range operands) {
394   if (!attr) {
395     if (operands.empty())
396       return success();
397 
398     return imageOp.emitError("the Image Operands should encode what operands "
399                              "follow, as per Image Operands");
400   }
401 
402   // TODO: Add the validation rules for the following Image Operands.
403   spirv::ImageOperands noSupportOperands =
404       spirv::ImageOperands::Bias | spirv::ImageOperands::Lod |
405       spirv::ImageOperands::Grad | spirv::ImageOperands::ConstOffset |
406       spirv::ImageOperands::Offset | spirv::ImageOperands::ConstOffsets |
407       spirv::ImageOperands::Sample | spirv::ImageOperands::MinLod |
408       spirv::ImageOperands::MakeTexelAvailable |
409       spirv::ImageOperands::MakeTexelVisible |
410       spirv::ImageOperands::SignExtend | spirv::ImageOperands::ZeroExtend;
411 
412   if (spirv::bitEnumContains(attr.getValue(), noSupportOperands))
413     llvm_unreachable("unimplemented operands of Image Operands");
414 
415   return success();
416 }
417 
418 static LogicalResult verifyCastOp(Operation *op,
419                                   bool requireSameBitWidth = true,
420                                   bool skipBitWidthCheck = false) {
421   // Some CastOps have no limit on bit widths for result and operand type.
422   if (skipBitWidthCheck)
423     return success();
424 
425   Type operandType = op->getOperand(0).getType();
426   Type resultType = op->getResult(0).getType();
427 
428   // ODS checks that result type and operand type have the same shape.
429   if (auto vectorType = operandType.dyn_cast<VectorType>()) {
430     operandType = vectorType.getElementType();
431     resultType = resultType.cast<VectorType>().getElementType();
432   }
433 
434   if (auto coopMatrixType =
435           operandType.dyn_cast<spirv::CooperativeMatrixNVType>()) {
436     operandType = coopMatrixType.getElementType();
437     resultType =
438         resultType.cast<spirv::CooperativeMatrixNVType>().getElementType();
439   }
440 
441   auto operandTypeBitWidth = operandType.getIntOrFloatBitWidth();
442   auto resultTypeBitWidth = resultType.getIntOrFloatBitWidth();
443   auto isSameBitWidth = operandTypeBitWidth == resultTypeBitWidth;
444 
445   if (requireSameBitWidth) {
446     if (!isSameBitWidth) {
447       return op->emitOpError(
448                  "expected the same bit widths for operand type and result "
449                  "type, but provided ")
450              << operandType << " and " << resultType;
451     }
452     return success();
453   }
454 
455   if (isSameBitWidth) {
456     return op->emitOpError(
457                "expected the different bit widths for operand type and result "
458                "type, but provided ")
459            << operandType << " and " << resultType;
460   }
461   return success();
462 }
463 
464 template <typename MemoryOpTy>
465 static LogicalResult verifyMemoryAccessAttribute(MemoryOpTy memoryOp) {
466   // ODS checks for attributes values. Just need to verify that if the
467   // memory-access attribute is Aligned, then the alignment attribute must be
468   // present.
469   auto *op = memoryOp.getOperation();
470   auto memAccessAttr = op->getAttr(kMemoryAccessAttrName);
471   if (!memAccessAttr) {
472     // Alignment attribute shouldn't be present if memory access attribute is
473     // not present.
474     if (op->getAttr(kAlignmentAttrName)) {
475       return memoryOp.emitOpError(
476           "invalid alignment specification without aligned memory access "
477           "specification");
478     }
479     return success();
480   }
481 
482   auto memAccessVal = memAccessAttr.template cast<IntegerAttr>();
483   auto memAccess = spirv::symbolizeMemoryAccess(memAccessVal.getInt());
484 
485   if (!memAccess) {
486     return memoryOp.emitOpError("invalid memory access specifier: ")
487            << memAccessVal;
488   }
489 
490   if (spirv::bitEnumContains(*memAccess, spirv::MemoryAccess::Aligned)) {
491     if (!op->getAttr(kAlignmentAttrName)) {
492       return memoryOp.emitOpError("missing alignment value");
493     }
494   } else {
495     if (op->getAttr(kAlignmentAttrName)) {
496       return memoryOp.emitOpError(
497           "invalid alignment specification with non-aligned memory access "
498           "specification");
499     }
500   }
501   return success();
502 }
503 
504 // TODO Make sure to merge this and the previous function into one template
505 // parameterized by memory access attribute name and alignment. Doing so now
506 // results in VS2017 in producing an internal error (at the call site) that's
507 // not detailed enough to understand what is happening.
508 template <typename MemoryOpTy>
509 static LogicalResult verifySourceMemoryAccessAttribute(MemoryOpTy memoryOp) {
510   // ODS checks for attributes values. Just need to verify that if the
511   // memory-access attribute is Aligned, then the alignment attribute must be
512   // present.
513   auto *op = memoryOp.getOperation();
514   auto memAccessAttr = op->getAttr(kSourceMemoryAccessAttrName);
515   if (!memAccessAttr) {
516     // Alignment attribute shouldn't be present if memory access attribute is
517     // not present.
518     if (op->getAttr(kSourceAlignmentAttrName)) {
519       return memoryOp.emitOpError(
520           "invalid alignment specification without aligned memory access "
521           "specification");
522     }
523     return success();
524   }
525 
526   auto memAccessVal = memAccessAttr.template cast<IntegerAttr>();
527   auto memAccess = spirv::symbolizeMemoryAccess(memAccessVal.getInt());
528 
529   if (!memAccess) {
530     return memoryOp.emitOpError("invalid memory access specifier: ")
531            << memAccessVal;
532   }
533 
534   if (spirv::bitEnumContains(*memAccess, spirv::MemoryAccess::Aligned)) {
535     if (!op->getAttr(kSourceAlignmentAttrName)) {
536       return memoryOp.emitOpError("missing alignment value");
537     }
538   } else {
539     if (op->getAttr(kSourceAlignmentAttrName)) {
540       return memoryOp.emitOpError(
541           "invalid alignment specification with non-aligned memory access "
542           "specification");
543     }
544   }
545   return success();
546 }
547 
548 static LogicalResult
549 verifyMemorySemantics(Operation *op, spirv::MemorySemantics memorySemantics) {
550   // According to the SPIR-V specification:
551   // "Despite being a mask and allowing multiple bits to be combined, it is
552   // invalid for more than one of these four bits to be set: Acquire, Release,
553   // AcquireRelease, or SequentiallyConsistent. Requesting both Acquire and
554   // Release semantics is done by setting the AcquireRelease bit, not by setting
555   // two bits."
556   auto atMostOneInSet = spirv::MemorySemantics::Acquire |
557                         spirv::MemorySemantics::Release |
558                         spirv::MemorySemantics::AcquireRelease |
559                         spirv::MemorySemantics::SequentiallyConsistent;
560 
561   auto bitCount = llvm::countPopulation(
562       static_cast<uint32_t>(memorySemantics & atMostOneInSet));
563   if (bitCount > 1) {
564     return op->emitError(
565         "expected at most one of these four memory constraints "
566         "to be set: `Acquire`, `Release`,"
567         "`AcquireRelease` or `SequentiallyConsistent`");
568   }
569   return success();
570 }
571 
572 template <typename LoadStoreOpTy>
573 static LogicalResult verifyLoadStorePtrAndValTypes(LoadStoreOpTy op, Value ptr,
574                                                    Value val) {
575   // ODS already checks ptr is spirv::PointerType. Just check that the pointee
576   // type of the pointer and the type of the value are the same
577   //
578   // TODO: Check that the value type satisfies restrictions of
579   // SPIR-V OpLoad/OpStore operations
580   if (val.getType() !=
581       ptr.getType().cast<spirv::PointerType>().getPointeeType()) {
582     return op.emitOpError("mismatch in result type and pointer type");
583   }
584   return success();
585 }
586 
587 template <typename BlockReadWriteOpTy>
588 static LogicalResult verifyBlockReadWritePtrAndValTypes(BlockReadWriteOpTy op,
589                                                         Value ptr, Value val) {
590   auto valType = val.getType();
591   if (auto valVecTy = valType.dyn_cast<VectorType>())
592     valType = valVecTy.getElementType();
593 
594   if (valType != ptr.getType().cast<spirv::PointerType>().getPointeeType()) {
595     return op.emitOpError("mismatch in result type and pointer type");
596   }
597   return success();
598 }
599 
600 static ParseResult parseVariableDecorations(OpAsmParser &parser,
601                                             OperationState &state) {
602   auto builtInName = llvm::convertToSnakeFromCamelCase(
603       stringifyDecoration(spirv::Decoration::BuiltIn));
604   if (succeeded(parser.parseOptionalKeyword("bind"))) {
605     Attribute set, binding;
606     // Parse optional descriptor binding
607     auto descriptorSetName = llvm::convertToSnakeFromCamelCase(
608         stringifyDecoration(spirv::Decoration::DescriptorSet));
609     auto bindingName = llvm::convertToSnakeFromCamelCase(
610         stringifyDecoration(spirv::Decoration::Binding));
611     Type i32Type = parser.getBuilder().getIntegerType(32);
612     if (parser.parseLParen() ||
613         parser.parseAttribute(set, i32Type, descriptorSetName,
614                               state.attributes) ||
615         parser.parseComma() ||
616         parser.parseAttribute(binding, i32Type, bindingName,
617                               state.attributes) ||
618         parser.parseRParen()) {
619       return failure();
620     }
621   } else if (succeeded(parser.parseOptionalKeyword(builtInName))) {
622     StringAttr builtIn;
623     if (parser.parseLParen() ||
624         parser.parseAttribute(builtIn, builtInName, state.attributes) ||
625         parser.parseRParen()) {
626       return failure();
627     }
628   }
629 
630   // Parse other attributes
631   if (parser.parseOptionalAttrDict(state.attributes))
632     return failure();
633 
634   return success();
635 }
636 
637 static void printVariableDecorations(Operation *op, OpAsmPrinter &printer,
638                                      SmallVectorImpl<StringRef> &elidedAttrs) {
639   // Print optional descriptor binding
640   auto descriptorSetName = llvm::convertToSnakeFromCamelCase(
641       stringifyDecoration(spirv::Decoration::DescriptorSet));
642   auto bindingName = llvm::convertToSnakeFromCamelCase(
643       stringifyDecoration(spirv::Decoration::Binding));
644   auto descriptorSet = op->getAttrOfType<IntegerAttr>(descriptorSetName);
645   auto binding = op->getAttrOfType<IntegerAttr>(bindingName);
646   if (descriptorSet && binding) {
647     elidedAttrs.push_back(descriptorSetName);
648     elidedAttrs.push_back(bindingName);
649     printer << " bind(" << descriptorSet.getInt() << ", " << binding.getInt()
650             << ")";
651   }
652 
653   // Print BuiltIn attribute if present
654   auto builtInName = llvm::convertToSnakeFromCamelCase(
655       stringifyDecoration(spirv::Decoration::BuiltIn));
656   if (auto builtin = op->getAttrOfType<StringAttr>(builtInName)) {
657     printer << " " << builtInName << "(\"" << builtin.getValue() << "\")";
658     elidedAttrs.push_back(builtInName);
659   }
660 
661   printer.printOptionalAttrDict(op->getAttrs(), elidedAttrs);
662 }
663 
664 // Get bit width of types.
665 static unsigned getBitWidth(Type type) {
666   if (type.isa<spirv::PointerType>()) {
667     // Just return 64 bits for pointer types for now.
668     // TODO: Make sure not caller relies on the actual pointer width value.
669     return 64;
670   }
671 
672   if (type.isIntOrFloat())
673     return type.getIntOrFloatBitWidth();
674 
675   if (auto vectorType = type.dyn_cast<VectorType>()) {
676     assert(vectorType.getElementType().isIntOrFloat());
677     return vectorType.getNumElements() *
678            vectorType.getElementType().getIntOrFloatBitWidth();
679   }
680   llvm_unreachable("unhandled bit width computation for type");
681 }
682 
683 /// Walks the given type hierarchy with the given indices, potentially down
684 /// to component granularity, to select an element type. Returns null type and
685 /// emits errors with the given loc on failure.
686 static Type
687 getElementType(Type type, ArrayRef<int32_t> indices,
688                function_ref<InFlightDiagnostic(StringRef)> emitErrorFn) {
689   if (indices.empty()) {
690     emitErrorFn("expected at least one index for spv.CompositeExtract");
691     return nullptr;
692   }
693 
694   for (auto index : indices) {
695     if (auto cType = type.dyn_cast<spirv::CompositeType>()) {
696       if (cType.hasCompileTimeKnownNumElements() &&
697           (index < 0 ||
698            static_cast<uint64_t>(index) >= cType.getNumElements())) {
699         emitErrorFn("index ") << index << " out of bounds for " << type;
700         return nullptr;
701       }
702       type = cType.getElementType(index);
703     } else {
704       emitErrorFn("cannot extract from non-composite type ")
705           << type << " with index " << index;
706       return nullptr;
707     }
708   }
709   return type;
710 }
711 
712 static Type
713 getElementType(Type type, Attribute indices,
714                function_ref<InFlightDiagnostic(StringRef)> emitErrorFn) {
715   auto indicesArrayAttr = indices.dyn_cast<ArrayAttr>();
716   if (!indicesArrayAttr) {
717     emitErrorFn("expected a 32-bit integer array attribute for 'indices'");
718     return nullptr;
719   }
720   if (indicesArrayAttr.empty()) {
721     emitErrorFn("expected at least one index for spv.CompositeExtract");
722     return nullptr;
723   }
724 
725   SmallVector<int32_t, 2> indexVals;
726   for (auto indexAttr : indicesArrayAttr) {
727     auto indexIntAttr = indexAttr.dyn_cast<IntegerAttr>();
728     if (!indexIntAttr) {
729       emitErrorFn("expected an 32-bit integer for index, but found '")
730           << indexAttr << "'";
731       return nullptr;
732     }
733     indexVals.push_back(indexIntAttr.getInt());
734   }
735   return getElementType(type, indexVals, emitErrorFn);
736 }
737 
738 static Type getElementType(Type type, Attribute indices, Location loc) {
739   auto errorFn = [&](StringRef err) -> InFlightDiagnostic {
740     return ::mlir::emitError(loc, err);
741   };
742   return getElementType(type, indices, errorFn);
743 }
744 
745 static Type getElementType(Type type, Attribute indices, OpAsmParser &parser,
746                            SMLoc loc) {
747   auto errorFn = [&](StringRef err) -> InFlightDiagnostic {
748     return parser.emitError(loc, err);
749   };
750   return getElementType(type, indices, errorFn);
751 }
752 
753 /// Returns true if the given `block` only contains one `spv.mlir.merge` op.
754 static inline bool isMergeBlock(Block &block) {
755   return !block.empty() && std::next(block.begin()) == block.end() &&
756          isa<spirv::MergeOp>(block.front());
757 }
758 
759 //===----------------------------------------------------------------------===//
760 // Common parsers and printers
761 //===----------------------------------------------------------------------===//
762 
763 // Parses an atomic update op. If the update op does not take a value (like
764 // AtomicIIncrement) `hasValue` must be false.
765 static ParseResult parseAtomicUpdateOp(OpAsmParser &parser,
766                                        OperationState &state, bool hasValue) {
767   spirv::Scope scope;
768   spirv::MemorySemantics memoryScope;
769   SmallVector<OpAsmParser::UnresolvedOperand, 2> operandInfo;
770   OpAsmParser::UnresolvedOperand ptrInfo, valueInfo;
771   Type type;
772   SMLoc loc;
773   if (parseEnumStrAttr(scope, parser, state, kMemoryScopeAttrName) ||
774       parseEnumStrAttr(memoryScope, parser, state, kSemanticsAttrName) ||
775       parser.parseOperandList(operandInfo, (hasValue ? 2 : 1)) ||
776       parser.getCurrentLocation(&loc) || parser.parseColonType(type))
777     return failure();
778 
779   auto ptrType = type.dyn_cast<spirv::PointerType>();
780   if (!ptrType)
781     return parser.emitError(loc, "expected pointer type");
782 
783   SmallVector<Type, 2> operandTypes;
784   operandTypes.push_back(ptrType);
785   if (hasValue)
786     operandTypes.push_back(ptrType.getPointeeType());
787   if (parser.resolveOperands(operandInfo, operandTypes, parser.getNameLoc(),
788                              state.operands))
789     return failure();
790   return parser.addTypeToList(ptrType.getPointeeType(), state.types);
791 }
792 
793 // Prints an atomic update op.
794 static void printAtomicUpdateOp(Operation *op, OpAsmPrinter &printer) {
795   printer << " \"";
796   auto scopeAttr = op->getAttrOfType<IntegerAttr>(kMemoryScopeAttrName);
797   printer << spirv::stringifyScope(
798                  static_cast<spirv::Scope>(scopeAttr.getInt()))
799           << "\" \"";
800   auto memorySemanticsAttr = op->getAttrOfType<IntegerAttr>(kSemanticsAttrName);
801   printer << spirv::stringifyMemorySemantics(
802                  static_cast<spirv::MemorySemantics>(
803                      memorySemanticsAttr.getInt()))
804           << "\" " << op->getOperands() << " : " << op->getOperand(0).getType();
805 }
806 
807 template <typename T>
808 static StringRef stringifyTypeName();
809 
810 template <>
811 StringRef stringifyTypeName<IntegerType>() {
812   return "integer";
813 }
814 
815 template <>
816 StringRef stringifyTypeName<FloatType>() {
817   return "float";
818 }
819 
820 // Verifies an atomic update op.
821 template <typename ExpectedElementType>
822 static LogicalResult verifyAtomicUpdateOp(Operation *op) {
823   auto ptrType = op->getOperand(0).getType().cast<spirv::PointerType>();
824   auto elementType = ptrType.getPointeeType();
825   if (!elementType.isa<ExpectedElementType>())
826     return op->emitOpError() << "pointer operand must point to an "
827                              << stringifyTypeName<ExpectedElementType>()
828                              << " value, found " << elementType;
829 
830   if (op->getNumOperands() > 1) {
831     auto valueType = op->getOperand(1).getType();
832     if (valueType != elementType)
833       return op->emitOpError("expected value to have the same type as the "
834                              "pointer operand's pointee type ")
835              << elementType << ", but found " << valueType;
836   }
837   auto memorySemantics = static_cast<spirv::MemorySemantics>(
838       op->getAttrOfType<IntegerAttr>(kSemanticsAttrName).getInt());
839   if (failed(verifyMemorySemantics(op, memorySemantics))) {
840     return failure();
841   }
842   return success();
843 }
844 
845 static ParseResult parseGroupNonUniformArithmeticOp(OpAsmParser &parser,
846                                                     OperationState &state) {
847   spirv::Scope executionScope;
848   spirv::GroupOperation groupOperation;
849   OpAsmParser::UnresolvedOperand valueInfo;
850   if (parseEnumStrAttr(executionScope, parser, state,
851                        kExecutionScopeAttrName) ||
852       parseEnumStrAttr(groupOperation, parser, state,
853                        kGroupOperationAttrName) ||
854       parser.parseOperand(valueInfo))
855     return failure();
856 
857   Optional<OpAsmParser::UnresolvedOperand> clusterSizeInfo;
858   if (succeeded(parser.parseOptionalKeyword(kClusterSize))) {
859     clusterSizeInfo = OpAsmParser::UnresolvedOperand();
860     if (parser.parseLParen() || parser.parseOperand(*clusterSizeInfo) ||
861         parser.parseRParen())
862       return failure();
863   }
864 
865   Type resultType;
866   if (parser.parseColonType(resultType))
867     return failure();
868 
869   if (parser.resolveOperand(valueInfo, resultType, state.operands))
870     return failure();
871 
872   if (clusterSizeInfo.hasValue()) {
873     Type i32Type = parser.getBuilder().getIntegerType(32);
874     if (parser.resolveOperand(*clusterSizeInfo, i32Type, state.operands))
875       return failure();
876   }
877 
878   return parser.addTypeToList(resultType, state.types);
879 }
880 
881 static void printGroupNonUniformArithmeticOp(Operation *groupOp,
882                                              OpAsmPrinter &printer) {
883   printer << " \""
884           << stringifyScope(static_cast<spirv::Scope>(
885                  groupOp->getAttrOfType<IntegerAttr>(kExecutionScopeAttrName)
886                      .getInt()))
887           << "\" \""
888           << stringifyGroupOperation(static_cast<spirv::GroupOperation>(
889                  groupOp->getAttrOfType<IntegerAttr>(kGroupOperationAttrName)
890                      .getInt()))
891           << "\" " << groupOp->getOperand(0);
892 
893   if (groupOp->getNumOperands() > 1)
894     printer << " " << kClusterSize << '(' << groupOp->getOperand(1) << ')';
895   printer << " : " << groupOp->getResult(0).getType();
896 }
897 
898 static LogicalResult verifyGroupNonUniformArithmeticOp(Operation *groupOp) {
899   spirv::Scope scope = static_cast<spirv::Scope>(
900       groupOp->getAttrOfType<IntegerAttr>(kExecutionScopeAttrName).getInt());
901   if (scope != spirv::Scope::Workgroup && scope != spirv::Scope::Subgroup)
902     return groupOp->emitOpError(
903         "execution scope must be 'Workgroup' or 'Subgroup'");
904 
905   spirv::GroupOperation operation = static_cast<spirv::GroupOperation>(
906       groupOp->getAttrOfType<IntegerAttr>(kGroupOperationAttrName).getInt());
907   if (operation == spirv::GroupOperation::ClusteredReduce &&
908       groupOp->getNumOperands() == 1)
909     return groupOp->emitOpError("cluster size operand must be provided for "
910                                 "'ClusteredReduce' group operation");
911   if (groupOp->getNumOperands() > 1) {
912     Operation *sizeOp = groupOp->getOperand(1).getDefiningOp();
913     int32_t clusterSize = 0;
914 
915     // TODO: support specialization constant here.
916     if (failed(extractValueFromConstOp(sizeOp, clusterSize)))
917       return groupOp->emitOpError(
918           "cluster size operand must come from a constant op");
919 
920     if (!llvm::isPowerOf2_32(clusterSize))
921       return groupOp->emitOpError(
922           "cluster size operand must be a power of two");
923   }
924   return success();
925 }
926 
927 /// Result of a logical op must be a scalar or vector of boolean type.
928 static Type getUnaryOpResultType(Type operandType) {
929   Builder builder(operandType.getContext());
930   Type resultType = builder.getIntegerType(1);
931   if (auto vecType = operandType.dyn_cast<VectorType>())
932     return VectorType::get(vecType.getNumElements(), resultType);
933   return resultType;
934 }
935 
936 static LogicalResult verifyShiftOp(Operation *op) {
937   if (op->getOperand(0).getType() != op->getResult(0).getType()) {
938     return op->emitError("expected the same type for the first operand and "
939                          "result, but provided ")
940            << op->getOperand(0).getType() << " and "
941            << op->getResult(0).getType();
942   }
943   return success();
944 }
945 
946 static void buildLogicalBinaryOp(OpBuilder &builder, OperationState &state,
947                                  Value lhs, Value rhs) {
948   assert(lhs.getType() == rhs.getType());
949 
950   Type boolType = builder.getI1Type();
951   if (auto vecType = lhs.getType().dyn_cast<VectorType>())
952     boolType = VectorType::get(vecType.getShape(), boolType);
953   state.addTypes(boolType);
954 
955   state.addOperands({lhs, rhs});
956 }
957 
958 static void buildLogicalUnaryOp(OpBuilder &builder, OperationState &state,
959                                 Value value) {
960   Type boolType = builder.getI1Type();
961   if (auto vecType = value.getType().dyn_cast<VectorType>())
962     boolType = VectorType::get(vecType.getShape(), boolType);
963   state.addTypes(boolType);
964 
965   state.addOperands(value);
966 }
967 
968 //===----------------------------------------------------------------------===//
969 // spv.AccessChainOp
970 //===----------------------------------------------------------------------===//
971 
972 static Type getElementPtrType(Type type, ValueRange indices, Location baseLoc) {
973   auto ptrType = type.dyn_cast<spirv::PointerType>();
974   if (!ptrType) {
975     emitError(baseLoc, "'spv.AccessChain' op expected a pointer "
976                        "to composite type, but provided ")
977         << type;
978     return nullptr;
979   }
980 
981   auto resultType = ptrType.getPointeeType();
982   auto resultStorageClass = ptrType.getStorageClass();
983   int32_t index = 0;
984 
985   for (auto indexSSA : indices) {
986     auto cType = resultType.dyn_cast<spirv::CompositeType>();
987     if (!cType) {
988       emitError(baseLoc,
989                 "'spv.AccessChain' op cannot extract from non-composite type ")
990           << resultType << " with index " << index;
991       return nullptr;
992     }
993     index = 0;
994     if (resultType.isa<spirv::StructType>()) {
995       Operation *op = indexSSA.getDefiningOp();
996       if (!op) {
997         emitError(baseLoc, "'spv.AccessChain' op index must be an "
998                            "integer spv.Constant to access "
999                            "element of spv.struct");
1000         return nullptr;
1001       }
1002 
1003       // TODO: this should be relaxed to allow
1004       // integer literals of other bitwidths.
1005       if (failed(extractValueFromConstOp(op, index))) {
1006         emitError(baseLoc,
1007                   "'spv.AccessChain' index must be an integer spv.Constant to "
1008                   "access element of spv.struct, but provided ")
1009             << op->getName();
1010         return nullptr;
1011       }
1012       if (index < 0 || static_cast<uint64_t>(index) >= cType.getNumElements()) {
1013         emitError(baseLoc, "'spv.AccessChain' op index ")
1014             << index << " out of bounds for " << resultType;
1015         return nullptr;
1016       }
1017     }
1018     resultType = cType.getElementType(index);
1019   }
1020   return spirv::PointerType::get(resultType, resultStorageClass);
1021 }
1022 
1023 void spirv::AccessChainOp::build(OpBuilder &builder, OperationState &state,
1024                                  Value basePtr, ValueRange indices) {
1025   auto type = getElementPtrType(basePtr.getType(), indices, state.location);
1026   assert(type && "Unable to deduce return type based on basePtr and indices");
1027   build(builder, state, type, basePtr, indices);
1028 }
1029 
1030 ParseResult spirv::AccessChainOp::parse(OpAsmParser &parser,
1031                                         OperationState &state) {
1032   OpAsmParser::UnresolvedOperand ptrInfo;
1033   SmallVector<OpAsmParser::UnresolvedOperand, 4> indicesInfo;
1034   Type type;
1035   auto loc = parser.getCurrentLocation();
1036   SmallVector<Type, 4> indicesTypes;
1037 
1038   if (parser.parseOperand(ptrInfo) ||
1039       parser.parseOperandList(indicesInfo, OpAsmParser::Delimiter::Square) ||
1040       parser.parseColonType(type) ||
1041       parser.resolveOperand(ptrInfo, type, state.operands)) {
1042     return failure();
1043   }
1044 
1045   // Check that the provided indices list is not empty before parsing their
1046   // type list.
1047   if (indicesInfo.empty()) {
1048     return mlir::emitError(state.location, "'spv.AccessChain' op expected at "
1049                                            "least one index ");
1050   }
1051 
1052   if (parser.parseComma() || parser.parseTypeList(indicesTypes))
1053     return failure();
1054 
1055   // Check that the indices types list is not empty and that it has a one-to-one
1056   // mapping to the provided indices.
1057   if (indicesTypes.size() != indicesInfo.size()) {
1058     return mlir::emitError(state.location,
1059                            "'spv.AccessChain' op indices types' count must be "
1060                            "equal to indices info count");
1061   }
1062 
1063   if (parser.resolveOperands(indicesInfo, indicesTypes, loc, state.operands))
1064     return failure();
1065 
1066   auto resultType = getElementPtrType(
1067       type, llvm::makeArrayRef(state.operands).drop_front(), state.location);
1068   if (!resultType) {
1069     return failure();
1070   }
1071 
1072   state.addTypes(resultType);
1073   return success();
1074 }
1075 
1076 template <typename Op>
1077 static void printAccessChain(Op op, ValueRange indices, OpAsmPrinter &printer) {
1078   printer << ' ' << op.base_ptr() << '[' << indices
1079           << "] : " << op.base_ptr().getType() << ", " << indices.getTypes();
1080 }
1081 
1082 void spirv::AccessChainOp::print(OpAsmPrinter &printer) {
1083   printAccessChain(*this, indices(), printer);
1084 }
1085 
1086 template <typename Op>
1087 static LogicalResult verifyAccessChain(Op accessChainOp, ValueRange indices) {
1088   auto resultType = getElementPtrType(accessChainOp.base_ptr().getType(),
1089                                       indices, accessChainOp.getLoc());
1090   if (!resultType)
1091     return failure();
1092 
1093   auto providedResultType =
1094       accessChainOp.getType().template dyn_cast<spirv::PointerType>();
1095   if (!providedResultType)
1096     return accessChainOp.emitOpError(
1097                "result type must be a pointer, but provided")
1098            << providedResultType;
1099 
1100   if (resultType != providedResultType)
1101     return accessChainOp.emitOpError("invalid result type: expected ")
1102            << resultType << ", but provided " << providedResultType;
1103 
1104   return success();
1105 }
1106 
1107 LogicalResult spirv::AccessChainOp::verify() {
1108   return verifyAccessChain(*this, indices());
1109 }
1110 
1111 //===----------------------------------------------------------------------===//
1112 // spv.mlir.addressof
1113 //===----------------------------------------------------------------------===//
1114 
1115 void spirv::AddressOfOp::build(OpBuilder &builder, OperationState &state,
1116                                spirv::GlobalVariableOp var) {
1117   build(builder, state, var.type(), SymbolRefAttr::get(var));
1118 }
1119 
1120 LogicalResult spirv::AddressOfOp::verify() {
1121   auto varOp = dyn_cast_or_null<spirv::GlobalVariableOp>(
1122       SymbolTable::lookupNearestSymbolFrom((*this)->getParentOp(),
1123                                            variableAttr()));
1124   if (!varOp) {
1125     return emitOpError("expected spv.GlobalVariable symbol");
1126   }
1127   if (pointer().getType() != varOp.type()) {
1128     return emitOpError(
1129         "result type mismatch with the referenced global variable's type");
1130   }
1131   return success();
1132 }
1133 
1134 template <typename T>
1135 static void printAtomicCompareExchangeImpl(T atomOp, OpAsmPrinter &printer) {
1136   printer << " \"" << stringifyScope(atomOp.memory_scope()) << "\" \""
1137           << stringifyMemorySemantics(atomOp.equal_semantics()) << "\" \""
1138           << stringifyMemorySemantics(atomOp.unequal_semantics()) << "\" "
1139           << atomOp.getOperands() << " : " << atomOp.pointer().getType();
1140 }
1141 
1142 static ParseResult parseAtomicCompareExchangeImpl(OpAsmParser &parser,
1143                                                   OperationState &state) {
1144   spirv::Scope memoryScope;
1145   spirv::MemorySemantics equalSemantics, unequalSemantics;
1146   SmallVector<OpAsmParser::UnresolvedOperand, 3> operandInfo;
1147   Type type;
1148   if (parseEnumStrAttr(memoryScope, parser, state, kMemoryScopeAttrName) ||
1149       parseEnumStrAttr(equalSemantics, parser, state,
1150                        kEqualSemanticsAttrName) ||
1151       parseEnumStrAttr(unequalSemantics, parser, state,
1152                        kUnequalSemanticsAttrName) ||
1153       parser.parseOperandList(operandInfo, 3))
1154     return failure();
1155 
1156   auto loc = parser.getCurrentLocation();
1157   if (parser.parseColonType(type))
1158     return failure();
1159 
1160   auto ptrType = type.dyn_cast<spirv::PointerType>();
1161   if (!ptrType)
1162     return parser.emitError(loc, "expected pointer type");
1163 
1164   if (parser.resolveOperands(
1165           operandInfo,
1166           {ptrType, ptrType.getPointeeType(), ptrType.getPointeeType()},
1167           parser.getNameLoc(), state.operands))
1168     return failure();
1169 
1170   return parser.addTypeToList(ptrType.getPointeeType(), state.types);
1171 }
1172 
1173 template <typename T>
1174 static LogicalResult verifyAtomicCompareExchangeImpl(T atomOp) {
1175   // According to the spec:
1176   // "The type of Value must be the same as Result Type. The type of the value
1177   // pointed to by Pointer must be the same as Result Type. This type must also
1178   // match the type of Comparator."
1179   if (atomOp.getType() != atomOp.value().getType())
1180     return atomOp.emitOpError("value operand must have the same type as the op "
1181                               "result, but found ")
1182            << atomOp.value().getType() << " vs " << atomOp.getType();
1183 
1184   if (atomOp.getType() != atomOp.comparator().getType())
1185     return atomOp.emitOpError(
1186                "comparator operand must have the same type as the op "
1187                "result, but found ")
1188            << atomOp.comparator().getType() << " vs " << atomOp.getType();
1189 
1190   Type pointeeType = atomOp.pointer()
1191                          .getType()
1192                          .template cast<spirv::PointerType>()
1193                          .getPointeeType();
1194   if (atomOp.getType() != pointeeType)
1195     return atomOp.emitOpError(
1196                "pointer operand's pointee type must have the same "
1197                "as the op result type, but found ")
1198            << pointeeType << " vs " << atomOp.getType();
1199 
1200   // TODO: Unequal cannot be set to Release or Acquire and Release.
1201   // In addition, Unequal cannot be set to a stronger memory-order then Equal.
1202 
1203   return success();
1204 }
1205 
1206 //===----------------------------------------------------------------------===//
1207 // spv.AtomicAndOp
1208 //===----------------------------------------------------------------------===//
1209 
1210 LogicalResult spirv::AtomicAndOp::verify() {
1211   return ::verifyAtomicUpdateOp<IntegerType>(getOperation());
1212 }
1213 
1214 ParseResult spirv::AtomicAndOp::parse(OpAsmParser &parser,
1215                                       OperationState &result) {
1216   return ::parseAtomicUpdateOp(parser, result, true);
1217 }
1218 void spirv::AtomicAndOp::print(OpAsmPrinter &p) {
1219   ::printAtomicUpdateOp(*this, p);
1220 }
1221 
1222 //===----------------------------------------------------------------------===//
1223 // spv.AtomicCompareExchangeOp
1224 //===----------------------------------------------------------------------===//
1225 
1226 LogicalResult spirv::AtomicCompareExchangeOp::verify() {
1227   return ::verifyAtomicCompareExchangeImpl(*this);
1228 }
1229 
1230 ParseResult spirv::AtomicCompareExchangeOp::parse(OpAsmParser &parser,
1231                                                   OperationState &result) {
1232   return ::parseAtomicCompareExchangeImpl(parser, result);
1233 }
1234 void spirv::AtomicCompareExchangeOp::print(OpAsmPrinter &p) {
1235   ::printAtomicCompareExchangeImpl(*this, p);
1236 }
1237 
1238 //===----------------------------------------------------------------------===//
1239 // spv.AtomicCompareExchangeWeakOp
1240 //===----------------------------------------------------------------------===//
1241 
1242 LogicalResult spirv::AtomicCompareExchangeWeakOp::verify() {
1243   return ::verifyAtomicCompareExchangeImpl(*this);
1244 }
1245 
1246 ParseResult spirv::AtomicCompareExchangeWeakOp::parse(OpAsmParser &parser,
1247                                                       OperationState &result) {
1248   return ::parseAtomicCompareExchangeImpl(parser, result);
1249 }
1250 void spirv::AtomicCompareExchangeWeakOp::print(OpAsmPrinter &p) {
1251   ::printAtomicCompareExchangeImpl(*this, p);
1252 }
1253 
1254 //===----------------------------------------------------------------------===//
1255 // spv.AtomicExchange
1256 //===----------------------------------------------------------------------===//
1257 
1258 void spirv::AtomicExchangeOp::print(OpAsmPrinter &printer) {
1259   printer << " \"" << stringifyScope(memory_scope()) << "\" \""
1260           << stringifyMemorySemantics(semantics()) << "\" " << getOperands()
1261           << " : " << pointer().getType();
1262 }
1263 
1264 ParseResult spirv::AtomicExchangeOp::parse(OpAsmParser &parser,
1265                                            OperationState &state) {
1266   spirv::Scope memoryScope;
1267   spirv::MemorySemantics semantics;
1268   SmallVector<OpAsmParser::UnresolvedOperand, 2> operandInfo;
1269   Type type;
1270   if (parseEnumStrAttr(memoryScope, parser, state, kMemoryScopeAttrName) ||
1271       parseEnumStrAttr(semantics, parser, state, kSemanticsAttrName) ||
1272       parser.parseOperandList(operandInfo, 2))
1273     return failure();
1274 
1275   auto loc = parser.getCurrentLocation();
1276   if (parser.parseColonType(type))
1277     return failure();
1278 
1279   auto ptrType = type.dyn_cast<spirv::PointerType>();
1280   if (!ptrType)
1281     return parser.emitError(loc, "expected pointer type");
1282 
1283   if (parser.resolveOperands(operandInfo, {ptrType, ptrType.getPointeeType()},
1284                              parser.getNameLoc(), state.operands))
1285     return failure();
1286 
1287   return parser.addTypeToList(ptrType.getPointeeType(), state.types);
1288 }
1289 
1290 LogicalResult spirv::AtomicExchangeOp::verify() {
1291   if (getType() != value().getType())
1292     return emitOpError("value operand must have the same type as the op "
1293                        "result, but found ")
1294            << value().getType() << " vs " << getType();
1295 
1296   Type pointeeType =
1297       pointer().getType().cast<spirv::PointerType>().getPointeeType();
1298   if (getType() != pointeeType)
1299     return emitOpError("pointer operand's pointee type must have the same "
1300                        "as the op result type, but found ")
1301            << pointeeType << " vs " << getType();
1302 
1303   return success();
1304 }
1305 
1306 //===----------------------------------------------------------------------===//
1307 // spv.AtomicIAddOp
1308 //===----------------------------------------------------------------------===//
1309 
1310 LogicalResult spirv::AtomicIAddOp::verify() {
1311   return ::verifyAtomicUpdateOp<IntegerType>(getOperation());
1312 }
1313 
1314 ParseResult spirv::AtomicIAddOp::parse(OpAsmParser &parser,
1315                                        OperationState &result) {
1316   return ::parseAtomicUpdateOp(parser, result, true);
1317 }
1318 void spirv::AtomicIAddOp::print(OpAsmPrinter &p) {
1319   ::printAtomicUpdateOp(*this, p);
1320 }
1321 
1322 //===----------------------------------------------------------------------===//
1323 // spv.AtomicFAddEXTOp
1324 //===----------------------------------------------------------------------===//
1325 
1326 LogicalResult spirv::AtomicFAddEXTOp::verify() {
1327   return ::verifyAtomicUpdateOp<FloatType>(getOperation());
1328 }
1329 
1330 ParseResult spirv::AtomicFAddEXTOp::parse(OpAsmParser &parser,
1331                                           OperationState &result) {
1332   return ::parseAtomicUpdateOp(parser, result, true);
1333 }
1334 void spirv::AtomicFAddEXTOp::print(OpAsmPrinter &p) {
1335   ::printAtomicUpdateOp(*this, p);
1336 }
1337 
1338 //===----------------------------------------------------------------------===//
1339 // spv.AtomicIDecrementOp
1340 //===----------------------------------------------------------------------===//
1341 
1342 LogicalResult spirv::AtomicIDecrementOp::verify() {
1343   return ::verifyAtomicUpdateOp<IntegerType>(getOperation());
1344 }
1345 
1346 ParseResult spirv::AtomicIDecrementOp::parse(OpAsmParser &parser,
1347                                              OperationState &result) {
1348   return ::parseAtomicUpdateOp(parser, result, false);
1349 }
1350 void spirv::AtomicIDecrementOp::print(OpAsmPrinter &p) {
1351   ::printAtomicUpdateOp(*this, p);
1352 }
1353 
1354 //===----------------------------------------------------------------------===//
1355 // spv.AtomicIIncrementOp
1356 //===----------------------------------------------------------------------===//
1357 
1358 LogicalResult spirv::AtomicIIncrementOp::verify() {
1359   return ::verifyAtomicUpdateOp<IntegerType>(getOperation());
1360 }
1361 
1362 ParseResult spirv::AtomicIIncrementOp::parse(OpAsmParser &parser,
1363                                              OperationState &result) {
1364   return ::parseAtomicUpdateOp(parser, result, false);
1365 }
1366 void spirv::AtomicIIncrementOp::print(OpAsmPrinter &p) {
1367   ::printAtomicUpdateOp(*this, p);
1368 }
1369 
1370 //===----------------------------------------------------------------------===//
1371 // spv.AtomicISubOp
1372 //===----------------------------------------------------------------------===//
1373 
1374 LogicalResult spirv::AtomicISubOp::verify() {
1375   return ::verifyAtomicUpdateOp<IntegerType>(getOperation());
1376 }
1377 
1378 ParseResult spirv::AtomicISubOp::parse(OpAsmParser &parser,
1379                                        OperationState &result) {
1380   return ::parseAtomicUpdateOp(parser, result, true);
1381 }
1382 void spirv::AtomicISubOp::print(OpAsmPrinter &p) {
1383   ::printAtomicUpdateOp(*this, p);
1384 }
1385 
1386 //===----------------------------------------------------------------------===//
1387 // spv.AtomicOrOp
1388 //===----------------------------------------------------------------------===//
1389 
1390 LogicalResult spirv::AtomicOrOp::verify() {
1391   return ::verifyAtomicUpdateOp<IntegerType>(getOperation());
1392 }
1393 
1394 ParseResult spirv::AtomicOrOp::parse(OpAsmParser &parser,
1395                                      OperationState &result) {
1396   return ::parseAtomicUpdateOp(parser, result, true);
1397 }
1398 void spirv::AtomicOrOp::print(OpAsmPrinter &p) {
1399   ::printAtomicUpdateOp(*this, p);
1400 }
1401 
1402 //===----------------------------------------------------------------------===//
1403 // spv.AtomicSMaxOp
1404 //===----------------------------------------------------------------------===//
1405 
1406 LogicalResult spirv::AtomicSMaxOp::verify() {
1407   return ::verifyAtomicUpdateOp<IntegerType>(getOperation());
1408 }
1409 
1410 ParseResult spirv::AtomicSMaxOp::parse(OpAsmParser &parser,
1411                                        OperationState &result) {
1412   return ::parseAtomicUpdateOp(parser, result, true);
1413 }
1414 void spirv::AtomicSMaxOp::print(OpAsmPrinter &p) {
1415   ::printAtomicUpdateOp(*this, p);
1416 }
1417 
1418 //===----------------------------------------------------------------------===//
1419 // spv.AtomicSMinOp
1420 //===----------------------------------------------------------------------===//
1421 
1422 LogicalResult spirv::AtomicSMinOp::verify() {
1423   return ::verifyAtomicUpdateOp<IntegerType>(getOperation());
1424 }
1425 
1426 ParseResult spirv::AtomicSMinOp::parse(OpAsmParser &parser,
1427                                        OperationState &result) {
1428   return ::parseAtomicUpdateOp(parser, result, true);
1429 }
1430 void spirv::AtomicSMinOp::print(OpAsmPrinter &p) {
1431   ::printAtomicUpdateOp(*this, p);
1432 }
1433 
1434 //===----------------------------------------------------------------------===//
1435 // spv.AtomicUMaxOp
1436 //===----------------------------------------------------------------------===//
1437 
1438 LogicalResult spirv::AtomicUMaxOp::verify() {
1439   return ::verifyAtomicUpdateOp<IntegerType>(getOperation());
1440 }
1441 
1442 ParseResult spirv::AtomicUMaxOp::parse(OpAsmParser &parser,
1443                                        OperationState &result) {
1444   return ::parseAtomicUpdateOp(parser, result, true);
1445 }
1446 void spirv::AtomicUMaxOp::print(OpAsmPrinter &p) {
1447   ::printAtomicUpdateOp(*this, p);
1448 }
1449 
1450 //===----------------------------------------------------------------------===//
1451 // spv.AtomicUMinOp
1452 //===----------------------------------------------------------------------===//
1453 
1454 LogicalResult spirv::AtomicUMinOp::verify() {
1455   return ::verifyAtomicUpdateOp<IntegerType>(getOperation());
1456 }
1457 
1458 ParseResult spirv::AtomicUMinOp::parse(OpAsmParser &parser,
1459                                        OperationState &result) {
1460   return ::parseAtomicUpdateOp(parser, result, true);
1461 }
1462 void spirv::AtomicUMinOp::print(OpAsmPrinter &p) {
1463   ::printAtomicUpdateOp(*this, p);
1464 }
1465 
1466 //===----------------------------------------------------------------------===//
1467 // spv.AtomicXorOp
1468 //===----------------------------------------------------------------------===//
1469 
1470 LogicalResult spirv::AtomicXorOp::verify() {
1471   return ::verifyAtomicUpdateOp<IntegerType>(getOperation());
1472 }
1473 
1474 ParseResult spirv::AtomicXorOp::parse(OpAsmParser &parser,
1475                                       OperationState &result) {
1476   return ::parseAtomicUpdateOp(parser, result, true);
1477 }
1478 void spirv::AtomicXorOp::print(OpAsmPrinter &p) {
1479   ::printAtomicUpdateOp(*this, p);
1480 }
1481 
1482 //===----------------------------------------------------------------------===//
1483 // spv.BitcastOp
1484 //===----------------------------------------------------------------------===//
1485 
1486 LogicalResult spirv::BitcastOp::verify() {
1487   // TODO: The SPIR-V spec validation rules are different for different
1488   // versions.
1489   auto operandType = operand().getType();
1490   auto resultType = result().getType();
1491   if (operandType == resultType) {
1492     return emitError("result type must be different from operand type");
1493   }
1494   if (operandType.isa<spirv::PointerType>() &&
1495       !resultType.isa<spirv::PointerType>()) {
1496     return emitError(
1497         "unhandled bit cast conversion from pointer type to non-pointer type");
1498   }
1499   if (!operandType.isa<spirv::PointerType>() &&
1500       resultType.isa<spirv::PointerType>()) {
1501     return emitError(
1502         "unhandled bit cast conversion from non-pointer type to pointer type");
1503   }
1504   auto operandBitWidth = getBitWidth(operandType);
1505   auto resultBitWidth = getBitWidth(resultType);
1506   if (operandBitWidth != resultBitWidth) {
1507     return emitOpError("mismatch in result type bitwidth ")
1508            << resultBitWidth << " and operand type bitwidth "
1509            << operandBitWidth;
1510   }
1511   return success();
1512 }
1513 
1514 //===----------------------------------------------------------------------===//
1515 // spv.BranchOp
1516 //===----------------------------------------------------------------------===//
1517 
1518 SuccessorOperands spirv::BranchOp::getSuccessorOperands(unsigned index) {
1519   assert(index == 0 && "invalid successor index");
1520   return SuccessorOperands(0, targetOperandsMutable());
1521 }
1522 
1523 //===----------------------------------------------------------------------===//
1524 // spv.BranchConditionalOp
1525 //===----------------------------------------------------------------------===//
1526 
1527 SuccessorOperands
1528 spirv::BranchConditionalOp::getSuccessorOperands(unsigned index) {
1529   assert(index < 2 && "invalid successor index");
1530   return SuccessorOperands(index == kTrueIndex ? trueTargetOperandsMutable()
1531                                                : falseTargetOperandsMutable());
1532 }
1533 
1534 ParseResult spirv::BranchConditionalOp::parse(OpAsmParser &parser,
1535                                               OperationState &state) {
1536   auto &builder = parser.getBuilder();
1537   OpAsmParser::UnresolvedOperand condInfo;
1538   Block *dest;
1539 
1540   // Parse the condition.
1541   Type boolTy = builder.getI1Type();
1542   if (parser.parseOperand(condInfo) ||
1543       parser.resolveOperand(condInfo, boolTy, state.operands))
1544     return failure();
1545 
1546   // Parse the optional branch weights.
1547   if (succeeded(parser.parseOptionalLSquare())) {
1548     IntegerAttr trueWeight, falseWeight;
1549     NamedAttrList weights;
1550 
1551     auto i32Type = builder.getIntegerType(32);
1552     if (parser.parseAttribute(trueWeight, i32Type, "weight", weights) ||
1553         parser.parseComma() ||
1554         parser.parseAttribute(falseWeight, i32Type, "weight", weights) ||
1555         parser.parseRSquare())
1556       return failure();
1557 
1558     state.addAttribute(kBranchWeightAttrName,
1559                        builder.getArrayAttr({trueWeight, falseWeight}));
1560   }
1561 
1562   // Parse the true branch.
1563   SmallVector<Value, 4> trueOperands;
1564   if (parser.parseComma() ||
1565       parser.parseSuccessorAndUseList(dest, trueOperands))
1566     return failure();
1567   state.addSuccessors(dest);
1568   state.addOperands(trueOperands);
1569 
1570   // Parse the false branch.
1571   SmallVector<Value, 4> falseOperands;
1572   if (parser.parseComma() ||
1573       parser.parseSuccessorAndUseList(dest, falseOperands))
1574     return failure();
1575   state.addSuccessors(dest);
1576   state.addOperands(falseOperands);
1577   state.addAttribute(
1578       spirv::BranchConditionalOp::getOperandSegmentSizeAttr(),
1579       builder.getI32VectorAttr({1, static_cast<int32_t>(trueOperands.size()),
1580                                 static_cast<int32_t>(falseOperands.size())}));
1581 
1582   return success();
1583 }
1584 
1585 void spirv::BranchConditionalOp::print(OpAsmPrinter &printer) {
1586   printer << ' ' << condition();
1587 
1588   if (auto weights = branch_weights()) {
1589     printer << " [";
1590     llvm::interleaveComma(weights->getValue(), printer, [&](Attribute a) {
1591       printer << a.cast<IntegerAttr>().getInt();
1592     });
1593     printer << "]";
1594   }
1595 
1596   printer << ", ";
1597   printer.printSuccessorAndUseList(getTrueBlock(), getTrueBlockArguments());
1598   printer << ", ";
1599   printer.printSuccessorAndUseList(getFalseBlock(), getFalseBlockArguments());
1600 }
1601 
1602 LogicalResult spirv::BranchConditionalOp::verify() {
1603   if (auto weights = branch_weights()) {
1604     if (weights->getValue().size() != 2) {
1605       return emitOpError("must have exactly two branch weights");
1606     }
1607     if (llvm::all_of(*weights, [](Attribute attr) {
1608           return attr.cast<IntegerAttr>().getValue().isNullValue();
1609         }))
1610       return emitOpError("branch weights cannot both be zero");
1611   }
1612 
1613   return success();
1614 }
1615 
1616 //===----------------------------------------------------------------------===//
1617 // spv.CompositeConstruct
1618 //===----------------------------------------------------------------------===//
1619 
1620 ParseResult spirv::CompositeConstructOp::parse(OpAsmParser &parser,
1621                                                OperationState &state) {
1622   SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
1623   Type type;
1624   auto loc = parser.getCurrentLocation();
1625 
1626   if (parser.parseOperandList(operands) || parser.parseColonType(type)) {
1627     return failure();
1628   }
1629   auto cType = type.dyn_cast<spirv::CompositeType>();
1630   if (!cType) {
1631     return parser.emitError(
1632                loc, "result type must be a composite type, but provided ")
1633            << type;
1634   }
1635 
1636   if (cType.hasCompileTimeKnownNumElements() &&
1637       operands.size() != cType.getNumElements()) {
1638     return parser.emitError(loc, "has incorrect number of operands: expected ")
1639            << cType.getNumElements() << ", but provided " << operands.size();
1640   }
1641   // TODO: Add support for constructing a vector type from the vector operands.
1642   // According to the spec: "for constructing a vector, the operands may
1643   // also be vectors with the same component type as the Result Type component
1644   // type".
1645   SmallVector<Type, 4> elementTypes;
1646   elementTypes.reserve(operands.size());
1647   for (auto index : llvm::seq<uint32_t>(0, operands.size())) {
1648     elementTypes.push_back(cType.getElementType(index));
1649   }
1650   state.addTypes(type);
1651   return parser.resolveOperands(operands, elementTypes, loc, state.operands);
1652 }
1653 
1654 void spirv::CompositeConstructOp::print(OpAsmPrinter &printer) {
1655   printer << " " << constituents() << " : " << getResult().getType();
1656 }
1657 
1658 LogicalResult spirv::CompositeConstructOp::verify() {
1659   auto cType = getType().cast<spirv::CompositeType>();
1660   operand_range constituents = this->constituents();
1661 
1662   if (cType.isa<spirv::CooperativeMatrixNVType>()) {
1663     if (constituents.size() != 1)
1664       return emitError("has incorrect number of operands: expected ")
1665              << "1, but provided " << constituents.size();
1666   } else if (constituents.size() != cType.getNumElements()) {
1667     return emitError("has incorrect number of operands: expected ")
1668            << cType.getNumElements() << ", but provided "
1669            << constituents.size();
1670   }
1671 
1672   for (auto index : llvm::seq<uint32_t>(0, constituents.size())) {
1673     if (constituents[index].getType() != cType.getElementType(index)) {
1674       return emitError("operand type mismatch: expected operand type ")
1675              << cType.getElementType(index) << ", but provided "
1676              << constituents[index].getType();
1677     }
1678   }
1679 
1680   return success();
1681 }
1682 
1683 //===----------------------------------------------------------------------===//
1684 // spv.CompositeExtractOp
1685 //===----------------------------------------------------------------------===//
1686 
1687 void spirv::CompositeExtractOp::build(OpBuilder &builder, OperationState &state,
1688                                       Value composite,
1689                                       ArrayRef<int32_t> indices) {
1690   auto indexAttr = builder.getI32ArrayAttr(indices);
1691   auto elementType =
1692       getElementType(composite.getType(), indexAttr, state.location);
1693   if (!elementType) {
1694     return;
1695   }
1696   build(builder, state, elementType, composite, indexAttr);
1697 }
1698 
1699 ParseResult spirv::CompositeExtractOp::parse(OpAsmParser &parser,
1700                                              OperationState &state) {
1701   OpAsmParser::UnresolvedOperand compositeInfo;
1702   Attribute indicesAttr;
1703   Type compositeType;
1704   SMLoc attrLocation;
1705 
1706   if (parser.parseOperand(compositeInfo) ||
1707       parser.getCurrentLocation(&attrLocation) ||
1708       parser.parseAttribute(indicesAttr, kIndicesAttrName, state.attributes) ||
1709       parser.parseColonType(compositeType) ||
1710       parser.resolveOperand(compositeInfo, compositeType, state.operands)) {
1711     return failure();
1712   }
1713 
1714   Type resultType =
1715       getElementType(compositeType, indicesAttr, parser, attrLocation);
1716   if (!resultType) {
1717     return failure();
1718   }
1719   state.addTypes(resultType);
1720   return success();
1721 }
1722 
1723 void spirv::CompositeExtractOp::print(OpAsmPrinter &printer) {
1724   printer << ' ' << composite() << indices() << " : " << composite().getType();
1725 }
1726 
1727 LogicalResult spirv::CompositeExtractOp::verify() {
1728   auto indicesArrayAttr = indices().dyn_cast<ArrayAttr>();
1729   auto resultType =
1730       getElementType(composite().getType(), indicesArrayAttr, getLoc());
1731   if (!resultType)
1732     return failure();
1733 
1734   if (resultType != getType()) {
1735     return emitOpError("invalid result type: expected ")
1736            << resultType << " but provided " << getType();
1737   }
1738 
1739   return success();
1740 }
1741 
1742 //===----------------------------------------------------------------------===//
1743 // spv.CompositeInsert
1744 //===----------------------------------------------------------------------===//
1745 
1746 void spirv::CompositeInsertOp::build(OpBuilder &builder, OperationState &state,
1747                                      Value object, Value composite,
1748                                      ArrayRef<int32_t> indices) {
1749   auto indexAttr = builder.getI32ArrayAttr(indices);
1750   build(builder, state, composite.getType(), object, composite, indexAttr);
1751 }
1752 
1753 ParseResult spirv::CompositeInsertOp::parse(OpAsmParser &parser,
1754                                             OperationState &state) {
1755   SmallVector<OpAsmParser::UnresolvedOperand, 2> operands;
1756   Type objectType, compositeType;
1757   Attribute indicesAttr;
1758   auto loc = parser.getCurrentLocation();
1759 
1760   return failure(
1761       parser.parseOperandList(operands, 2) ||
1762       parser.parseAttribute(indicesAttr, kIndicesAttrName, state.attributes) ||
1763       parser.parseColonType(objectType) ||
1764       parser.parseKeywordType("into", compositeType) ||
1765       parser.resolveOperands(operands, {objectType, compositeType}, loc,
1766                              state.operands) ||
1767       parser.addTypesToList(compositeType, state.types));
1768 }
1769 
1770 LogicalResult spirv::CompositeInsertOp::verify() {
1771   auto indicesArrayAttr = indices().dyn_cast<ArrayAttr>();
1772   auto objectType =
1773       getElementType(composite().getType(), indicesArrayAttr, getLoc());
1774   if (!objectType)
1775     return failure();
1776 
1777   if (objectType != object().getType()) {
1778     return emitOpError("object operand type should be ")
1779            << objectType << ", but found " << object().getType();
1780   }
1781 
1782   if (composite().getType() != getType()) {
1783     return emitOpError("result type should be the same as "
1784                        "the composite type, but found ")
1785            << composite().getType() << " vs " << getType();
1786   }
1787 
1788   return success();
1789 }
1790 
1791 void spirv::CompositeInsertOp::print(OpAsmPrinter &printer) {
1792   printer << " " << object() << ", " << composite() << indices() << " : "
1793           << object().getType() << " into " << composite().getType();
1794 }
1795 
1796 //===----------------------------------------------------------------------===//
1797 // spv.Constant
1798 //===----------------------------------------------------------------------===//
1799 
1800 ParseResult spirv::ConstantOp::parse(OpAsmParser &parser,
1801                                      OperationState &state) {
1802   Attribute value;
1803   if (parser.parseAttribute(value, kValueAttrName, state.attributes))
1804     return failure();
1805 
1806   Type type = value.getType();
1807   if (type.isa<NoneType, TensorType>()) {
1808     if (parser.parseColonType(type))
1809       return failure();
1810   }
1811 
1812   return parser.addTypeToList(type, state.types);
1813 }
1814 
1815 void spirv::ConstantOp::print(OpAsmPrinter &printer) {
1816   printer << ' ' << value();
1817   if (getType().isa<spirv::ArrayType>())
1818     printer << " : " << getType();
1819 }
1820 
1821 static LogicalResult verifyConstantType(spirv::ConstantOp op, Attribute value,
1822                                         Type opType) {
1823   auto valueType = value.getType();
1824 
1825   if (value.isa<IntegerAttr, FloatAttr>()) {
1826     if (valueType != opType)
1827       return op.emitOpError("result type (")
1828              << opType << ") does not match value type (" << valueType << ")";
1829     return success();
1830   }
1831   if (value.isa<DenseIntOrFPElementsAttr, SparseElementsAttr>()) {
1832     if (valueType == opType)
1833       return success();
1834     auto arrayType = opType.dyn_cast<spirv::ArrayType>();
1835     auto shapedType = valueType.dyn_cast<ShapedType>();
1836     if (!arrayType)
1837       return op.emitOpError("result or element type (")
1838              << opType << ") does not match value type (" << valueType
1839              << "), must be the same or spv.array";
1840 
1841     int numElements = arrayType.getNumElements();
1842     auto opElemType = arrayType.getElementType();
1843     while (auto t = opElemType.dyn_cast<spirv::ArrayType>()) {
1844       numElements *= t.getNumElements();
1845       opElemType = t.getElementType();
1846     }
1847     if (!opElemType.isIntOrFloat())
1848       return op.emitOpError("only support nested array result type");
1849 
1850     auto valueElemType = shapedType.getElementType();
1851     if (valueElemType != opElemType) {
1852       return op.emitOpError("result element type (")
1853              << opElemType << ") does not match value element type ("
1854              << valueElemType << ")";
1855     }
1856 
1857     if (numElements != shapedType.getNumElements()) {
1858       return op.emitOpError("result number of elements (")
1859              << numElements << ") does not match value number of elements ("
1860              << shapedType.getNumElements() << ")";
1861     }
1862     return success();
1863   }
1864   if (auto arrayAttr = value.dyn_cast<ArrayAttr>()) {
1865     auto arrayType = opType.dyn_cast<spirv::ArrayType>();
1866     if (!arrayType)
1867       return op.emitOpError("must have spv.array result type for array value");
1868     Type elemType = arrayType.getElementType();
1869     for (Attribute element : arrayAttr.getValue()) {
1870       // Verify array elements recursively.
1871       if (failed(verifyConstantType(op, element, elemType)))
1872         return failure();
1873     }
1874     return success();
1875   }
1876   return op.emitOpError("cannot have value of type ") << valueType;
1877 }
1878 
1879 LogicalResult spirv::ConstantOp::verify() {
1880   // ODS already generates checks to make sure the result type is valid. We just
1881   // need to additionally check that the value's attribute type is consistent
1882   // with the result type.
1883   return verifyConstantType(*this, valueAttr(), getType());
1884 }
1885 
1886 bool spirv::ConstantOp::isBuildableWith(Type type) {
1887   // Must be valid SPIR-V type first.
1888   if (!type.isa<spirv::SPIRVType>())
1889     return false;
1890 
1891   if (isa<SPIRVDialect>(type.getDialect())) {
1892     // TODO: support constant struct
1893     return type.isa<spirv::ArrayType>();
1894   }
1895 
1896   return true;
1897 }
1898 
1899 spirv::ConstantOp spirv::ConstantOp::getZero(Type type, Location loc,
1900                                              OpBuilder &builder) {
1901   if (auto intType = type.dyn_cast<IntegerType>()) {
1902     unsigned width = intType.getWidth();
1903     if (width == 1)
1904       return builder.create<spirv::ConstantOp>(loc, type,
1905                                                builder.getBoolAttr(false));
1906     return builder.create<spirv::ConstantOp>(
1907         loc, type, builder.getIntegerAttr(type, APInt(width, 0)));
1908   }
1909   if (auto floatType = type.dyn_cast<FloatType>()) {
1910     return builder.create<spirv::ConstantOp>(
1911         loc, type, builder.getFloatAttr(floatType, 0.0));
1912   }
1913   if (auto vectorType = type.dyn_cast<VectorType>()) {
1914     Type elemType = vectorType.getElementType();
1915     if (elemType.isa<IntegerType>()) {
1916       return builder.create<spirv::ConstantOp>(
1917           loc, type,
1918           DenseElementsAttr::get(vectorType,
1919                                  IntegerAttr::get(elemType, 0.0).getValue()));
1920     }
1921     if (elemType.isa<FloatType>()) {
1922       return builder.create<spirv::ConstantOp>(
1923           loc, type,
1924           DenseFPElementsAttr::get(vectorType,
1925                                    FloatAttr::get(elemType, 0.0).getValue()));
1926     }
1927   }
1928 
1929   llvm_unreachable("unimplemented types for ConstantOp::getZero()");
1930 }
1931 
1932 spirv::ConstantOp spirv::ConstantOp::getOne(Type type, Location loc,
1933                                             OpBuilder &builder) {
1934   if (auto intType = type.dyn_cast<IntegerType>()) {
1935     unsigned width = intType.getWidth();
1936     if (width == 1)
1937       return builder.create<spirv::ConstantOp>(loc, type,
1938                                                builder.getBoolAttr(true));
1939     return builder.create<spirv::ConstantOp>(
1940         loc, type, builder.getIntegerAttr(type, APInt(width, 1)));
1941   }
1942   if (auto floatType = type.dyn_cast<FloatType>()) {
1943     return builder.create<spirv::ConstantOp>(
1944         loc, type, builder.getFloatAttr(floatType, 1.0));
1945   }
1946   if (auto vectorType = type.dyn_cast<VectorType>()) {
1947     Type elemType = vectorType.getElementType();
1948     if (elemType.isa<IntegerType>()) {
1949       return builder.create<spirv::ConstantOp>(
1950           loc, type,
1951           DenseElementsAttr::get(vectorType,
1952                                  IntegerAttr::get(elemType, 1.0).getValue()));
1953     }
1954     if (elemType.isa<FloatType>()) {
1955       return builder.create<spirv::ConstantOp>(
1956           loc, type,
1957           DenseFPElementsAttr::get(vectorType,
1958                                    FloatAttr::get(elemType, 1.0).getValue()));
1959     }
1960   }
1961 
1962   llvm_unreachable("unimplemented types for ConstantOp::getOne()");
1963 }
1964 
1965 void mlir::spirv::ConstantOp::getAsmResultNames(
1966     llvm::function_ref<void(mlir::Value, llvm::StringRef)> setNameFn) {
1967   Type type = getType();
1968 
1969   SmallString<32> specialNameBuffer;
1970   llvm::raw_svector_ostream specialName(specialNameBuffer);
1971   specialName << "cst";
1972 
1973   IntegerType intTy = type.dyn_cast<IntegerType>();
1974 
1975   if (IntegerAttr intCst = value().dyn_cast<IntegerAttr>()) {
1976     if (intTy && intTy.getWidth() == 1) {
1977       return setNameFn(getResult(), (intCst.getInt() ? "true" : "false"));
1978     }
1979 
1980     if (intTy.isSignless()) {
1981       specialName << intCst.getInt();
1982     } else {
1983       specialName << intCst.getSInt();
1984     }
1985   }
1986 
1987   if (intTy || type.isa<FloatType>()) {
1988     specialName << '_' << type;
1989   }
1990 
1991   if (auto vecType = type.dyn_cast<VectorType>()) {
1992     specialName << "_vec_";
1993     specialName << vecType.getDimSize(0);
1994 
1995     Type elementType = vecType.getElementType();
1996 
1997     if (elementType.isa<IntegerType>() || elementType.isa<FloatType>()) {
1998       specialName << "x" << elementType;
1999     }
2000   }
2001 
2002   setNameFn(getResult(), specialName.str());
2003 }
2004 
2005 void mlir::spirv::AddressOfOp::getAsmResultNames(
2006     llvm::function_ref<void(mlir::Value, llvm::StringRef)> setNameFn) {
2007   SmallString<32> specialNameBuffer;
2008   llvm::raw_svector_ostream specialName(specialNameBuffer);
2009   specialName << variable() << "_addr";
2010   setNameFn(getResult(), specialName.str());
2011 }
2012 
2013 //===----------------------------------------------------------------------===//
2014 // spv.ControlBarrierOp
2015 //===----------------------------------------------------------------------===//
2016 
2017 LogicalResult spirv::ControlBarrierOp::verify() {
2018   return verifyMemorySemantics(getOperation(), memory_semantics());
2019 }
2020 
2021 //===----------------------------------------------------------------------===//
2022 // spv.ConvertFToSOp
2023 //===----------------------------------------------------------------------===//
2024 
2025 LogicalResult spirv::ConvertFToSOp::verify() {
2026   return verifyCastOp(*this, /*requireSameBitWidth=*/false,
2027                       /*skipBitWidthCheck=*/true);
2028 }
2029 
2030 //===----------------------------------------------------------------------===//
2031 // spv.ConvertFToUOp
2032 //===----------------------------------------------------------------------===//
2033 
2034 LogicalResult spirv::ConvertFToUOp::verify() {
2035   return verifyCastOp(*this, /*requireSameBitWidth=*/false,
2036                       /*skipBitWidthCheck=*/true);
2037 }
2038 
2039 //===----------------------------------------------------------------------===//
2040 // spv.ConvertSToFOp
2041 //===----------------------------------------------------------------------===//
2042 
2043 LogicalResult spirv::ConvertSToFOp::verify() {
2044   return verifyCastOp(*this, /*requireSameBitWidth=*/false,
2045                       /*skipBitWidthCheck=*/true);
2046 }
2047 
2048 //===----------------------------------------------------------------------===//
2049 // spv.ConvertUToFOp
2050 //===----------------------------------------------------------------------===//
2051 
2052 LogicalResult spirv::ConvertUToFOp::verify() {
2053   return verifyCastOp(*this, /*requireSameBitWidth=*/false,
2054                       /*skipBitWidthCheck=*/true);
2055 }
2056 
2057 //===----------------------------------------------------------------------===//
2058 // spv.EntryPoint
2059 //===----------------------------------------------------------------------===//
2060 
2061 void spirv::EntryPointOp::build(OpBuilder &builder, OperationState &state,
2062                                 spirv::ExecutionModel executionModel,
2063                                 spirv::FuncOp function,
2064                                 ArrayRef<Attribute> interfaceVars) {
2065   build(builder, state,
2066         spirv::ExecutionModelAttr::get(builder.getContext(), executionModel),
2067         SymbolRefAttr::get(function), builder.getArrayAttr(interfaceVars));
2068 }
2069 
2070 ParseResult spirv::EntryPointOp::parse(OpAsmParser &parser,
2071                                        OperationState &state) {
2072   spirv::ExecutionModel execModel;
2073   SmallVector<OpAsmParser::UnresolvedOperand, 0> identifiers;
2074   SmallVector<Type, 0> idTypes;
2075   SmallVector<Attribute, 4> interfaceVars;
2076 
2077   FlatSymbolRefAttr fn;
2078   if (parseEnumStrAttr(execModel, parser, state) ||
2079       parser.parseAttribute(fn, Type(), kFnNameAttrName, state.attributes)) {
2080     return failure();
2081   }
2082 
2083   if (!parser.parseOptionalComma()) {
2084     // Parse the interface variables
2085     if (parser.parseCommaSeparatedList([&]() -> ParseResult {
2086           // The name of the interface variable attribute isnt important
2087           FlatSymbolRefAttr var;
2088           NamedAttrList attrs;
2089           if (parser.parseAttribute(var, Type(), "var_symbol", attrs))
2090             return failure();
2091           interfaceVars.push_back(var);
2092           return success();
2093         }))
2094       return failure();
2095   }
2096   state.addAttribute(kInterfaceAttrName,
2097                      parser.getBuilder().getArrayAttr(interfaceVars));
2098   return success();
2099 }
2100 
2101 void spirv::EntryPointOp::print(OpAsmPrinter &printer) {
2102   printer << " \"" << stringifyExecutionModel(execution_model()) << "\" ";
2103   printer.printSymbolName(fn());
2104   auto interfaceVars = interface().getValue();
2105   if (!interfaceVars.empty()) {
2106     printer << ", ";
2107     llvm::interleaveComma(interfaceVars, printer);
2108   }
2109 }
2110 
2111 LogicalResult spirv::EntryPointOp::verify() {
2112   // Checks for fn and interface symbol reference are done in spirv::ModuleOp
2113   // verification.
2114   return success();
2115 }
2116 
2117 //===----------------------------------------------------------------------===//
2118 // spv.ExecutionMode
2119 //===----------------------------------------------------------------------===//
2120 
2121 void spirv::ExecutionModeOp::build(OpBuilder &builder, OperationState &state,
2122                                    spirv::FuncOp function,
2123                                    spirv::ExecutionMode executionMode,
2124                                    ArrayRef<int32_t> params) {
2125   build(builder, state, SymbolRefAttr::get(function),
2126         spirv::ExecutionModeAttr::get(builder.getContext(), executionMode),
2127         builder.getI32ArrayAttr(params));
2128 }
2129 
2130 ParseResult spirv::ExecutionModeOp::parse(OpAsmParser &parser,
2131                                           OperationState &state) {
2132   spirv::ExecutionMode execMode;
2133   Attribute fn;
2134   if (parser.parseAttribute(fn, kFnNameAttrName, state.attributes) ||
2135       parseEnumStrAttr(execMode, parser, state)) {
2136     return failure();
2137   }
2138 
2139   SmallVector<int32_t, 4> values;
2140   Type i32Type = parser.getBuilder().getIntegerType(32);
2141   while (!parser.parseOptionalComma()) {
2142     NamedAttrList attr;
2143     Attribute value;
2144     if (parser.parseAttribute(value, i32Type, "value", attr)) {
2145       return failure();
2146     }
2147     values.push_back(value.cast<IntegerAttr>().getInt());
2148   }
2149   state.addAttribute(kValuesAttrName,
2150                      parser.getBuilder().getI32ArrayAttr(values));
2151   return success();
2152 }
2153 
2154 void spirv::ExecutionModeOp::print(OpAsmPrinter &printer) {
2155   printer << " ";
2156   printer.printSymbolName(fn());
2157   printer << " \"" << stringifyExecutionMode(execution_mode()) << "\"";
2158   auto values = this->values();
2159   if (values.empty())
2160     return;
2161   printer << ", ";
2162   llvm::interleaveComma(values, printer, [&](Attribute a) {
2163     printer << a.cast<IntegerAttr>().getInt();
2164   });
2165 }
2166 
2167 //===----------------------------------------------------------------------===//
2168 // spv.FConvertOp
2169 //===----------------------------------------------------------------------===//
2170 
2171 LogicalResult spirv::FConvertOp::verify() {
2172   return verifyCastOp(*this, /*requireSameBitWidth=*/false);
2173 }
2174 
2175 //===----------------------------------------------------------------------===//
2176 // spv.SConvertOp
2177 //===----------------------------------------------------------------------===//
2178 
2179 LogicalResult spirv::SConvertOp::verify() {
2180   return verifyCastOp(*this, /*requireSameBitWidth=*/false);
2181 }
2182 
2183 //===----------------------------------------------------------------------===//
2184 // spv.UConvertOp
2185 //===----------------------------------------------------------------------===//
2186 
2187 LogicalResult spirv::UConvertOp::verify() {
2188   return verifyCastOp(*this, /*requireSameBitWidth=*/false);
2189 }
2190 
2191 //===----------------------------------------------------------------------===//
2192 // spv.func
2193 //===----------------------------------------------------------------------===//
2194 
2195 ParseResult spirv::FuncOp::parse(OpAsmParser &parser, OperationState &state) {
2196   SmallVector<OpAsmParser::Argument> entryArgs;
2197   SmallVector<DictionaryAttr> resultAttrs;
2198   SmallVector<Type> resultTypes;
2199   auto &builder = parser.getBuilder();
2200 
2201   // Parse the name as a symbol.
2202   StringAttr nameAttr;
2203   if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
2204                              state.attributes))
2205     return failure();
2206 
2207   // Parse the function signature.
2208   bool isVariadic = false;
2209   if (function_interface_impl::parseFunctionSignature(
2210           parser, /*allowVariadic=*/false, entryArgs, isVariadic, resultTypes,
2211           resultAttrs))
2212     return failure();
2213 
2214   SmallVector<Type> argTypes;
2215   for (auto &arg : entryArgs)
2216     argTypes.push_back(arg.type);
2217   auto fnType = builder.getFunctionType(argTypes, resultTypes);
2218   state.addAttribute(FunctionOpInterface::getTypeAttrName(),
2219                      TypeAttr::get(fnType));
2220 
2221   // Parse the optional function control keyword.
2222   spirv::FunctionControl fnControl;
2223   if (parseEnumStrAttr(fnControl, parser, state))
2224     return failure();
2225 
2226   // If additional attributes are present, parse them.
2227   if (parser.parseOptionalAttrDictWithKeyword(state.attributes))
2228     return failure();
2229 
2230   // Add the attributes to the function arguments.
2231   assert(resultAttrs.size() == resultTypes.size());
2232   function_interface_impl::addArgAndResultAttrs(builder, state, entryArgs,
2233                                                 resultAttrs);
2234 
2235   // Parse the optional function body.
2236   auto *body = state.addRegion();
2237   OptionalParseResult result = parser.parseOptionalRegion(*body, entryArgs);
2238   return failure(result.hasValue() && failed(*result));
2239 }
2240 
2241 void spirv::FuncOp::print(OpAsmPrinter &printer) {
2242   // Print function name, signature, and control.
2243   printer << " ";
2244   printer.printSymbolName(sym_name());
2245   auto fnType = getFunctionType();
2246   function_interface_impl::printFunctionSignature(
2247       printer, *this, fnType.getInputs(),
2248       /*isVariadic=*/false, fnType.getResults());
2249   printer << " \"" << spirv::stringifyFunctionControl(function_control())
2250           << "\"";
2251   function_interface_impl::printFunctionAttributes(
2252       printer, *this, fnType.getNumInputs(), fnType.getNumResults(),
2253       {spirv::attributeName<spirv::FunctionControl>()});
2254 
2255   // Print the body if this is not an external function.
2256   Region &body = this->body();
2257   if (!body.empty()) {
2258     printer << ' ';
2259     printer.printRegion(body, /*printEntryBlockArgs=*/false,
2260                         /*printBlockTerminators=*/true);
2261   }
2262 }
2263 
2264 LogicalResult spirv::FuncOp::verifyType() {
2265   auto type = getFunctionTypeAttr().getValue();
2266   if (!type.isa<FunctionType>())
2267     return emitOpError("requires '" + getTypeAttrName() +
2268                        "' attribute of function type");
2269   if (getFunctionType().getNumResults() > 1)
2270     return emitOpError("cannot have more than one result");
2271   return success();
2272 }
2273 
2274 LogicalResult spirv::FuncOp::verifyBody() {
2275   FunctionType fnType = getFunctionType();
2276 
2277   auto walkResult = walk([fnType](Operation *op) -> WalkResult {
2278     if (auto retOp = dyn_cast<spirv::ReturnOp>(op)) {
2279       if (fnType.getNumResults() != 0)
2280         return retOp.emitOpError("cannot be used in functions returning value");
2281     } else if (auto retOp = dyn_cast<spirv::ReturnValueOp>(op)) {
2282       if (fnType.getNumResults() != 1)
2283         return retOp.emitOpError(
2284                    "returns 1 value but enclosing function requires ")
2285                << fnType.getNumResults() << " results";
2286 
2287       auto retOperandType = retOp.value().getType();
2288       auto fnResultType = fnType.getResult(0);
2289       if (retOperandType != fnResultType)
2290         return retOp.emitOpError(" return value's type (")
2291                << retOperandType << ") mismatch with function's result type ("
2292                << fnResultType << ")";
2293     }
2294     return WalkResult::advance();
2295   });
2296 
2297   // TODO: verify other bits like linkage type.
2298 
2299   return failure(walkResult.wasInterrupted());
2300 }
2301 
2302 void spirv::FuncOp::build(OpBuilder &builder, OperationState &state,
2303                           StringRef name, FunctionType type,
2304                           spirv::FunctionControl control,
2305                           ArrayRef<NamedAttribute> attrs) {
2306   state.addAttribute(SymbolTable::getSymbolAttrName(),
2307                      builder.getStringAttr(name));
2308   state.addAttribute(getTypeAttrName(), TypeAttr::get(type));
2309   state.addAttribute(spirv::attributeName<spirv::FunctionControl>(),
2310                      builder.getI32IntegerAttr(static_cast<uint32_t>(control)));
2311   state.attributes.append(attrs.begin(), attrs.end());
2312   state.addRegion();
2313 }
2314 
2315 // CallableOpInterface
2316 Region *spirv::FuncOp::getCallableRegion() {
2317   return isExternal() ? nullptr : &body();
2318 }
2319 
2320 // CallableOpInterface
2321 ArrayRef<Type> spirv::FuncOp::getCallableResults() {
2322   return getFunctionType().getResults();
2323 }
2324 
2325 //===----------------------------------------------------------------------===//
2326 // spv.FunctionCall
2327 //===----------------------------------------------------------------------===//
2328 
2329 LogicalResult spirv::FunctionCallOp::verify() {
2330   auto fnName = calleeAttr();
2331 
2332   auto funcOp = dyn_cast_or_null<spirv::FuncOp>(
2333       SymbolTable::lookupNearestSymbolFrom((*this)->getParentOp(), fnName));
2334   if (!funcOp) {
2335     return emitOpError("callee function '")
2336            << fnName.getValue() << "' not found in nearest symbol table";
2337   }
2338 
2339   auto functionType = funcOp.getFunctionType();
2340 
2341   if (getNumResults() > 1) {
2342     return emitOpError(
2343                "expected callee function to have 0 or 1 result, but provided ")
2344            << getNumResults();
2345   }
2346 
2347   if (functionType.getNumInputs() != getNumOperands()) {
2348     return emitOpError("has incorrect number of operands for callee: expected ")
2349            << functionType.getNumInputs() << ", but provided "
2350            << getNumOperands();
2351   }
2352 
2353   for (uint32_t i = 0, e = functionType.getNumInputs(); i != e; ++i) {
2354     if (getOperand(i).getType() != functionType.getInput(i)) {
2355       return emitOpError("operand type mismatch: expected operand type ")
2356              << functionType.getInput(i) << ", but provided "
2357              << getOperand(i).getType() << " for operand number " << i;
2358     }
2359   }
2360 
2361   if (functionType.getNumResults() != getNumResults()) {
2362     return emitOpError(
2363                "has incorrect number of results has for callee: expected ")
2364            << functionType.getNumResults() << ", but provided "
2365            << getNumResults();
2366   }
2367 
2368   if (getNumResults() &&
2369       (getResult(0).getType() != functionType.getResult(0))) {
2370     return emitOpError("result type mismatch: expected ")
2371            << functionType.getResult(0) << ", but provided "
2372            << getResult(0).getType();
2373   }
2374 
2375   return success();
2376 }
2377 
2378 CallInterfaceCallable spirv::FunctionCallOp::getCallableForCallee() {
2379   return (*this)->getAttrOfType<SymbolRefAttr>(kCallee);
2380 }
2381 
2382 Operation::operand_range spirv::FunctionCallOp::getArgOperands() {
2383   return arguments();
2384 }
2385 
2386 //===----------------------------------------------------------------------===//
2387 // spv.GLSLFClampOp
2388 //===----------------------------------------------------------------------===//
2389 
2390 ParseResult spirv::GLSLFClampOp::parse(OpAsmParser &parser,
2391                                        OperationState &result) {
2392   return parseOneResultSameOperandTypeOp(parser, result);
2393 }
2394 void spirv::GLSLFClampOp::print(OpAsmPrinter &p) { printOneResultOp(*this, p); }
2395 
2396 //===----------------------------------------------------------------------===//
2397 // spv.GLSLUClampOp
2398 //===----------------------------------------------------------------------===//
2399 
2400 ParseResult spirv::GLSLUClampOp::parse(OpAsmParser &parser,
2401                                        OperationState &result) {
2402   return parseOneResultSameOperandTypeOp(parser, result);
2403 }
2404 void spirv::GLSLUClampOp::print(OpAsmPrinter &p) { printOneResultOp(*this, p); }
2405 
2406 //===----------------------------------------------------------------------===//
2407 // spv.GLSLSClampOp
2408 //===----------------------------------------------------------------------===//
2409 
2410 ParseResult spirv::GLSLSClampOp::parse(OpAsmParser &parser,
2411                                        OperationState &result) {
2412   return parseOneResultSameOperandTypeOp(parser, result);
2413 }
2414 void spirv::GLSLSClampOp::print(OpAsmPrinter &p) { printOneResultOp(*this, p); }
2415 
2416 //===----------------------------------------------------------------------===//
2417 // spv.GLSLFmaOp
2418 //===----------------------------------------------------------------------===//
2419 
2420 ParseResult spirv::GLSLFmaOp::parse(OpAsmParser &parser,
2421                                     OperationState &result) {
2422   return parseOneResultSameOperandTypeOp(parser, result);
2423 }
2424 void spirv::GLSLFmaOp::print(OpAsmPrinter &p) { printOneResultOp(*this, p); }
2425 
2426 //===----------------------------------------------------------------------===//
2427 // spv.GlobalVariable
2428 //===----------------------------------------------------------------------===//
2429 
2430 void spirv::GlobalVariableOp::build(OpBuilder &builder, OperationState &state,
2431                                     Type type, StringRef name,
2432                                     unsigned descriptorSet, unsigned binding) {
2433   build(builder, state, TypeAttr::get(type), builder.getStringAttr(name));
2434   state.addAttribute(
2435       spirv::SPIRVDialect::getAttributeName(spirv::Decoration::DescriptorSet),
2436       builder.getI32IntegerAttr(descriptorSet));
2437   state.addAttribute(
2438       spirv::SPIRVDialect::getAttributeName(spirv::Decoration::Binding),
2439       builder.getI32IntegerAttr(binding));
2440 }
2441 
2442 void spirv::GlobalVariableOp::build(OpBuilder &builder, OperationState &state,
2443                                     Type type, StringRef name,
2444                                     spirv::BuiltIn builtin) {
2445   build(builder, state, TypeAttr::get(type), builder.getStringAttr(name));
2446   state.addAttribute(
2447       spirv::SPIRVDialect::getAttributeName(spirv::Decoration::BuiltIn),
2448       builder.getStringAttr(spirv::stringifyBuiltIn(builtin)));
2449 }
2450 
2451 ParseResult spirv::GlobalVariableOp::parse(OpAsmParser &parser,
2452                                            OperationState &state) {
2453   // Parse variable name.
2454   StringAttr nameAttr;
2455   if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
2456                              state.attributes)) {
2457     return failure();
2458   }
2459 
2460   // Parse optional initializer
2461   if (succeeded(parser.parseOptionalKeyword(kInitializerAttrName))) {
2462     FlatSymbolRefAttr initSymbol;
2463     if (parser.parseLParen() ||
2464         parser.parseAttribute(initSymbol, Type(), kInitializerAttrName,
2465                               state.attributes) ||
2466         parser.parseRParen())
2467       return failure();
2468   }
2469 
2470   if (parseVariableDecorations(parser, state)) {
2471     return failure();
2472   }
2473 
2474   Type type;
2475   auto loc = parser.getCurrentLocation();
2476   if (parser.parseColonType(type)) {
2477     return failure();
2478   }
2479   if (!type.isa<spirv::PointerType>()) {
2480     return parser.emitError(loc, "expected spv.ptr type");
2481   }
2482   state.addAttribute(kTypeAttrName, TypeAttr::get(type));
2483 
2484   return success();
2485 }
2486 
2487 void spirv::GlobalVariableOp::print(OpAsmPrinter &printer) {
2488   SmallVector<StringRef, 4> elidedAttrs{
2489       spirv::attributeName<spirv::StorageClass>()};
2490 
2491   // Print variable name.
2492   printer << ' ';
2493   printer.printSymbolName(sym_name());
2494   elidedAttrs.push_back(SymbolTable::getSymbolAttrName());
2495 
2496   // Print optional initializer
2497   if (auto initializer = this->initializer()) {
2498     printer << " " << kInitializerAttrName << '(';
2499     printer.printSymbolName(initializer.getValue());
2500     printer << ')';
2501     elidedAttrs.push_back(kInitializerAttrName);
2502   }
2503 
2504   elidedAttrs.push_back(kTypeAttrName);
2505   printVariableDecorations(*this, printer, elidedAttrs);
2506   printer << " : " << type();
2507 }
2508 
2509 LogicalResult spirv::GlobalVariableOp::verify() {
2510   // SPIR-V spec: "Storage Class is the Storage Class of the memory holding the
2511   // object. It cannot be Generic. It must be the same as the Storage Class
2512   // operand of the Result Type."
2513   // Also, Function storage class is reserved by spv.Variable.
2514   auto storageClass = this->storageClass();
2515   if (storageClass == spirv::StorageClass::Generic ||
2516       storageClass == spirv::StorageClass::Function) {
2517     return emitOpError("storage class cannot be '")
2518            << stringifyStorageClass(storageClass) << "'";
2519   }
2520 
2521   if (auto init =
2522           (*this)->getAttrOfType<FlatSymbolRefAttr>(kInitializerAttrName)) {
2523     Operation *initOp = SymbolTable::lookupNearestSymbolFrom(
2524         (*this)->getParentOp(), init.getAttr());
2525     // TODO: Currently only variable initialization with specialization
2526     // constants and other variables is supported. They could be normal
2527     // constants in the module scope as well.
2528     if (!initOp ||
2529         !isa<spirv::GlobalVariableOp, spirv::SpecConstantOp>(initOp)) {
2530       return emitOpError("initializer must be result of a "
2531                          "spv.SpecConstant or spv.GlobalVariable op");
2532     }
2533   }
2534 
2535   return success();
2536 }
2537 
2538 //===----------------------------------------------------------------------===//
2539 // spv.GroupBroadcast
2540 //===----------------------------------------------------------------------===//
2541 
2542 LogicalResult spirv::GroupBroadcastOp::verify() {
2543   spirv::Scope scope = execution_scope();
2544   if (scope != spirv::Scope::Workgroup && scope != spirv::Scope::Subgroup)
2545     return emitOpError("execution scope must be 'Workgroup' or 'Subgroup'");
2546 
2547   if (auto localIdTy = localid().getType().dyn_cast<VectorType>())
2548     if (!(localIdTy.getNumElements() == 2 || localIdTy.getNumElements() == 3))
2549       return emitOpError("localid is a vector and can be with only "
2550                          " 2 or 3 components, actual number is ")
2551              << localIdTy.getNumElements();
2552 
2553   return success();
2554 }
2555 
2556 //===----------------------------------------------------------------------===//
2557 // spv.GroupNonUniformBallotOp
2558 //===----------------------------------------------------------------------===//
2559 
2560 LogicalResult spirv::GroupNonUniformBallotOp::verify() {
2561   spirv::Scope scope = execution_scope();
2562   if (scope != spirv::Scope::Workgroup && scope != spirv::Scope::Subgroup)
2563     return emitOpError("execution scope must be 'Workgroup' or 'Subgroup'");
2564 
2565   return success();
2566 }
2567 
2568 //===----------------------------------------------------------------------===//
2569 // spv.GroupNonUniformBroadcast
2570 //===----------------------------------------------------------------------===//
2571 
2572 LogicalResult spirv::GroupNonUniformBroadcastOp::verify() {
2573   spirv::Scope scope = execution_scope();
2574   if (scope != spirv::Scope::Workgroup && scope != spirv::Scope::Subgroup)
2575     return emitOpError("execution scope must be 'Workgroup' or 'Subgroup'");
2576 
2577   // SPIR-V spec: "Before version 1.5, Id must come from a
2578   // constant instruction.
2579   auto targetEnv = spirv::getDefaultTargetEnv(getContext());
2580   if (auto spirvModule = (*this)->getParentOfType<spirv::ModuleOp>())
2581     targetEnv = spirv::lookupTargetEnvOrDefault(spirvModule);
2582 
2583   if (targetEnv.getVersion() < spirv::Version::V_1_5) {
2584     auto *idOp = id().getDefiningOp();
2585     if (!idOp || !isa<spirv::ConstantOp,           // for normal constant
2586                       spirv::ReferenceOfOp>(idOp)) // for spec constant
2587       return emitOpError("id must be the result of a constant op");
2588   }
2589 
2590   return success();
2591 }
2592 
2593 //===----------------------------------------------------------------------===//
2594 // spv.SubgroupBlockReadINTEL
2595 //===----------------------------------------------------------------------===//
2596 
2597 ParseResult spirv::SubgroupBlockReadINTELOp::parse(OpAsmParser &parser,
2598                                                    OperationState &state) {
2599   // Parse the storage class specification
2600   spirv::StorageClass storageClass;
2601   OpAsmParser::UnresolvedOperand ptrInfo;
2602   Type elementType;
2603   if (parseEnumStrAttr(storageClass, parser) || parser.parseOperand(ptrInfo) ||
2604       parser.parseColon() || parser.parseType(elementType)) {
2605     return failure();
2606   }
2607 
2608   auto ptrType = spirv::PointerType::get(elementType, storageClass);
2609   if (auto valVecTy = elementType.dyn_cast<VectorType>())
2610     ptrType = spirv::PointerType::get(valVecTy.getElementType(), storageClass);
2611 
2612   if (parser.resolveOperand(ptrInfo, ptrType, state.operands)) {
2613     return failure();
2614   }
2615 
2616   state.addTypes(elementType);
2617   return success();
2618 }
2619 
2620 void spirv::SubgroupBlockReadINTELOp::print(OpAsmPrinter &printer) {
2621   printer << " " << ptr() << " : " << getType();
2622 }
2623 
2624 LogicalResult spirv::SubgroupBlockReadINTELOp::verify() {
2625   if (failed(verifyBlockReadWritePtrAndValTypes(*this, ptr(), value())))
2626     return failure();
2627 
2628   return success();
2629 }
2630 
2631 //===----------------------------------------------------------------------===//
2632 // spv.SubgroupBlockWriteINTEL
2633 //===----------------------------------------------------------------------===//
2634 
2635 ParseResult spirv::SubgroupBlockWriteINTELOp::parse(OpAsmParser &parser,
2636                                                     OperationState &state) {
2637   // Parse the storage class specification
2638   spirv::StorageClass storageClass;
2639   SmallVector<OpAsmParser::UnresolvedOperand, 2> operandInfo;
2640   auto loc = parser.getCurrentLocation();
2641   Type elementType;
2642   if (parseEnumStrAttr(storageClass, parser) ||
2643       parser.parseOperandList(operandInfo, 2) || parser.parseColon() ||
2644       parser.parseType(elementType)) {
2645     return failure();
2646   }
2647 
2648   auto ptrType = spirv::PointerType::get(elementType, storageClass);
2649   if (auto valVecTy = elementType.dyn_cast<VectorType>())
2650     ptrType = spirv::PointerType::get(valVecTy.getElementType(), storageClass);
2651 
2652   if (parser.resolveOperands(operandInfo, {ptrType, elementType}, loc,
2653                              state.operands)) {
2654     return failure();
2655   }
2656   return success();
2657 }
2658 
2659 void spirv::SubgroupBlockWriteINTELOp::print(OpAsmPrinter &printer) {
2660   printer << " " << ptr() << ", " << value() << " : " << value().getType();
2661 }
2662 
2663 LogicalResult spirv::SubgroupBlockWriteINTELOp::verify() {
2664   if (failed(verifyBlockReadWritePtrAndValTypes(*this, ptr(), value())))
2665     return failure();
2666 
2667   return success();
2668 }
2669 
2670 //===----------------------------------------------------------------------===//
2671 // spv.GroupNonUniformElectOp
2672 //===----------------------------------------------------------------------===//
2673 
2674 LogicalResult spirv::GroupNonUniformElectOp::verify() {
2675   spirv::Scope scope = execution_scope();
2676   if (scope != spirv::Scope::Workgroup && scope != spirv::Scope::Subgroup)
2677     return emitOpError("execution scope must be 'Workgroup' or 'Subgroup'");
2678 
2679   return success();
2680 }
2681 
2682 //===----------------------------------------------------------------------===//
2683 // spv.GroupNonUniformFAddOp
2684 //===----------------------------------------------------------------------===//
2685 
2686 LogicalResult spirv::GroupNonUniformFAddOp::verify() {
2687   return verifyGroupNonUniformArithmeticOp(*this);
2688 }
2689 
2690 ParseResult spirv::GroupNonUniformFAddOp::parse(OpAsmParser &parser,
2691                                                 OperationState &result) {
2692   return parseGroupNonUniformArithmeticOp(parser, result);
2693 }
2694 void spirv::GroupNonUniformFAddOp::print(OpAsmPrinter &p) {
2695   printGroupNonUniformArithmeticOp(*this, p);
2696 }
2697 
2698 //===----------------------------------------------------------------------===//
2699 // spv.GroupNonUniformFMaxOp
2700 //===----------------------------------------------------------------------===//
2701 
2702 LogicalResult spirv::GroupNonUniformFMaxOp::verify() {
2703   return verifyGroupNonUniformArithmeticOp(*this);
2704 }
2705 
2706 ParseResult spirv::GroupNonUniformFMaxOp::parse(OpAsmParser &parser,
2707                                                 OperationState &result) {
2708   return parseGroupNonUniformArithmeticOp(parser, result);
2709 }
2710 void spirv::GroupNonUniformFMaxOp::print(OpAsmPrinter &p) {
2711   printGroupNonUniformArithmeticOp(*this, p);
2712 }
2713 
2714 //===----------------------------------------------------------------------===//
2715 // spv.GroupNonUniformFMinOp
2716 //===----------------------------------------------------------------------===//
2717 
2718 LogicalResult spirv::GroupNonUniformFMinOp::verify() {
2719   return verifyGroupNonUniformArithmeticOp(*this);
2720 }
2721 
2722 ParseResult spirv::GroupNonUniformFMinOp::parse(OpAsmParser &parser,
2723                                                 OperationState &result) {
2724   return parseGroupNonUniformArithmeticOp(parser, result);
2725 }
2726 void spirv::GroupNonUniformFMinOp::print(OpAsmPrinter &p) {
2727   printGroupNonUniformArithmeticOp(*this, p);
2728 }
2729 
2730 //===----------------------------------------------------------------------===//
2731 // spv.GroupNonUniformFMulOp
2732 //===----------------------------------------------------------------------===//
2733 
2734 LogicalResult spirv::GroupNonUniformFMulOp::verify() {
2735   return verifyGroupNonUniformArithmeticOp(*this);
2736 }
2737 
2738 ParseResult spirv::GroupNonUniformFMulOp::parse(OpAsmParser &parser,
2739                                                 OperationState &result) {
2740   return parseGroupNonUniformArithmeticOp(parser, result);
2741 }
2742 void spirv::GroupNonUniformFMulOp::print(OpAsmPrinter &p) {
2743   printGroupNonUniformArithmeticOp(*this, p);
2744 }
2745 
2746 //===----------------------------------------------------------------------===//
2747 // spv.GroupNonUniformIAddOp
2748 //===----------------------------------------------------------------------===//
2749 
2750 LogicalResult spirv::GroupNonUniformIAddOp::verify() {
2751   return verifyGroupNonUniformArithmeticOp(*this);
2752 }
2753 
2754 ParseResult spirv::GroupNonUniformIAddOp::parse(OpAsmParser &parser,
2755                                                 OperationState &result) {
2756   return parseGroupNonUniformArithmeticOp(parser, result);
2757 }
2758 void spirv::GroupNonUniformIAddOp::print(OpAsmPrinter &p) {
2759   printGroupNonUniformArithmeticOp(*this, p);
2760 }
2761 
2762 //===----------------------------------------------------------------------===//
2763 // spv.GroupNonUniformIMulOp
2764 //===----------------------------------------------------------------------===//
2765 
2766 LogicalResult spirv::GroupNonUniformIMulOp::verify() {
2767   return verifyGroupNonUniformArithmeticOp(*this);
2768 }
2769 
2770 ParseResult spirv::GroupNonUniformIMulOp::parse(OpAsmParser &parser,
2771                                                 OperationState &result) {
2772   return parseGroupNonUniformArithmeticOp(parser, result);
2773 }
2774 void spirv::GroupNonUniformIMulOp::print(OpAsmPrinter &p) {
2775   printGroupNonUniformArithmeticOp(*this, p);
2776 }
2777 
2778 //===----------------------------------------------------------------------===//
2779 // spv.GroupNonUniformSMaxOp
2780 //===----------------------------------------------------------------------===//
2781 
2782 LogicalResult spirv::GroupNonUniformSMaxOp::verify() {
2783   return verifyGroupNonUniformArithmeticOp(*this);
2784 }
2785 
2786 ParseResult spirv::GroupNonUniformSMaxOp::parse(OpAsmParser &parser,
2787                                                 OperationState &result) {
2788   return parseGroupNonUniformArithmeticOp(parser, result);
2789 }
2790 void spirv::GroupNonUniformSMaxOp::print(OpAsmPrinter &p) {
2791   printGroupNonUniformArithmeticOp(*this, p);
2792 }
2793 
2794 //===----------------------------------------------------------------------===//
2795 // spv.GroupNonUniformSMinOp
2796 //===----------------------------------------------------------------------===//
2797 
2798 LogicalResult spirv::GroupNonUniformSMinOp::verify() {
2799   return verifyGroupNonUniformArithmeticOp(*this);
2800 }
2801 
2802 ParseResult spirv::GroupNonUniformSMinOp::parse(OpAsmParser &parser,
2803                                                 OperationState &result) {
2804   return parseGroupNonUniformArithmeticOp(parser, result);
2805 }
2806 void spirv::GroupNonUniformSMinOp::print(OpAsmPrinter &p) {
2807   printGroupNonUniformArithmeticOp(*this, p);
2808 }
2809 
2810 //===----------------------------------------------------------------------===//
2811 // spv.GroupNonUniformUMaxOp
2812 //===----------------------------------------------------------------------===//
2813 
2814 LogicalResult spirv::GroupNonUniformUMaxOp::verify() {
2815   return verifyGroupNonUniformArithmeticOp(*this);
2816 }
2817 
2818 ParseResult spirv::GroupNonUniformUMaxOp::parse(OpAsmParser &parser,
2819                                                 OperationState &result) {
2820   return parseGroupNonUniformArithmeticOp(parser, result);
2821 }
2822 void spirv::GroupNonUniformUMaxOp::print(OpAsmPrinter &p) {
2823   printGroupNonUniformArithmeticOp(*this, p);
2824 }
2825 
2826 //===----------------------------------------------------------------------===//
2827 // spv.GroupNonUniformUMinOp
2828 //===----------------------------------------------------------------------===//
2829 
2830 LogicalResult spirv::GroupNonUniformUMinOp::verify() {
2831   return verifyGroupNonUniformArithmeticOp(*this);
2832 }
2833 
2834 ParseResult spirv::GroupNonUniformUMinOp::parse(OpAsmParser &parser,
2835                                                 OperationState &result) {
2836   return parseGroupNonUniformArithmeticOp(parser, result);
2837 }
2838 void spirv::GroupNonUniformUMinOp::print(OpAsmPrinter &p) {
2839   printGroupNonUniformArithmeticOp(*this, p);
2840 }
2841 
2842 //===----------------------------------------------------------------------===//
2843 // spv.LoadOp
2844 //===----------------------------------------------------------------------===//
2845 
2846 void spirv::LoadOp::build(OpBuilder &builder, OperationState &state,
2847                           Value basePtr, MemoryAccessAttr memoryAccess,
2848                           IntegerAttr alignment) {
2849   auto ptrType = basePtr.getType().cast<spirv::PointerType>();
2850   build(builder, state, ptrType.getPointeeType(), basePtr, memoryAccess,
2851         alignment);
2852 }
2853 
2854 ParseResult spirv::LoadOp::parse(OpAsmParser &parser, OperationState &state) {
2855   // Parse the storage class specification
2856   spirv::StorageClass storageClass;
2857   OpAsmParser::UnresolvedOperand ptrInfo;
2858   Type elementType;
2859   if (parseEnumStrAttr(storageClass, parser) || parser.parseOperand(ptrInfo) ||
2860       parseMemoryAccessAttributes(parser, state) ||
2861       parser.parseOptionalAttrDict(state.attributes) || parser.parseColon() ||
2862       parser.parseType(elementType)) {
2863     return failure();
2864   }
2865 
2866   auto ptrType = spirv::PointerType::get(elementType, storageClass);
2867   if (parser.resolveOperand(ptrInfo, ptrType, state.operands)) {
2868     return failure();
2869   }
2870 
2871   state.addTypes(elementType);
2872   return success();
2873 }
2874 
2875 void spirv::LoadOp::print(OpAsmPrinter &printer) {
2876   SmallVector<StringRef, 4> elidedAttrs;
2877   StringRef sc = stringifyStorageClass(
2878       ptr().getType().cast<spirv::PointerType>().getStorageClass());
2879   printer << " \"" << sc << "\" " << ptr();
2880 
2881   printMemoryAccessAttribute(*this, printer, elidedAttrs);
2882 
2883   printer.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs);
2884   printer << " : " << getType();
2885 }
2886 
2887 LogicalResult spirv::LoadOp::verify() {
2888   // SPIR-V spec : "Result Type is the type of the loaded object. It must be a
2889   // type with fixed size; i.e., it cannot be, nor include, any
2890   // OpTypeRuntimeArray types."
2891   if (failed(verifyLoadStorePtrAndValTypes(*this, ptr(), value()))) {
2892     return failure();
2893   }
2894   return verifyMemoryAccessAttribute(*this);
2895 }
2896 
2897 //===----------------------------------------------------------------------===//
2898 // spv.mlir.loop
2899 //===----------------------------------------------------------------------===//
2900 
2901 void spirv::LoopOp::build(OpBuilder &builder, OperationState &state) {
2902   state.addAttribute("loop_control",
2903                      builder.getI32IntegerAttr(
2904                          static_cast<uint32_t>(spirv::LoopControl::None)));
2905   state.addRegion();
2906 }
2907 
2908 ParseResult spirv::LoopOp::parse(OpAsmParser &parser, OperationState &state) {
2909   if (parseControlAttribute<spirv::LoopControl>(parser, state))
2910     return failure();
2911   return parser.parseRegion(*state.addRegion(), /*arguments=*/{},
2912                             /*argTypes=*/{});
2913 }
2914 
2915 void spirv::LoopOp::print(OpAsmPrinter &printer) {
2916   auto control = loop_control();
2917   if (control != spirv::LoopControl::None)
2918     printer << " control(" << spirv::stringifyLoopControl(control) << ")";
2919   printer << ' ';
2920   printer.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
2921                       /*printBlockTerminators=*/true);
2922 }
2923 
2924 /// Returns true if the given `srcBlock` contains only one `spv.Branch` to the
2925 /// given `dstBlock`.
2926 static inline bool hasOneBranchOpTo(Block &srcBlock, Block &dstBlock) {
2927   // Check that there is only one op in the `srcBlock`.
2928   if (!llvm::hasSingleElement(srcBlock))
2929     return false;
2930 
2931   auto branchOp = dyn_cast<spirv::BranchOp>(srcBlock.back());
2932   return branchOp && branchOp.getSuccessor() == &dstBlock;
2933 }
2934 
2935 LogicalResult spirv::LoopOp::verifyRegions() {
2936   auto *op = getOperation();
2937 
2938   // We need to verify that the blocks follow the following layout:
2939   //
2940   //                     +-------------+
2941   //                     | entry block |
2942   //                     +-------------+
2943   //                            |
2944   //                            v
2945   //                     +-------------+
2946   //                     | loop header | <-----+
2947   //                     +-------------+       |
2948   //                                           |
2949   //                           ...             |
2950   //                          \ | /            |
2951   //                            v              |
2952   //                    +---------------+      |
2953   //                    | loop continue | -----+
2954   //                    +---------------+
2955   //
2956   //                           ...
2957   //                          \ | /
2958   //                            v
2959   //                     +-------------+
2960   //                     | merge block |
2961   //                     +-------------+
2962 
2963   auto &region = op->getRegion(0);
2964   // Allow empty region as a degenerated case, which can come from
2965   // optimizations.
2966   if (region.empty())
2967     return success();
2968 
2969   // The last block is the merge block.
2970   Block &merge = region.back();
2971   if (!isMergeBlock(merge))
2972     return emitOpError(
2973         "last block must be the merge block with only one 'spv.mlir.merge' op");
2974 
2975   if (std::next(region.begin()) == region.end())
2976     return emitOpError(
2977         "must have an entry block branching to the loop header block");
2978   // The first block is the entry block.
2979   Block &entry = region.front();
2980 
2981   if (std::next(region.begin(), 2) == region.end())
2982     return emitOpError(
2983         "must have a loop header block branched from the entry block");
2984   // The second block is the loop header block.
2985   Block &header = *std::next(region.begin(), 1);
2986 
2987   if (!hasOneBranchOpTo(entry, header))
2988     return emitOpError(
2989         "entry block must only have one 'spv.Branch' op to the second block");
2990 
2991   if (std::next(region.begin(), 3) == region.end())
2992     return emitOpError(
2993         "requires a loop continue block branching to the loop header block");
2994   // The second to last block is the loop continue block.
2995   Block &cont = *std::prev(region.end(), 2);
2996 
2997   // Make sure that we have a branch from the loop continue block to the loop
2998   // header block.
2999   if (llvm::none_of(
3000           llvm::seq<unsigned>(0, cont.getNumSuccessors()),
3001           [&](unsigned index) { return cont.getSuccessor(index) == &header; }))
3002     return emitOpError("second to last block must be the loop continue "
3003                        "block that branches to the loop header block");
3004 
3005   // Make sure that no other blocks (except the entry and loop continue block)
3006   // branches to the loop header block.
3007   for (auto &block : llvm::make_range(std::next(region.begin(), 2),
3008                                       std::prev(region.end(), 2))) {
3009     for (auto i : llvm::seq<unsigned>(0, block.getNumSuccessors())) {
3010       if (block.getSuccessor(i) == &header) {
3011         return emitOpError("can only have the entry and loop continue "
3012                            "block branching to the loop header block");
3013       }
3014     }
3015   }
3016 
3017   return success();
3018 }
3019 
3020 Block *spirv::LoopOp::getEntryBlock() {
3021   assert(!body().empty() && "op region should not be empty!");
3022   return &body().front();
3023 }
3024 
3025 Block *spirv::LoopOp::getHeaderBlock() {
3026   assert(!body().empty() && "op region should not be empty!");
3027   // The second block is the loop header block.
3028   return &*std::next(body().begin());
3029 }
3030 
3031 Block *spirv::LoopOp::getContinueBlock() {
3032   assert(!body().empty() && "op region should not be empty!");
3033   // The second to last block is the loop continue block.
3034   return &*std::prev(body().end(), 2);
3035 }
3036 
3037 Block *spirv::LoopOp::getMergeBlock() {
3038   assert(!body().empty() && "op region should not be empty!");
3039   // The last block is the loop merge block.
3040   return &body().back();
3041 }
3042 
3043 void spirv::LoopOp::addEntryAndMergeBlock() {
3044   assert(body().empty() && "entry and merge block already exist");
3045   body().push_back(new Block());
3046   auto *mergeBlock = new Block();
3047   body().push_back(mergeBlock);
3048   OpBuilder builder = OpBuilder::atBlockEnd(mergeBlock);
3049 
3050   // Add a spv.mlir.merge op into the merge block.
3051   builder.create<spirv::MergeOp>(getLoc());
3052 }
3053 
3054 //===----------------------------------------------------------------------===//
3055 // spv.MemoryBarrierOp
3056 //===----------------------------------------------------------------------===//
3057 
3058 LogicalResult spirv::MemoryBarrierOp::verify() {
3059   return verifyMemorySemantics(getOperation(), memory_semantics());
3060 }
3061 
3062 //===----------------------------------------------------------------------===//
3063 // spv.mlir.merge
3064 //===----------------------------------------------------------------------===//
3065 
3066 LogicalResult spirv::MergeOp::verify() {
3067   auto *parentOp = (*this)->getParentOp();
3068   if (!parentOp || !isa<spirv::SelectionOp, spirv::LoopOp>(parentOp))
3069     return emitOpError(
3070         "expected parent op to be 'spv.mlir.selection' or 'spv.mlir.loop'");
3071 
3072   // TODO: This check should be done in `verifyRegions` of parent op.
3073   Block &parentLastBlock = (*this)->getParentRegion()->back();
3074   if (getOperation() != parentLastBlock.getTerminator())
3075     return emitOpError("can only be used in the last block of "
3076                        "'spv.mlir.selection' or 'spv.mlir.loop'");
3077   return success();
3078 }
3079 
3080 //===----------------------------------------------------------------------===//
3081 // spv.module
3082 //===----------------------------------------------------------------------===//
3083 
3084 void spirv::ModuleOp::build(OpBuilder &builder, OperationState &state,
3085                             Optional<StringRef> name) {
3086   OpBuilder::InsertionGuard guard(builder);
3087   builder.createBlock(state.addRegion());
3088   if (name) {
3089     state.attributes.append(mlir::SymbolTable::getSymbolAttrName(),
3090                             builder.getStringAttr(*name));
3091   }
3092 }
3093 
3094 void spirv::ModuleOp::build(OpBuilder &builder, OperationState &state,
3095                             spirv::AddressingModel addressingModel,
3096                             spirv::MemoryModel memoryModel,
3097                             Optional<VerCapExtAttr> vceTriple,
3098                             Optional<StringRef> name) {
3099   state.addAttribute(
3100       "addressing_model",
3101       builder.getI32IntegerAttr(static_cast<int32_t>(addressingModel)));
3102   state.addAttribute("memory_model", builder.getI32IntegerAttr(
3103                                          static_cast<int32_t>(memoryModel)));
3104   OpBuilder::InsertionGuard guard(builder);
3105   builder.createBlock(state.addRegion());
3106   if (vceTriple)
3107     state.addAttribute(getVCETripleAttrName(), *vceTriple);
3108   if (name)
3109     state.addAttribute(mlir::SymbolTable::getSymbolAttrName(),
3110                        builder.getStringAttr(*name));
3111 }
3112 
3113 ParseResult spirv::ModuleOp::parse(OpAsmParser &parser, OperationState &state) {
3114   Region *body = state.addRegion();
3115 
3116   // If the name is present, parse it.
3117   StringAttr nameAttr;
3118   parser.parseOptionalSymbolName(
3119       nameAttr, mlir::SymbolTable::getSymbolAttrName(), state.attributes);
3120 
3121   // Parse attributes
3122   spirv::AddressingModel addrModel;
3123   spirv::MemoryModel memoryModel;
3124   if (::parseEnumKeywordAttr(addrModel, parser, state) ||
3125       ::parseEnumKeywordAttr(memoryModel, parser, state))
3126     return failure();
3127 
3128   if (succeeded(parser.parseOptionalKeyword("requires"))) {
3129     spirv::VerCapExtAttr vceTriple;
3130     if (parser.parseAttribute(vceTriple,
3131                               spirv::ModuleOp::getVCETripleAttrName(),
3132                               state.attributes))
3133       return failure();
3134   }
3135 
3136   if (parser.parseOptionalAttrDictWithKeyword(state.attributes))
3137     return failure();
3138 
3139   if (parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{}))
3140     return failure();
3141 
3142   // Make sure we have at least one block.
3143   if (body->empty())
3144     body->push_back(new Block());
3145 
3146   return success();
3147 }
3148 
3149 void spirv::ModuleOp::print(OpAsmPrinter &printer) {
3150   if (Optional<StringRef> name = getName()) {
3151     printer << ' ';
3152     printer.printSymbolName(*name);
3153   }
3154 
3155   SmallVector<StringRef, 2> elidedAttrs;
3156 
3157   printer << " " << spirv::stringifyAddressingModel(addressing_model()) << " "
3158           << spirv::stringifyMemoryModel(memory_model());
3159   auto addressingModelAttrName = spirv::attributeName<spirv::AddressingModel>();
3160   auto memoryModelAttrName = spirv::attributeName<spirv::MemoryModel>();
3161   elidedAttrs.assign({addressingModelAttrName, memoryModelAttrName,
3162                       mlir::SymbolTable::getSymbolAttrName()});
3163 
3164   if (Optional<spirv::VerCapExtAttr> triple = vce_triple()) {
3165     printer << " requires " << *triple;
3166     elidedAttrs.push_back(spirv::ModuleOp::getVCETripleAttrName());
3167   }
3168 
3169   printer.printOptionalAttrDictWithKeyword((*this)->getAttrs(), elidedAttrs);
3170   printer << ' ';
3171   printer.printRegion(getRegion());
3172 }
3173 
3174 LogicalResult spirv::ModuleOp::verifyRegions() {
3175   Dialect *dialect = (*this)->getDialect();
3176   DenseMap<std::pair<spirv::FuncOp, spirv::ExecutionModel>, spirv::EntryPointOp>
3177       entryPoints;
3178   mlir::SymbolTable table(*this);
3179 
3180   for (auto &op : *getBody()) {
3181     if (op.getDialect() != dialect)
3182       return op.emitError("'spv.module' can only contain spv.* ops");
3183 
3184     // For EntryPoint op, check that the function and execution model is not
3185     // duplicated in EntryPointOps. Also verify that the interface specified
3186     // comes from globalVariables here to make this check cheaper.
3187     if (auto entryPointOp = dyn_cast<spirv::EntryPointOp>(op)) {
3188       auto funcOp = table.lookup<spirv::FuncOp>(entryPointOp.fn());
3189       if (!funcOp) {
3190         return entryPointOp.emitError("function '")
3191                << entryPointOp.fn() << "' not found in 'spv.module'";
3192       }
3193       if (auto interface = entryPointOp.interface()) {
3194         for (Attribute varRef : interface) {
3195           auto varSymRef = varRef.dyn_cast<FlatSymbolRefAttr>();
3196           if (!varSymRef) {
3197             return entryPointOp.emitError(
3198                        "expected symbol reference for interface "
3199                        "specification instead of '")
3200                    << varRef;
3201           }
3202           auto variableOp =
3203               table.lookup<spirv::GlobalVariableOp>(varSymRef.getValue());
3204           if (!variableOp) {
3205             return entryPointOp.emitError("expected spv.GlobalVariable "
3206                                           "symbol reference instead of'")
3207                    << varSymRef << "'";
3208           }
3209         }
3210       }
3211 
3212       auto key = std::pair<spirv::FuncOp, spirv::ExecutionModel>(
3213           funcOp, entryPointOp.execution_model());
3214       auto entryPtIt = entryPoints.find(key);
3215       if (entryPtIt != entryPoints.end()) {
3216         return entryPointOp.emitError("duplicate of a previous EntryPointOp");
3217       }
3218       entryPoints[key] = entryPointOp;
3219     } else if (auto funcOp = dyn_cast<spirv::FuncOp>(op)) {
3220       if (funcOp.isExternal())
3221         return op.emitError("'spv.module' cannot contain external functions");
3222 
3223       // TODO: move this check to spv.func.
3224       for (auto &block : funcOp)
3225         for (auto &op : block) {
3226           if (op.getDialect() != dialect)
3227             return op.emitError(
3228                 "functions in 'spv.module' can only contain spv.* ops");
3229         }
3230     }
3231   }
3232 
3233   return success();
3234 }
3235 
3236 //===----------------------------------------------------------------------===//
3237 // spv.mlir.referenceof
3238 //===----------------------------------------------------------------------===//
3239 
3240 LogicalResult spirv::ReferenceOfOp::verify() {
3241   auto *specConstSym = SymbolTable::lookupNearestSymbolFrom(
3242       (*this)->getParentOp(), spec_constAttr());
3243   Type constType;
3244 
3245   auto specConstOp = dyn_cast_or_null<spirv::SpecConstantOp>(specConstSym);
3246   if (specConstOp)
3247     constType = specConstOp.default_value().getType();
3248 
3249   auto specConstCompositeOp =
3250       dyn_cast_or_null<spirv::SpecConstantCompositeOp>(specConstSym);
3251   if (specConstCompositeOp)
3252     constType = specConstCompositeOp.type();
3253 
3254   if (!specConstOp && !specConstCompositeOp)
3255     return emitOpError(
3256         "expected spv.SpecConstant or spv.SpecConstantComposite symbol");
3257 
3258   if (reference().getType() != constType)
3259     return emitOpError("result type mismatch with the referenced "
3260                        "specialization constant's type");
3261 
3262   return success();
3263 }
3264 
3265 //===----------------------------------------------------------------------===//
3266 // spv.Return
3267 //===----------------------------------------------------------------------===//
3268 
3269 LogicalResult spirv::ReturnOp::verify() {
3270   // Verification is performed in spv.func op.
3271   return success();
3272 }
3273 
3274 //===----------------------------------------------------------------------===//
3275 // spv.ReturnValue
3276 //===----------------------------------------------------------------------===//
3277 
3278 LogicalResult spirv::ReturnValueOp::verify() {
3279   // Verification is performed in spv.func op.
3280   return success();
3281 }
3282 
3283 //===----------------------------------------------------------------------===//
3284 // spv.Select
3285 //===----------------------------------------------------------------------===//
3286 
3287 LogicalResult spirv::SelectOp::verify() {
3288   if (auto conditionTy = condition().getType().dyn_cast<VectorType>()) {
3289     auto resultVectorTy = result().getType().dyn_cast<VectorType>();
3290     if (!resultVectorTy) {
3291       return emitOpError("result expected to be of vector type when "
3292                          "condition is of vector type");
3293     }
3294     if (resultVectorTy.getNumElements() != conditionTy.getNumElements()) {
3295       return emitOpError("result should have the same number of elements as "
3296                          "the condition when condition is of vector type");
3297     }
3298   }
3299   return success();
3300 }
3301 
3302 //===----------------------------------------------------------------------===//
3303 // spv.mlir.selection
3304 //===----------------------------------------------------------------------===//
3305 
3306 ParseResult spirv::SelectionOp::parse(OpAsmParser &parser,
3307                                       OperationState &state) {
3308   if (parseControlAttribute<spirv::SelectionControl>(parser, state))
3309     return failure();
3310   return parser.parseRegion(*state.addRegion(), /*arguments=*/{},
3311                             /*argTypes=*/{});
3312 }
3313 
3314 void spirv::SelectionOp::print(OpAsmPrinter &printer) {
3315   auto control = selection_control();
3316   if (control != spirv::SelectionControl::None)
3317     printer << " control(" << spirv::stringifySelectionControl(control) << ")";
3318   printer << ' ';
3319   printer.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
3320                       /*printBlockTerminators=*/true);
3321 }
3322 
3323 LogicalResult spirv::SelectionOp::verifyRegions() {
3324   auto *op = getOperation();
3325 
3326   // We need to verify that the blocks follow the following layout:
3327   //
3328   //                     +--------------+
3329   //                     | header block |
3330   //                     +--------------+
3331   //                          / | \
3332   //                           ...
3333   //
3334   //
3335   //         +---------+   +---------+   +---------+
3336   //         | case #0 |   | case #1 |   | case #2 |  ...
3337   //         +---------+   +---------+   +---------+
3338   //
3339   //
3340   //                           ...
3341   //                          \ | /
3342   //                            v
3343   //                     +-------------+
3344   //                     | merge block |
3345   //                     +-------------+
3346 
3347   auto &region = op->getRegion(0);
3348   // Allow empty region as a degenerated case, which can come from
3349   // optimizations.
3350   if (region.empty())
3351     return success();
3352 
3353   // The last block is the merge block.
3354   if (!isMergeBlock(region.back()))
3355     return emitOpError(
3356         "last block must be the merge block with only one 'spv.mlir.merge' op");
3357 
3358   if (std::next(region.begin()) == region.end())
3359     return emitOpError("must have a selection header block");
3360 
3361   return success();
3362 }
3363 
3364 Block *spirv::SelectionOp::getHeaderBlock() {
3365   assert(!body().empty() && "op region should not be empty!");
3366   // The first block is the loop header block.
3367   return &body().front();
3368 }
3369 
3370 Block *spirv::SelectionOp::getMergeBlock() {
3371   assert(!body().empty() && "op region should not be empty!");
3372   // The last block is the loop merge block.
3373   return &body().back();
3374 }
3375 
3376 void spirv::SelectionOp::addMergeBlock() {
3377   assert(body().empty() && "entry and merge block already exist");
3378   auto *mergeBlock = new Block();
3379   body().push_back(mergeBlock);
3380   OpBuilder builder = OpBuilder::atBlockEnd(mergeBlock);
3381 
3382   // Add a spv.mlir.merge op into the merge block.
3383   builder.create<spirv::MergeOp>(getLoc());
3384 }
3385 
3386 spirv::SelectionOp spirv::SelectionOp::createIfThen(
3387     Location loc, Value condition,
3388     function_ref<void(OpBuilder &builder)> thenBody, OpBuilder &builder) {
3389   auto selectionOp =
3390       builder.create<spirv::SelectionOp>(loc, spirv::SelectionControl::None);
3391 
3392   selectionOp.addMergeBlock();
3393   Block *mergeBlock = selectionOp.getMergeBlock();
3394   Block *thenBlock = nullptr;
3395 
3396   // Build the "then" block.
3397   {
3398     OpBuilder::InsertionGuard guard(builder);
3399     thenBlock = builder.createBlock(mergeBlock);
3400     thenBody(builder);
3401     builder.create<spirv::BranchOp>(loc, mergeBlock);
3402   }
3403 
3404   // Build the header block.
3405   {
3406     OpBuilder::InsertionGuard guard(builder);
3407     builder.createBlock(thenBlock);
3408     builder.create<spirv::BranchConditionalOp>(
3409         loc, condition, thenBlock,
3410         /*trueArguments=*/ArrayRef<Value>(), mergeBlock,
3411         /*falseArguments=*/ArrayRef<Value>());
3412   }
3413 
3414   return selectionOp;
3415 }
3416 
3417 //===----------------------------------------------------------------------===//
3418 // spv.SpecConstant
3419 //===----------------------------------------------------------------------===//
3420 
3421 ParseResult spirv::SpecConstantOp::parse(OpAsmParser &parser,
3422                                          OperationState &state) {
3423   StringAttr nameAttr;
3424   Attribute valueAttr;
3425 
3426   if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
3427                              state.attributes))
3428     return failure();
3429 
3430   // Parse optional spec_id.
3431   if (succeeded(parser.parseOptionalKeyword(kSpecIdAttrName))) {
3432     IntegerAttr specIdAttr;
3433     if (parser.parseLParen() ||
3434         parser.parseAttribute(specIdAttr, kSpecIdAttrName, state.attributes) ||
3435         parser.parseRParen())
3436       return failure();
3437   }
3438 
3439   if (parser.parseEqual() ||
3440       parser.parseAttribute(valueAttr, kDefaultValueAttrName, state.attributes))
3441     return failure();
3442 
3443   return success();
3444 }
3445 
3446 void spirv::SpecConstantOp::print(OpAsmPrinter &printer) {
3447   printer << ' ';
3448   printer.printSymbolName(sym_name());
3449   if (auto specID = (*this)->getAttrOfType<IntegerAttr>(kSpecIdAttrName))
3450     printer << ' ' << kSpecIdAttrName << '(' << specID.getInt() << ')';
3451   printer << " = " << default_value();
3452 }
3453 
3454 LogicalResult spirv::SpecConstantOp::verify() {
3455   if (auto specID = (*this)->getAttrOfType<IntegerAttr>(kSpecIdAttrName))
3456     if (specID.getValue().isNegative())
3457       return emitOpError("SpecId cannot be negative");
3458 
3459   auto value = default_value();
3460   if (value.isa<IntegerAttr, FloatAttr>()) {
3461     // Make sure bitwidth is allowed.
3462     if (!value.getType().isa<spirv::SPIRVType>())
3463       return emitOpError("default value bitwidth disallowed");
3464     return success();
3465   }
3466   return emitOpError(
3467       "default value can only be a bool, integer, or float scalar");
3468 }
3469 
3470 //===----------------------------------------------------------------------===//
3471 // spv.StoreOp
3472 //===----------------------------------------------------------------------===//
3473 
3474 ParseResult spirv::StoreOp::parse(OpAsmParser &parser, OperationState &state) {
3475   // Parse the storage class specification
3476   spirv::StorageClass storageClass;
3477   SmallVector<OpAsmParser::UnresolvedOperand, 2> operandInfo;
3478   auto loc = parser.getCurrentLocation();
3479   Type elementType;
3480   if (parseEnumStrAttr(storageClass, parser) ||
3481       parser.parseOperandList(operandInfo, 2) ||
3482       parseMemoryAccessAttributes(parser, state) || parser.parseColon() ||
3483       parser.parseType(elementType)) {
3484     return failure();
3485   }
3486 
3487   auto ptrType = spirv::PointerType::get(elementType, storageClass);
3488   if (parser.resolveOperands(operandInfo, {ptrType, elementType}, loc,
3489                              state.operands)) {
3490     return failure();
3491   }
3492   return success();
3493 }
3494 
3495 void spirv::StoreOp::print(OpAsmPrinter &printer) {
3496   SmallVector<StringRef, 4> elidedAttrs;
3497   StringRef sc = stringifyStorageClass(
3498       ptr().getType().cast<spirv::PointerType>().getStorageClass());
3499   printer << " \"" << sc << "\" " << ptr() << ", " << value();
3500 
3501   printMemoryAccessAttribute(*this, printer, elidedAttrs);
3502 
3503   printer << " : " << value().getType();
3504   printer.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs);
3505 }
3506 
3507 LogicalResult spirv::StoreOp::verify() {
3508   // SPIR-V spec : "Pointer is the pointer to store through. Its type must be an
3509   // OpTypePointer whose Type operand is the same as the type of Object."
3510   if (failed(verifyLoadStorePtrAndValTypes(*this, ptr(), value())))
3511     return failure();
3512   return verifyMemoryAccessAttribute(*this);
3513 }
3514 
3515 //===----------------------------------------------------------------------===//
3516 // spv.Unreachable
3517 //===----------------------------------------------------------------------===//
3518 
3519 LogicalResult spirv::UnreachableOp::verify() {
3520   auto *block = (*this)->getBlock();
3521   // Fast track: if this is in entry block, its invalid. Otherwise, if no
3522   // predecessors, it's valid.
3523   if (block->isEntryBlock())
3524     return emitOpError("cannot be used in reachable block");
3525   if (block->hasNoPredecessors())
3526     return success();
3527 
3528   // TODO: further verification needs to analyze reachability from
3529   // the entry block.
3530 
3531   return success();
3532 }
3533 
3534 //===----------------------------------------------------------------------===//
3535 // spv.Variable
3536 //===----------------------------------------------------------------------===//
3537 
3538 ParseResult spirv::VariableOp::parse(OpAsmParser &parser,
3539                                      OperationState &state) {
3540   // Parse optional initializer
3541   Optional<OpAsmParser::UnresolvedOperand> initInfo;
3542   if (succeeded(parser.parseOptionalKeyword("init"))) {
3543     initInfo = OpAsmParser::UnresolvedOperand();
3544     if (parser.parseLParen() || parser.parseOperand(*initInfo) ||
3545         parser.parseRParen())
3546       return failure();
3547   }
3548 
3549   if (parseVariableDecorations(parser, state)) {
3550     return failure();
3551   }
3552 
3553   // Parse result pointer type
3554   Type type;
3555   if (parser.parseColon())
3556     return failure();
3557   auto loc = parser.getCurrentLocation();
3558   if (parser.parseType(type))
3559     return failure();
3560 
3561   auto ptrType = type.dyn_cast<spirv::PointerType>();
3562   if (!ptrType)
3563     return parser.emitError(loc, "expected spv.ptr type");
3564   state.addTypes(ptrType);
3565 
3566   // Resolve the initializer operand
3567   if (initInfo) {
3568     if (parser.resolveOperand(*initInfo, ptrType.getPointeeType(),
3569                               state.operands))
3570       return failure();
3571   }
3572 
3573   auto attr = parser.getBuilder().getI32IntegerAttr(
3574       llvm::bit_cast<int32_t>(ptrType.getStorageClass()));
3575   state.addAttribute(spirv::attributeName<spirv::StorageClass>(), attr);
3576 
3577   return success();
3578 }
3579 
3580 void spirv::VariableOp::print(OpAsmPrinter &printer) {
3581   SmallVector<StringRef, 4> elidedAttrs{
3582       spirv::attributeName<spirv::StorageClass>()};
3583   // Print optional initializer
3584   if (getNumOperands() != 0)
3585     printer << " init(" << initializer() << ")";
3586 
3587   printVariableDecorations(*this, printer, elidedAttrs);
3588   printer << " : " << getType();
3589 }
3590 
3591 LogicalResult spirv::VariableOp::verify() {
3592   // SPIR-V spec: "Storage Class is the Storage Class of the memory holding the
3593   // object. It cannot be Generic. It must be the same as the Storage Class
3594   // operand of the Result Type."
3595   if (storage_class() != spirv::StorageClass::Function) {
3596     return emitOpError(
3597         "can only be used to model function-level variables. Use "
3598         "spv.GlobalVariable for module-level variables.");
3599   }
3600 
3601   auto pointerType = pointer().getType().cast<spirv::PointerType>();
3602   if (storage_class() != pointerType.getStorageClass())
3603     return emitOpError(
3604         "storage class must match result pointer's storage class");
3605 
3606   if (getNumOperands() != 0) {
3607     // SPIR-V spec: "Initializer must be an <id> from a constant instruction or
3608     // a global (module scope) OpVariable instruction".
3609     auto *initOp = getOperand(0).getDefiningOp();
3610     if (!initOp || !isa<spirv::ConstantOp,    // for normal constant
3611                         spirv::ReferenceOfOp, // for spec constant
3612                         spirv::AddressOfOp>(initOp))
3613       return emitOpError("initializer must be the result of a "
3614                          "constant or spv.GlobalVariable op");
3615   }
3616 
3617   // TODO: generate these strings using ODS.
3618   auto *op = getOperation();
3619   auto descriptorSetName = llvm::convertToSnakeFromCamelCase(
3620       stringifyDecoration(spirv::Decoration::DescriptorSet));
3621   auto bindingName = llvm::convertToSnakeFromCamelCase(
3622       stringifyDecoration(spirv::Decoration::Binding));
3623   auto builtInName = llvm::convertToSnakeFromCamelCase(
3624       stringifyDecoration(spirv::Decoration::BuiltIn));
3625 
3626   for (const auto &attr : {descriptorSetName, bindingName, builtInName}) {
3627     if (op->getAttr(attr))
3628       return emitOpError("cannot have '")
3629              << attr << "' attribute (only allowed in spv.GlobalVariable)";
3630   }
3631 
3632   return success();
3633 }
3634 
3635 //===----------------------------------------------------------------------===//
3636 // spv.VectorShuffle
3637 //===----------------------------------------------------------------------===//
3638 
3639 LogicalResult spirv::VectorShuffleOp::verify() {
3640   VectorType resultType = getType().cast<VectorType>();
3641 
3642   size_t numResultElements = resultType.getNumElements();
3643   if (numResultElements != components().size())
3644     return emitOpError("result type element count (")
3645            << numResultElements
3646            << ") mismatch with the number of component selectors ("
3647            << components().size() << ")";
3648 
3649   size_t totalSrcElements =
3650       vector1().getType().cast<VectorType>().getNumElements() +
3651       vector2().getType().cast<VectorType>().getNumElements();
3652 
3653   for (const auto &selector : components().getAsValueRange<IntegerAttr>()) {
3654     uint32_t index = selector.getZExtValue();
3655     if (index >= totalSrcElements &&
3656         index != std::numeric_limits<uint32_t>().max())
3657       return emitOpError("component selector ")
3658              << index << " out of range: expected to be in [0, "
3659              << totalSrcElements << ") or 0xffffffff";
3660   }
3661   return success();
3662 }
3663 
3664 //===----------------------------------------------------------------------===//
3665 // spv.CooperativeMatrixLoadNV
3666 //===----------------------------------------------------------------------===//
3667 
3668 ParseResult spirv::CooperativeMatrixLoadNVOp::parse(OpAsmParser &parser,
3669                                                     OperationState &state) {
3670   SmallVector<OpAsmParser::UnresolvedOperand, 3> operandInfo;
3671   Type strideType = parser.getBuilder().getIntegerType(32);
3672   Type columnMajorType = parser.getBuilder().getIntegerType(1);
3673   Type ptrType;
3674   Type elementType;
3675   if (parser.parseOperandList(operandInfo, 3) ||
3676       parseMemoryAccessAttributes(parser, state) || parser.parseColon() ||
3677       parser.parseType(ptrType) || parser.parseKeywordType("as", elementType)) {
3678     return failure();
3679   }
3680   if (parser.resolveOperands(operandInfo,
3681                              {ptrType, strideType, columnMajorType},
3682                              parser.getNameLoc(), state.operands)) {
3683     return failure();
3684   }
3685 
3686   state.addTypes(elementType);
3687   return success();
3688 }
3689 
3690 void spirv::CooperativeMatrixLoadNVOp::print(OpAsmPrinter &printer) {
3691   printer << " " << pointer() << ", " << stride() << ", " << columnmajor();
3692   // Print optional memory access attribute.
3693   if (auto memAccess = memory_access())
3694     printer << " [\"" << stringifyMemoryAccess(*memAccess) << "\"]";
3695   printer << " : " << pointer().getType() << " as " << getType();
3696 }
3697 
3698 static LogicalResult verifyPointerAndCoopMatrixType(Operation *op, Type pointer,
3699                                                     Type coopMatrix) {
3700   Type pointeeType = pointer.cast<spirv::PointerType>().getPointeeType();
3701   if (!pointeeType.isa<spirv::ScalarType>() && !pointeeType.isa<VectorType>())
3702     return op->emitError(
3703                "Pointer must point to a scalar or vector type but provided ")
3704            << pointeeType;
3705   spirv::StorageClass storage =
3706       pointer.cast<spirv::PointerType>().getStorageClass();
3707   if (storage != spirv::StorageClass::Workgroup &&
3708       storage != spirv::StorageClass::StorageBuffer &&
3709       storage != spirv::StorageClass::PhysicalStorageBuffer)
3710     return op->emitError(
3711                "Pointer storage class must be Workgroup, StorageBuffer or "
3712                "PhysicalStorageBufferEXT but provided ")
3713            << stringifyStorageClass(storage);
3714   return success();
3715 }
3716 
3717 LogicalResult spirv::CooperativeMatrixLoadNVOp::verify() {
3718   return verifyPointerAndCoopMatrixType(*this, pointer().getType(),
3719                                         result().getType());
3720 }
3721 
3722 //===----------------------------------------------------------------------===//
3723 // spv.CooperativeMatrixStoreNV
3724 //===----------------------------------------------------------------------===//
3725 
3726 ParseResult spirv::CooperativeMatrixStoreNVOp::parse(OpAsmParser &parser,
3727                                                      OperationState &state) {
3728   SmallVector<OpAsmParser::UnresolvedOperand, 4> operandInfo;
3729   Type strideType = parser.getBuilder().getIntegerType(32);
3730   Type columnMajorType = parser.getBuilder().getIntegerType(1);
3731   Type ptrType;
3732   Type elementType;
3733   if (parser.parseOperandList(operandInfo, 4) ||
3734       parseMemoryAccessAttributes(parser, state) || parser.parseColon() ||
3735       parser.parseType(ptrType) || parser.parseComma() ||
3736       parser.parseType(elementType)) {
3737     return failure();
3738   }
3739   if (parser.resolveOperands(
3740           operandInfo, {ptrType, elementType, strideType, columnMajorType},
3741           parser.getNameLoc(), state.operands)) {
3742     return failure();
3743   }
3744 
3745   return success();
3746 }
3747 
3748 void spirv::CooperativeMatrixStoreNVOp::print(OpAsmPrinter &printer) {
3749   printer << " " << pointer() << ", " << object() << ", " << stride() << ", "
3750           << columnmajor();
3751   // Print optional memory access attribute.
3752   if (auto memAccess = memory_access())
3753     printer << " [\"" << stringifyMemoryAccess(*memAccess) << "\"]";
3754   printer << " : " << pointer().getType() << ", " << getOperand(1).getType();
3755 }
3756 
3757 LogicalResult spirv::CooperativeMatrixStoreNVOp::verify() {
3758   return verifyPointerAndCoopMatrixType(*this, pointer().getType(),
3759                                         object().getType());
3760 }
3761 
3762 //===----------------------------------------------------------------------===//
3763 // spv.CooperativeMatrixMulAddNV
3764 //===----------------------------------------------------------------------===//
3765 
3766 static LogicalResult
3767 verifyCoopMatrixMulAdd(spirv::CooperativeMatrixMulAddNVOp op) {
3768   if (op.c().getType() != op.result().getType())
3769     return op.emitOpError("result and third operand must have the same type");
3770   auto typeA = op.a().getType().cast<spirv::CooperativeMatrixNVType>();
3771   auto typeB = op.b().getType().cast<spirv::CooperativeMatrixNVType>();
3772   auto typeC = op.c().getType().cast<spirv::CooperativeMatrixNVType>();
3773   auto typeR = op.result().getType().cast<spirv::CooperativeMatrixNVType>();
3774   if (typeA.getRows() != typeR.getRows() ||
3775       typeA.getColumns() != typeB.getRows() ||
3776       typeB.getColumns() != typeR.getColumns())
3777     return op.emitOpError("matrix size must match");
3778   if (typeR.getScope() != typeA.getScope() ||
3779       typeR.getScope() != typeB.getScope() ||
3780       typeR.getScope() != typeC.getScope())
3781     return op.emitOpError("matrix scope must match");
3782   if (typeA.getElementType() != typeB.getElementType() ||
3783       typeR.getElementType() != typeC.getElementType())
3784     return op.emitOpError("matrix element type must match");
3785   return success();
3786 }
3787 
3788 LogicalResult spirv::CooperativeMatrixMulAddNVOp::verify() {
3789   return verifyCoopMatrixMulAdd(*this);
3790 }
3791 
3792 //===----------------------------------------------------------------------===//
3793 // spv.MatrixTimesScalar
3794 //===----------------------------------------------------------------------===//
3795 
3796 LogicalResult spirv::MatrixTimesScalarOp::verify() {
3797   // We already checked that result and matrix are both of matrix type in the
3798   // auto-generated verify method.
3799 
3800   auto inputMatrix = matrix().getType().cast<spirv::MatrixType>();
3801   auto resultMatrix = result().getType().cast<spirv::MatrixType>();
3802 
3803   // Check that the scalar type is the same as the matrix element type.
3804   if (scalar().getType() != inputMatrix.getElementType())
3805     return emitError("input matrix components' type and scaling value must "
3806                      "have the same type");
3807 
3808   // Note that the next three checks could be done using the AllTypesMatch
3809   // trait in the Op definition file but it generates a vague error message.
3810 
3811   // Check that the input and result matrices have the same columns' count
3812   if (inputMatrix.getNumColumns() != resultMatrix.getNumColumns())
3813     return emitError("input and result matrices must have the same "
3814                      "number of columns");
3815 
3816   // Check that the input and result matrices' have the same rows count
3817   if (inputMatrix.getNumRows() != resultMatrix.getNumRows())
3818     return emitError("input and result matrices' columns must have "
3819                      "the same size");
3820 
3821   // Check that the input and result matrices' have the same component type
3822   if (inputMatrix.getElementType() != resultMatrix.getElementType())
3823     return emitError("input and result matrices' columns must have "
3824                      "the same component type");
3825 
3826   return success();
3827 }
3828 
3829 //===----------------------------------------------------------------------===//
3830 // spv.CopyMemory
3831 //===----------------------------------------------------------------------===//
3832 
3833 void spirv::CopyMemoryOp::print(OpAsmPrinter &printer) {
3834   printer << ' ';
3835 
3836   StringRef targetStorageClass = stringifyStorageClass(
3837       target().getType().cast<spirv::PointerType>().getStorageClass());
3838   printer << " \"" << targetStorageClass << "\" " << target() << ", ";
3839 
3840   StringRef sourceStorageClass = stringifyStorageClass(
3841       source().getType().cast<spirv::PointerType>().getStorageClass());
3842   printer << " \"" << sourceStorageClass << "\" " << source();
3843 
3844   SmallVector<StringRef, 4> elidedAttrs;
3845   printMemoryAccessAttribute(*this, printer, elidedAttrs);
3846   printSourceMemoryAccessAttribute(*this, printer, elidedAttrs,
3847                                    source_memory_access(), source_alignment());
3848 
3849   printer.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs);
3850 
3851   Type pointeeType =
3852       target().getType().cast<spirv::PointerType>().getPointeeType();
3853   printer << " : " << pointeeType;
3854 }
3855 
3856 ParseResult spirv::CopyMemoryOp::parse(OpAsmParser &parser,
3857                                        OperationState &state) {
3858   spirv::StorageClass targetStorageClass;
3859   OpAsmParser::UnresolvedOperand targetPtrInfo;
3860 
3861   spirv::StorageClass sourceStorageClass;
3862   OpAsmParser::UnresolvedOperand sourcePtrInfo;
3863 
3864   Type elementType;
3865 
3866   if (parseEnumStrAttr(targetStorageClass, parser) ||
3867       parser.parseOperand(targetPtrInfo) || parser.parseComma() ||
3868       parseEnumStrAttr(sourceStorageClass, parser) ||
3869       parser.parseOperand(sourcePtrInfo) ||
3870       parseMemoryAccessAttributes(parser, state)) {
3871     return failure();
3872   }
3873 
3874   if (!parser.parseOptionalComma()) {
3875     // Parse 2nd memory access attributes.
3876     if (parseSourceMemoryAccessAttributes(parser, state)) {
3877       return failure();
3878     }
3879   }
3880 
3881   if (parser.parseColon() || parser.parseType(elementType))
3882     return failure();
3883 
3884   if (parser.parseOptionalAttrDict(state.attributes))
3885     return failure();
3886 
3887   auto targetPtrType = spirv::PointerType::get(elementType, targetStorageClass);
3888   auto sourcePtrType = spirv::PointerType::get(elementType, sourceStorageClass);
3889 
3890   if (parser.resolveOperand(targetPtrInfo, targetPtrType, state.operands) ||
3891       parser.resolveOperand(sourcePtrInfo, sourcePtrType, state.operands)) {
3892     return failure();
3893   }
3894 
3895   return success();
3896 }
3897 
3898 LogicalResult spirv::CopyMemoryOp::verify() {
3899   Type targetType =
3900       target().getType().cast<spirv::PointerType>().getPointeeType();
3901 
3902   Type sourceType =
3903       source().getType().cast<spirv::PointerType>().getPointeeType();
3904 
3905   if (targetType != sourceType)
3906     return emitOpError("both operands must be pointers to the same type");
3907 
3908   if (failed(verifyMemoryAccessAttribute(*this)))
3909     return failure();
3910 
3911   // TODO - According to the spec:
3912   //
3913   // If two masks are present, the first applies to Target and cannot include
3914   // MakePointerVisible, and the second applies to Source and cannot include
3915   // MakePointerAvailable.
3916   //
3917   // Add such verification here.
3918 
3919   return verifySourceMemoryAccessAttribute(*this);
3920 }
3921 
3922 //===----------------------------------------------------------------------===//
3923 // spv.Transpose
3924 //===----------------------------------------------------------------------===//
3925 
3926 LogicalResult spirv::TransposeOp::verify() {
3927   auto inputMatrix = matrix().getType().cast<spirv::MatrixType>();
3928   auto resultMatrix = result().getType().cast<spirv::MatrixType>();
3929 
3930   // Verify that the input and output matrices have correct shapes.
3931   if (inputMatrix.getNumRows() != resultMatrix.getNumColumns())
3932     return emitError("input matrix rows count must be equal to "
3933                      "output matrix columns count");
3934 
3935   if (inputMatrix.getNumColumns() != resultMatrix.getNumRows())
3936     return emitError("input matrix columns count must be equal to "
3937                      "output matrix rows count");
3938 
3939   // Verify that the input and output matrices have the same component type
3940   if (inputMatrix.getElementType() != resultMatrix.getElementType())
3941     return emitError("input and output matrices must have the same "
3942                      "component type");
3943 
3944   return success();
3945 }
3946 
3947 //===----------------------------------------------------------------------===//
3948 // spv.MatrixTimesMatrix
3949 //===----------------------------------------------------------------------===//
3950 
3951 LogicalResult spirv::MatrixTimesMatrixOp::verify() {
3952   auto leftMatrix = leftmatrix().getType().cast<spirv::MatrixType>();
3953   auto rightMatrix = rightmatrix().getType().cast<spirv::MatrixType>();
3954   auto resultMatrix = result().getType().cast<spirv::MatrixType>();
3955 
3956   // left matrix columns' count and right matrix rows' count must be equal
3957   if (leftMatrix.getNumColumns() != rightMatrix.getNumRows())
3958     return emitError("left matrix columns' count must be equal to "
3959                      "the right matrix rows' count");
3960 
3961   // right and result matrices columns' count must be the same
3962   if (rightMatrix.getNumColumns() != resultMatrix.getNumColumns())
3963     return emitError(
3964         "right and result matrices must have equal columns' count");
3965 
3966   // right and result matrices component type must be the same
3967   if (rightMatrix.getElementType() != resultMatrix.getElementType())
3968     return emitError("right and result matrices' component type must"
3969                      " be the same");
3970 
3971   // left and result matrices component type must be the same
3972   if (leftMatrix.getElementType() != resultMatrix.getElementType())
3973     return emitError("left and result matrices' component type"
3974                      " must be the same");
3975 
3976   // left and result matrices rows count must be the same
3977   if (leftMatrix.getNumRows() != resultMatrix.getNumRows())
3978     return emitError("left and result matrices must have equal rows' count");
3979 
3980   return success();
3981 }
3982 
3983 //===----------------------------------------------------------------------===//
3984 // spv.SpecConstantComposite
3985 //===----------------------------------------------------------------------===//
3986 
3987 ParseResult spirv::SpecConstantCompositeOp::parse(OpAsmParser &parser,
3988                                                   OperationState &state) {
3989 
3990   StringAttr compositeName;
3991   if (parser.parseSymbolName(compositeName, SymbolTable::getSymbolAttrName(),
3992                              state.attributes))
3993     return failure();
3994 
3995   if (parser.parseLParen())
3996     return failure();
3997 
3998   SmallVector<Attribute, 4> constituents;
3999 
4000   do {
4001     // The name of the constituent attribute isn't important
4002     const char *attrName = "spec_const";
4003     FlatSymbolRefAttr specConstRef;
4004     NamedAttrList attrs;
4005 
4006     if (parser.parseAttribute(specConstRef, Type(), attrName, attrs))
4007       return failure();
4008 
4009     constituents.push_back(specConstRef);
4010   } while (!parser.parseOptionalComma());
4011 
4012   if (parser.parseRParen())
4013     return failure();
4014 
4015   state.addAttribute(kCompositeSpecConstituentsName,
4016                      parser.getBuilder().getArrayAttr(constituents));
4017 
4018   Type type;
4019   if (parser.parseColonType(type))
4020     return failure();
4021 
4022   state.addAttribute(kTypeAttrName, TypeAttr::get(type));
4023 
4024   return success();
4025 }
4026 
4027 void spirv::SpecConstantCompositeOp::print(OpAsmPrinter &printer) {
4028   printer << " ";
4029   printer.printSymbolName(sym_name());
4030   printer << " (";
4031   auto constituents = this->constituents().getValue();
4032 
4033   if (!constituents.empty())
4034     llvm::interleaveComma(constituents, printer);
4035 
4036   printer << ") : " << type();
4037 }
4038 
4039 LogicalResult spirv::SpecConstantCompositeOp::verify() {
4040   auto cType = type().dyn_cast<spirv::CompositeType>();
4041   auto constituents = this->constituents().getValue();
4042 
4043   if (!cType)
4044     return emitError("result type must be a composite type, but provided ")
4045            << type();
4046 
4047   if (cType.isa<spirv::CooperativeMatrixNVType>())
4048     return emitError("unsupported composite type  ") << cType;
4049   if (constituents.size() != cType.getNumElements())
4050     return emitError("has incorrect number of operands: expected ")
4051            << cType.getNumElements() << ", but provided "
4052            << constituents.size();
4053 
4054   for (auto index : llvm::seq<uint32_t>(0, constituents.size())) {
4055     auto constituent = constituents[index].cast<FlatSymbolRefAttr>();
4056 
4057     auto constituentSpecConstOp =
4058         dyn_cast<spirv::SpecConstantOp>(SymbolTable::lookupNearestSymbolFrom(
4059             (*this)->getParentOp(), constituent.getAttr()));
4060 
4061     if (constituentSpecConstOp.default_value().getType() !=
4062         cType.getElementType(index))
4063       return emitError("has incorrect types of operands: expected ")
4064              << cType.getElementType(index) << ", but provided "
4065              << constituentSpecConstOp.default_value().getType();
4066   }
4067 
4068   return success();
4069 }
4070 
4071 //===----------------------------------------------------------------------===//
4072 // spv.SpecConstantOperation
4073 //===----------------------------------------------------------------------===//
4074 
4075 ParseResult spirv::SpecConstantOperationOp::parse(OpAsmParser &parser,
4076                                                   OperationState &state) {
4077   Region *body = state.addRegion();
4078 
4079   if (parser.parseKeyword("wraps"))
4080     return failure();
4081 
4082   body->push_back(new Block);
4083   Block &block = body->back();
4084   Operation *wrappedOp = parser.parseGenericOperation(&block, block.begin());
4085 
4086   if (!wrappedOp)
4087     return failure();
4088 
4089   OpBuilder builder(parser.getContext());
4090   builder.setInsertionPointToEnd(&block);
4091   builder.create<spirv::YieldOp>(wrappedOp->getLoc(), wrappedOp->getResult(0));
4092   state.location = wrappedOp->getLoc();
4093 
4094   state.addTypes(wrappedOp->getResult(0).getType());
4095 
4096   if (parser.parseOptionalAttrDict(state.attributes))
4097     return failure();
4098 
4099   return success();
4100 }
4101 
4102 void spirv::SpecConstantOperationOp::print(OpAsmPrinter &printer) {
4103   printer << " wraps ";
4104   printer.printGenericOp(&body().front().front());
4105 }
4106 
4107 LogicalResult spirv::SpecConstantOperationOp::verifyRegions() {
4108   Block &block = getRegion().getBlocks().front();
4109 
4110   if (block.getOperations().size() != 2)
4111     return emitOpError("expected exactly 2 nested ops");
4112 
4113   Operation &enclosedOp = block.getOperations().front();
4114 
4115   if (!enclosedOp.hasTrait<OpTrait::spirv::UsableInSpecConstantOp>())
4116     return emitOpError("invalid enclosed op");
4117 
4118   for (auto operand : enclosedOp.getOperands())
4119     if (!isa<spirv::ConstantOp, spirv::ReferenceOfOp,
4120              spirv::SpecConstantOperationOp>(operand.getDefiningOp()))
4121       return emitOpError(
4122           "invalid operand, must be defined by a constant operation");
4123 
4124   return success();
4125 }
4126 
4127 //===----------------------------------------------------------------------===//
4128 // spv.GLSL.FrexpStruct
4129 //===----------------------------------------------------------------------===//
4130 
4131 LogicalResult spirv::GLSLFrexpStructOp::verify() {
4132   spirv::StructType structTy = result().getType().dyn_cast<spirv::StructType>();
4133 
4134   if (structTy.getNumElements() != 2)
4135     return emitError("result type must be a struct type with two memebers");
4136 
4137   Type significandTy = structTy.getElementType(0);
4138   Type exponentTy = structTy.getElementType(1);
4139   VectorType exponentVecTy = exponentTy.dyn_cast<VectorType>();
4140   IntegerType exponentIntTy = exponentTy.dyn_cast<IntegerType>();
4141 
4142   Type operandTy = operand().getType();
4143   VectorType operandVecTy = operandTy.dyn_cast<VectorType>();
4144   FloatType operandFTy = operandTy.dyn_cast<FloatType>();
4145 
4146   if (significandTy != operandTy)
4147     return emitError("member zero of the resulting struct type must be the "
4148                      "same type as the operand");
4149 
4150   if (exponentVecTy) {
4151     IntegerType componentIntTy =
4152         exponentVecTy.getElementType().dyn_cast<IntegerType>();
4153     if (!(componentIntTy && componentIntTy.getWidth() == 32))
4154       return emitError("member one of the resulting struct type must"
4155                        "be a scalar or vector of 32 bit integer type");
4156   } else if (!(exponentIntTy && exponentIntTy.getWidth() == 32)) {
4157     return emitError("member one of the resulting struct type "
4158                      "must be a scalar or vector of 32 bit integer type");
4159   }
4160 
4161   // Check that the two member types have the same number of components
4162   if (operandVecTy && exponentVecTy &&
4163       (exponentVecTy.getNumElements() == operandVecTy.getNumElements()))
4164     return success();
4165 
4166   if (operandFTy && exponentIntTy)
4167     return success();
4168 
4169   return emitError("member one of the resulting struct type must have the same "
4170                    "number of components as the operand type");
4171 }
4172 
4173 //===----------------------------------------------------------------------===//
4174 // spv.GLSL.Ldexp
4175 //===----------------------------------------------------------------------===//
4176 
4177 LogicalResult spirv::GLSLLdexpOp::verify() {
4178   Type significandType = x().getType();
4179   Type exponentType = exp().getType();
4180 
4181   if (significandType.isa<FloatType>() != exponentType.isa<IntegerType>())
4182     return emitOpError("operands must both be scalars or vectors");
4183 
4184   auto getNumElements = [](Type type) -> unsigned {
4185     if (auto vectorType = type.dyn_cast<VectorType>())
4186       return vectorType.getNumElements();
4187     return 1;
4188   };
4189 
4190   if (getNumElements(significandType) != getNumElements(exponentType))
4191     return emitOpError("operands must have the same number of elements");
4192 
4193   return success();
4194 }
4195 
4196 //===----------------------------------------------------------------------===//
4197 // spv.ImageDrefGather
4198 //===----------------------------------------------------------------------===//
4199 
4200 LogicalResult spirv::ImageDrefGatherOp::verify() {
4201   VectorType resultType = result().getType().cast<VectorType>();
4202   auto sampledImageType =
4203       sampledimage().getType().cast<spirv::SampledImageType>();
4204   auto imageType = sampledImageType.getImageType().cast<spirv::ImageType>();
4205 
4206   if (resultType.getNumElements() != 4)
4207     return emitOpError("result type must be a vector of four components");
4208 
4209   Type elementType = resultType.getElementType();
4210   Type sampledElementType = imageType.getElementType();
4211   if (!sampledElementType.isa<NoneType>() && elementType != sampledElementType)
4212     return emitOpError(
4213         "the component type of result must be the same as sampled type of the "
4214         "underlying image type");
4215 
4216   spirv::Dim imageDim = imageType.getDim();
4217   spirv::ImageSamplingInfo imageMS = imageType.getSamplingInfo();
4218 
4219   if (imageDim != spirv::Dim::Dim2D && imageDim != spirv::Dim::Cube &&
4220       imageDim != spirv::Dim::Rect)
4221     return emitOpError(
4222         "the Dim operand of the underlying image type must be 2D, Cube, or "
4223         "Rect");
4224 
4225   if (imageMS != spirv::ImageSamplingInfo::SingleSampled)
4226     return emitOpError("the MS operand of the underlying image type must be 0");
4227 
4228   spirv::ImageOperandsAttr attr = imageoperandsAttr();
4229   auto operandArguments = operand_arguments();
4230 
4231   return verifyImageOperands(*this, attr, operandArguments);
4232 }
4233 
4234 //===----------------------------------------------------------------------===//
4235 // spv.ShiftLeftLogicalOp
4236 //===----------------------------------------------------------------------===//
4237 
4238 LogicalResult spirv::ShiftLeftLogicalOp::verify() {
4239   return verifyShiftOp(*this);
4240 }
4241 
4242 //===----------------------------------------------------------------------===//
4243 // spv.ShiftRightArithmeticOp
4244 //===----------------------------------------------------------------------===//
4245 
4246 LogicalResult spirv::ShiftRightArithmeticOp::verify() {
4247   return verifyShiftOp(*this);
4248 }
4249 
4250 //===----------------------------------------------------------------------===//
4251 // spv.ShiftRightLogicalOp
4252 //===----------------------------------------------------------------------===//
4253 
4254 LogicalResult spirv::ShiftRightLogicalOp::verify() {
4255   return verifyShiftOp(*this);
4256 }
4257 
4258 //===----------------------------------------------------------------------===//
4259 // spv.ImageQuerySize
4260 //===----------------------------------------------------------------------===//
4261 
4262 LogicalResult spirv::ImageQuerySizeOp::verify() {
4263   spirv::ImageType imageType = image().getType().cast<spirv::ImageType>();
4264   Type resultType = result().getType();
4265 
4266   spirv::Dim dim = imageType.getDim();
4267   spirv::ImageSamplingInfo samplingInfo = imageType.getSamplingInfo();
4268   spirv::ImageSamplerUseInfo samplerInfo = imageType.getSamplerUseInfo();
4269   switch (dim) {
4270   case spirv::Dim::Dim1D:
4271   case spirv::Dim::Dim2D:
4272   case spirv::Dim::Dim3D:
4273   case spirv::Dim::Cube:
4274     if (!(samplingInfo == spirv::ImageSamplingInfo::MultiSampled ||
4275           samplerInfo == spirv::ImageSamplerUseInfo::SamplerUnknown ||
4276           samplerInfo == spirv::ImageSamplerUseInfo::NoSampler))
4277       return emitError(
4278           "if Dim is 1D, 2D, 3D, or Cube, "
4279           "it must also have either an MS of 1 or a Sampled of 0 or 2");
4280     break;
4281   case spirv::Dim::Buffer:
4282   case spirv::Dim::Rect:
4283     break;
4284   default:
4285     return emitError("the Dim operand of the image type must "
4286                      "be 1D, 2D, 3D, Buffer, Cube, or Rect");
4287   }
4288 
4289   unsigned componentNumber = 0;
4290   switch (dim) {
4291   case spirv::Dim::Dim1D:
4292   case spirv::Dim::Buffer:
4293     componentNumber = 1;
4294     break;
4295   case spirv::Dim::Dim2D:
4296   case spirv::Dim::Cube:
4297   case spirv::Dim::Rect:
4298     componentNumber = 2;
4299     break;
4300   case spirv::Dim::Dim3D:
4301     componentNumber = 3;
4302     break;
4303   default:
4304     break;
4305   }
4306 
4307   if (imageType.getArrayedInfo() == spirv::ImageArrayedInfo::Arrayed)
4308     componentNumber += 1;
4309 
4310   unsigned resultComponentNumber = 1;
4311   if (auto resultVectorType = resultType.dyn_cast<VectorType>())
4312     resultComponentNumber = resultVectorType.getNumElements();
4313 
4314   if (componentNumber != resultComponentNumber)
4315     return emitError("expected the result to have ")
4316            << componentNumber << " component(s), but found "
4317            << resultComponentNumber << " component(s)";
4318 
4319   return success();
4320 }
4321 
4322 static ParseResult parsePtrAccessChainOpImpl(StringRef opName,
4323                                              OpAsmParser &parser,
4324                                              OperationState &state) {
4325   OpAsmParser::UnresolvedOperand ptrInfo;
4326   SmallVector<OpAsmParser::UnresolvedOperand, 4> indicesInfo;
4327   Type type;
4328   auto loc = parser.getCurrentLocation();
4329   SmallVector<Type, 4> indicesTypes;
4330 
4331   if (parser.parseOperand(ptrInfo) ||
4332       parser.parseOperandList(indicesInfo, OpAsmParser::Delimiter::Square) ||
4333       parser.parseColonType(type) ||
4334       parser.resolveOperand(ptrInfo, type, state.operands))
4335     return failure();
4336 
4337   // Check that the provided indices list is not empty before parsing their
4338   // type list.
4339   if (indicesInfo.empty())
4340     return emitError(state.location) << opName << " expected element";
4341 
4342   if (parser.parseComma() || parser.parseTypeList(indicesTypes))
4343     return failure();
4344 
4345   // Check that the indices types list is not empty and that it has a one-to-one
4346   // mapping to the provided indices.
4347   if (indicesTypes.size() != indicesInfo.size())
4348     return emitError(state.location)
4349            << opName
4350            << " indices types' count must be equal to indices info count";
4351 
4352   if (parser.resolveOperands(indicesInfo, indicesTypes, loc, state.operands))
4353     return failure();
4354 
4355   auto resultType = getElementPtrType(
4356       type, llvm::makeArrayRef(state.operands).drop_front(2), state.location);
4357   if (!resultType)
4358     return failure();
4359 
4360   state.addTypes(resultType);
4361   return success();
4362 }
4363 
4364 template <typename Op>
4365 static auto concatElemAndIndices(Op op) {
4366   SmallVector<Value> ret(op.indices().size() + 1);
4367   ret[0] = op.element();
4368   llvm::copy(op.indices(), ret.begin() + 1);
4369   return ret;
4370 }
4371 
4372 //===----------------------------------------------------------------------===//
4373 // spv.InBoundsPtrAccessChainOp
4374 //===----------------------------------------------------------------------===//
4375 
4376 void spirv::InBoundsPtrAccessChainOp::build(OpBuilder &builder,
4377                                             OperationState &state,
4378                                             Value basePtr, Value element,
4379                                             ValueRange indices) {
4380   auto type = getElementPtrType(basePtr.getType(), indices, state.location);
4381   assert(type && "Unable to deduce return type based on basePtr and indices");
4382   build(builder, state, type, basePtr, element, indices);
4383 }
4384 
4385 ParseResult spirv::InBoundsPtrAccessChainOp::parse(OpAsmParser &parser,
4386                                                    OperationState &state) {
4387   return parsePtrAccessChainOpImpl(
4388       spirv::InBoundsPtrAccessChainOp::getOperationName(), parser, state);
4389 }
4390 
4391 void spirv::InBoundsPtrAccessChainOp::print(OpAsmPrinter &printer) {
4392   printAccessChain(*this, concatElemAndIndices(*this), printer);
4393 }
4394 
4395 LogicalResult spirv::InBoundsPtrAccessChainOp::verify() {
4396   return verifyAccessChain(*this, indices());
4397 }
4398 
4399 //===----------------------------------------------------------------------===//
4400 // spv.PtrAccessChainOp
4401 //===----------------------------------------------------------------------===//
4402 
4403 void spirv::PtrAccessChainOp::build(OpBuilder &builder, OperationState &state,
4404                                     Value basePtr, Value element,
4405                                     ValueRange indices) {
4406   auto type = getElementPtrType(basePtr.getType(), indices, state.location);
4407   assert(type && "Unable to deduce return type based on basePtr and indices");
4408   build(builder, state, type, basePtr, element, indices);
4409 }
4410 
4411 ParseResult spirv::PtrAccessChainOp::parse(OpAsmParser &parser,
4412                                            OperationState &state) {
4413   return parsePtrAccessChainOpImpl(spirv::PtrAccessChainOp::getOperationName(),
4414                                    parser, state);
4415 }
4416 
4417 void spirv::PtrAccessChainOp::print(OpAsmPrinter &printer) {
4418   printAccessChain(*this, concatElemAndIndices(*this), printer);
4419 }
4420 
4421 LogicalResult spirv::PtrAccessChainOp::verify() {
4422   return verifyAccessChain(*this, indices());
4423 }
4424 
4425 //===----------------------------------------------------------------------===//
4426 // spv.VectorTimesScalarOp
4427 //===----------------------------------------------------------------------===//
4428 
4429 LogicalResult spirv::VectorTimesScalarOp::verify() {
4430   if (vector().getType() != getType())
4431     return emitOpError("vector operand and result type mismatch");
4432   auto scalarType = getType().cast<VectorType>().getElementType();
4433   if (scalar().getType() != scalarType)
4434     return emitOpError("scalar operand and result element type match");
4435   return success();
4436 }
4437 
4438 // TableGen'erated operation interfaces for querying versions, extensions, and
4439 // capabilities.
4440 #include "mlir/Dialect/SPIRV/IR/SPIRVAvailability.cpp.inc"
4441 
4442 // TablenGen'erated operation definitions.
4443 #define GET_OP_CLASSES
4444 #include "mlir/Dialect/SPIRV/IR/SPIRVOps.cpp.inc"
4445 
4446 namespace mlir {
4447 namespace spirv {
4448 // TableGen'erated operation availability interface implementations.
4449 #include "mlir/Dialect/SPIRV/IR/SPIRVOpAvailabilityImpl.inc"
4450 } // namespace spirv
4451 } // namespace mlir
4452