MLIR 24.0.0git
SPIRVOps.cpp
Go to the documentation of this file.
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
14
15#include "SPIRVOpUtils.h"
16#include "SPIRVParsingUtils.h"
17
24#include "mlir/IR/Builders.h"
28#include "mlir/IR/Operation.h"
31#include "llvm/ADT/APFloat.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/ArrayRef.h"
34#include "llvm/ADT/DenseSet.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/StringExtras.h"
37#include "llvm/ADT/TypeSwitch.h"
38#include "llvm/Support/InterleavedRange.h"
39#include <cassert>
40#include <numeric>
41#include <optional>
42
43using namespace mlir;
44using namespace mlir::spirv::AttrNames;
45
46//===----------------------------------------------------------------------===//
47// Common utility functions
48//===----------------------------------------------------------------------===//
49
50LogicalResult spirv::extractValueFromConstOp(Operation *op, int32_t &value) {
51 auto constOp = dyn_cast_or_null<spirv::ConstantOp>(op);
52 if (!constOp) {
53 return failure();
54 }
55 auto valueAttr = constOp.getValue();
56 auto integerValueAttr = dyn_cast<IntegerAttr>(valueAttr);
57 if (!integerValueAttr) {
58 return failure();
59 }
60
61 if (integerValueAttr.getType().isSignlessInteger())
62 value = integerValueAttr.getInt();
63 else
64 value = integerValueAttr.getSInt();
65
66 return success();
67}
68
69LogicalResult
71 spirv::MemorySemantics memorySemantics) {
72 // According to the SPIR-V specification:
73 // "Despite being a mask and allowing multiple bits to be combined, it is
74 // invalid for more than one of these four bits to be set: Acquire, Release,
75 // AcquireRelease, or SequentiallyConsistent. Requesting both Acquire and
76 // Release semantics is done by setting the AcquireRelease bit, not by setting
77 // two bits."
78 auto atMostOneInSet = spirv::MemorySemantics::Acquire |
79 spirv::MemorySemantics::Release |
80 spirv::MemorySemantics::AcquireRelease |
81 spirv::MemorySemantics::SequentiallyConsistent;
82
83 auto bitCount =
84 llvm::popcount(static_cast<uint32_t>(memorySemantics & atMostOneInSet));
85 if (bitCount > 1) {
86 return op->emitError(
87 "expected at most one of these four memory constraints "
88 "to be set: `Acquire`, `Release`,"
89 "`AcquireRelease` or `SequentiallyConsistent`");
90 }
91 return success();
92}
93
95 Type pointeeType) {
96 // From SPV_KHR_physical_storage_buffer:
97 // > If an OpVariable's pointee type is a pointer (or array of pointers) in
98 // > PhysicalStorageBuffer storage class, then the variable must be decorated
99 // > with exactly one of AliasedPointer or RestrictPointer.
100 auto pointeePtrType = dyn_cast<spirv::PointerType>(pointeeType);
101 if (!pointeePtrType) {
102 if (auto pointeeArrayType = dyn_cast<spirv::ArrayType>(pointeeType)) {
103 pointeePtrType =
104 dyn_cast<spirv::PointerType>(pointeeArrayType.getElementType());
105 }
106 }
107
108 if (!pointeePtrType || pointeePtrType.getStorageClass() !=
109 spirv::StorageClass::PhysicalStorageBuffer)
110 return success();
111
112 auto getDecorationAttr = [op](spirv::Decoration decoration) {
113 return op->getDiscardableAttr(spirv::getDecorationString(decoration));
114 };
115
116 bool hasAliasedPtr =
117 getDecorationAttr(spirv::Decoration::AliasedPointer) != nullptr;
118 bool hasRestrictPtr =
119 getDecorationAttr(spirv::Decoration::RestrictPointer) != nullptr;
120
121 if (!hasAliasedPtr && !hasRestrictPtr)
122 return op->emitOpError()
123 << " with physical buffer pointer must be decorated "
124 "either 'AliasedPointer' or 'RestrictPointer'";
125
126 if (hasAliasedPtr && hasRestrictPtr)
127 return op->emitOpError()
128 << " with physical buffer pointer must have exactly one "
129 "aliasing decoration";
130
131 return success();
132}
133
135 SmallVectorImpl<StringRef> &elidedAttrs) {
136 NamedAttrList attrs(op->getDiscardableAttrDictionary().getValue());
137 op->getName().populateInherentAttrs(op, attrs);
138
139 // Print optional descriptor binding
140 auto descriptorSetName = llvm::convertToSnakeFromCamelCase(
141 stringifyDecoration(spirv::Decoration::DescriptorSet));
142 auto bindingName = llvm::convertToSnakeFromCamelCase(
143 stringifyDecoration(spirv::Decoration::Binding));
144 auto descriptorSet =
145 dyn_cast_or_null<IntegerAttr>(attrs.get(descriptorSetName));
146 auto binding = dyn_cast_or_null<IntegerAttr>(attrs.get(bindingName));
147 if (descriptorSet && binding) {
148 elidedAttrs.push_back(descriptorSetName);
149 elidedAttrs.push_back(bindingName);
150 printer << " bind(" << descriptorSet.getInt() << ", " << binding.getInt()
151 << ")";
152 }
153
154 // Print BuiltIn attribute if present
155 auto builtInName = llvm::convertToSnakeFromCamelCase(
156 stringifyDecoration(spirv::Decoration::BuiltIn));
157 if (auto builtin = dyn_cast_or_null<StringAttr>(attrs.get(builtInName))) {
158 printer << " " << builtInName << "(\"" << builtin.getValue() << "\")";
159 elidedAttrs.push_back(builtInName);
160 }
161
162 printer.printOptionalAttrDict(attrs, elidedAttrs);
163}
164
168 Type type;
169 // If the operand list is in-between parentheses, then we have a generic form.
170 // (see the fallback in `printOneResultOp`).
171 SMLoc loc = parser.getCurrentLocation();
172 if (!parser.parseOptionalLParen()) {
173 if (parser.parseOperandList(ops) || parser.parseRParen() ||
174 parser.parseOptionalAttrDict(result.attributes) ||
175 parser.parseColon() || parser.parseType(type))
176 return failure();
177 auto fnType = dyn_cast<FunctionType>(type);
178 if (!fnType) {
179 parser.emitError(loc, "expected function type");
180 return failure();
181 }
182 if (parser.resolveOperands(ops, fnType.getInputs(), loc, result.operands))
183 return failure();
184 result.addTypes(fnType.getResults());
185 return success();
186 }
187 return failure(parser.parseOperandList(ops) ||
188 parser.parseOptionalAttrDict(result.attributes) ||
189 parser.parseColonType(type) ||
190 parser.resolveOperands(ops, type, result.operands) ||
191 parser.addTypeToList(type, result.types));
192}
193
195 assert(op->getNumResults() == 1 && "op should have one result");
196
197 // If not all the operand and result types are the same, just use the
198 // generic assembly form to avoid omitting information in printing.
199 auto resultType = op->getResult(0).getType();
200 if (llvm::any_of(op->getOperandTypes(),
201 [&](Type type) { return type != resultType; })) {
202 p.printGenericOp(op, /*printOpName=*/false);
203 return;
204 }
205
206 p << ' ';
207 p.printOperands(op->getOperands());
209 // Now we can output only one type for all operands and the result.
210 p << " : " << resultType;
211}
212
213template <typename BlockReadWriteOpTy>
214static LogicalResult verifyBlockReadWritePtrAndValTypes(BlockReadWriteOpTy op,
215 Value ptr, Value val) {
216 auto valType = val.getType();
217 if (auto valVecTy = dyn_cast<VectorType>(valType))
218 valType = valVecTy.getElementType();
219
220 if (valType != cast<spirv::PointerType>(ptr.getType()).getPointeeType()) {
221 return op.emitOpError("mismatch in result type and pointer type");
222 }
223 return success();
224}
225
226/// Walks the given type hierarchy with the given indices, potentially down
227/// to component granularity, to select an element type. Returns null type and
228/// emits errors with the given loc on failure.
229static Type
231 function_ref<InFlightDiagnostic(StringRef)> emitErrorFn) {
232 if (indices.empty()) {
233 emitErrorFn("expected at least one index for spirv.CompositeExtract");
234 return nullptr;
235 }
236
237 for (auto index : indices) {
238 if (auto cType = dyn_cast<spirv::CompositeType>(type)) {
239 if (cType.hasCompileTimeKnownNumElements() &&
240 (index < 0 ||
241 static_cast<uint64_t>(index) >= cType.getNumElements())) {
242 emitErrorFn("index ") << index << " out of bounds for " << type;
243 return nullptr;
244 }
245 type = cType.getElementType(index);
246 } else {
247 emitErrorFn("cannot extract from non-composite type ")
248 << type << " with index " << index;
249 return nullptr;
250 }
251 }
252 return type;
253}
254
255static Type
257 function_ref<InFlightDiagnostic(StringRef)> emitErrorFn) {
258 auto indicesArrayAttr = dyn_cast<ArrayAttr>(indices);
259 if (!indicesArrayAttr) {
260 emitErrorFn("expected a 32-bit integer array attribute for 'indices'");
261 return nullptr;
262 }
263 if (indicesArrayAttr.empty()) {
264 emitErrorFn("expected at least one index for spirv.CompositeExtract");
265 return nullptr;
266 }
267
268 SmallVector<int32_t, 2> indexVals;
269 for (auto indexAttr : indicesArrayAttr) {
270 auto indexIntAttr = dyn_cast<IntegerAttr>(indexAttr);
271 if (!indexIntAttr) {
272 emitErrorFn("expected an 32-bit integer for index, but found '")
273 << indexAttr << "'";
274 return nullptr;
275 }
276 indexVals.push_back(indexIntAttr.getInt());
277 }
278 return getElementType(type, indexVals, emitErrorFn);
279}
280
282 auto errorFn = [&](StringRef err) -> InFlightDiagnostic {
283 return ::mlir::emitError(loc, err);
284 };
285 return getElementType(type, indices, errorFn);
286}
287
289 SMLoc loc) {
290 auto errorFn = [&](StringRef err) -> InFlightDiagnostic {
291 return parser.emitError(loc, err);
292 };
293 return getElementType(type, indices, errorFn);
294}
295
296template <typename ExtendedBinaryOp>
297static LogicalResult verifyArithmeticExtendedBinaryOp(ExtendedBinaryOp op) {
298 auto resultType = cast<spirv::StructType>(op.getType());
299 if (resultType.getNumElements() != 2)
300 return op.emitOpError("expected result struct type containing two members");
301
302 if (!llvm::all_equal({op.getOperand1().getType(), op.getOperand2().getType(),
303 resultType.getElementType(0),
304 resultType.getElementType(1)}))
305 return op.emitOpError(
306 "expected all operand types and struct member types are the same");
307
308 return success();
309}
310
314 if (parser.parseOptionalAttrDict(result.attributes) ||
315 parser.parseOperandList(operands) || parser.parseColon())
316 return failure();
317
318 Type resultType;
319 SMLoc loc = parser.getCurrentLocation();
320 if (parser.parseType(resultType))
321 return failure();
322
323 auto structType = dyn_cast<spirv::StructType>(resultType);
324 if (!structType || structType.getNumElements() != 2)
325 return parser.emitError(loc, "expected spirv.struct type with two members");
326
327 SmallVector<Type, 2> operandTypes(2, structType.getElementType(0));
328 if (parser.resolveOperands(operands, operandTypes, loc, result.operands))
329 return failure();
330
331 result.addTypes(resultType);
332 return success();
333}
334
336 OpAsmPrinter &printer) {
337 printer << ' ';
338 printer.printOptionalAttrDict(op->getDiscardableAttrDictionary().getValue());
339 printer.printOperands(op->getOperands());
340 printer << " : " << op->getResultTypes().front();
341}
342
343static LogicalResult verifyShiftOp(Operation *op) {
344 if (op->getOperand(0).getType() != op->getResult(0).getType()) {
345 return op->emitError("expected the same type for the first operand and "
346 "result, but provided ")
347 << op->getOperand(0).getType() << " and "
348 << op->getResult(0).getType();
349 }
350 return success();
351}
352
353//===----------------------------------------------------------------------===//
354// spirv.mlir.addressof
355//===----------------------------------------------------------------------===//
356
357void spirv::AddressOfOp::build(OpBuilder &builder, OperationState &state,
358 spirv::GlobalVariableOp var) {
359 build(builder, state, var.getType(), SymbolRefAttr::get(var));
360}
361
362LogicalResult
363spirv::AddressOfOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
364 auto varOp = symbolTable.lookupNearestSymbolFrom<spirv::GlobalVariableOp>(
365 *this, getVariableAttr());
366 if (!varOp) {
367 return emitOpError("expected spirv.GlobalVariable symbol");
368 }
369 if (getPointer().getType() != varOp.getType()) {
370 return emitOpError(
371 "result type mismatch with the referenced global variable's type");
372 }
373 return success();
374}
375
376//===----------------------------------------------------------------------===//
377// spirv.CompositeConstruct
378//===----------------------------------------------------------------------===//
379
380LogicalResult spirv::CompositeConstructOp::verify() {
381 operand_range constituents = this->getConstituents();
382
383 // There are 4 cases with varying verification rules:
384 // 1. Cooperative Matrices (1 constituent)
385 // 2. Structs (1 constituent for each member)
386 // 3. Arrays (1 constituent for each array element)
387 // 4. Vectors (1 constituent (sub-)element for each vector element)
388
389 auto coopElementType = llvm::TypeSwitch<Type, Type>(getType())
390 .Case([](spirv::CooperativeMatrixType coopType) {
391 return coopType.getElementType();
392 })
393 .Default(nullptr);
394
395 // Case 1. -- matrices.
396 if (coopElementType) {
397 if (constituents.size() != 1)
398 return emitOpError("has incorrect number of operands: expected ")
399 << "1, but provided " << constituents.size();
400 if (coopElementType != constituents.front().getType())
401 return emitOpError("operand type mismatch: expected operand type ")
402 << coopElementType << ", but provided "
403 << constituents.front().getType();
404 return success();
405 }
406
407 // Case 2./3./4. -- number of constituents matches the number of elements.
408 auto cType = cast<spirv::CompositeType>(getType());
409 if (constituents.size() == cType.getNumElements()) {
410 for (auto index : llvm::seq<uint32_t>(0, constituents.size())) {
411 if (constituents[index].getType() != cType.getElementType(index)) {
412 return emitOpError("operand type mismatch: expected operand type ")
413 << cType.getElementType(index) << ", but provided "
414 << constituents[index].getType();
415 }
416 }
417 return success();
418 }
419
420 // Case 4. -- check that all constituents add up tp the expected vector type.
421 auto resultType = dyn_cast<VectorType>(cType);
422 if (!resultType)
423 return emitOpError(
424 "expected to return a vector or cooperative matrix when the number of "
425 "constituents is less than what the result needs");
426
427 if (constituents.size() < 2)
428 return emitOpError("has incorrect number of operands: expected at least "
429 "2 for a vector result, but provided ")
430 << constituents.size();
431
433 for (Value component : constituents) {
434 if (!isa<VectorType>(component.getType()) &&
435 !component.getType().isIntOrFloat())
436 return emitOpError("operand type mismatch: expected operand to have "
437 "a scalar or vector type, but provided ")
438 << component.getType();
439
440 Type elementType = component.getType();
441 if (auto vectorType = dyn_cast<VectorType>(component.getType())) {
442 sizes.push_back(vectorType.getNumElements());
443 elementType = vectorType.getElementType();
444 } else {
445 sizes.push_back(1);
446 }
447
448 if (elementType != resultType.getElementType())
449 return emitOpError("operand element type mismatch: expected to be ")
450 << resultType.getElementType() << ", but provided " << elementType;
451 }
452 unsigned totalCount = llvm::sum_of(sizes);
453 if (totalCount != cType.getNumElements())
454 return emitOpError("has incorrect number of operands: expected ")
455 << cType.getNumElements() << ", but provided " << totalCount;
456 return success();
457}
458
459//===----------------------------------------------------------------------===//
460// spirv.CompositeExtractOp
461//===----------------------------------------------------------------------===//
462
463void spirv::CompositeExtractOp::build(OpBuilder &builder, OperationState &state,
464 Value composite,
466 auto indexAttr = builder.getI32ArrayAttr(indices);
467 auto elementType =
468 getElementType(composite.getType(), indexAttr, state.location);
469 if (!elementType) {
470 return;
471 }
472 build(builder, state, elementType, composite, indexAttr);
473}
474
475ParseResult spirv::CompositeExtractOp::parse(OpAsmParser &parser,
477 OpAsmParser::UnresolvedOperand compositeInfo;
478 Attribute indicesAttr;
479 StringRef indicesAttrName =
480 spirv::CompositeExtractOp::getIndicesAttrName(result.name);
481 Type compositeType;
482 SMLoc attrLocation;
483
484 if (parser.parseOperand(compositeInfo) ||
485 parser.getCurrentLocation(&attrLocation) ||
486 parser.parseAttribute(indicesAttr, indicesAttrName, result.attributes) ||
487 parser.parseColonType(compositeType) ||
488 parser.resolveOperand(compositeInfo, compositeType, result.operands)) {
489 return failure();
490 }
491
492 Type resultType =
493 getElementType(compositeType, indicesAttr, parser, attrLocation);
494 if (!resultType) {
495 return failure();
496 }
497 result.addTypes(resultType);
498 return success();
499}
500
501void spirv::CompositeExtractOp::print(OpAsmPrinter &printer) {
502 printer << ' ' << getComposite() << getIndices() << " : "
503 << getComposite().getType();
504}
505
506LogicalResult spirv::CompositeExtractOp::verify() {
507 auto indicesArrayAttr = dyn_cast<ArrayAttr>(getIndices());
508 auto resultType =
509 getElementType(getComposite().getType(), indicesArrayAttr, getLoc());
510 if (!resultType)
511 return failure();
512
513 if (resultType != getType()) {
514 return emitOpError("invalid result type: expected ")
515 << resultType << " but provided " << getType();
516 }
517
518 return success();
519}
520
521//===----------------------------------------------------------------------===//
522// spirv.CompositeInsert
523//===----------------------------------------------------------------------===//
524
525void spirv::CompositeInsertOp::build(OpBuilder &builder, OperationState &state,
526 Value object, Value composite,
528 auto indexAttr = builder.getI32ArrayAttr(indices);
529 build(builder, state, composite.getType(), object, composite, indexAttr);
530}
531
532ParseResult spirv::CompositeInsertOp::parse(OpAsmParser &parser,
535 Type objectType, compositeType;
536 Attribute indicesAttr;
537 StringRef indicesAttrName =
538 spirv::CompositeInsertOp::getIndicesAttrName(result.name);
539 auto loc = parser.getCurrentLocation();
540
541 return failure(
542 parser.parseOperandList(operands, 2) ||
543 parser.parseAttribute(indicesAttr, indicesAttrName, result.attributes) ||
544 parser.parseColonType(objectType) ||
545 parser.parseKeywordType("into", compositeType) ||
546 parser.resolveOperands(operands, {objectType, compositeType}, loc,
547 result.operands) ||
548 parser.addTypesToList(compositeType, result.types));
549}
550
551LogicalResult spirv::CompositeInsertOp::verify() {
552 auto indicesArrayAttr = dyn_cast<ArrayAttr>(getIndices());
553 auto objectType =
554 getElementType(getComposite().getType(), indicesArrayAttr, getLoc());
555 if (!objectType)
556 return failure();
557
558 if (objectType != getObject().getType()) {
559 return emitOpError("object operand type should be ")
560 << objectType << ", but found " << getObject().getType();
561 }
562
563 if (getComposite().getType() != getType()) {
564 return emitOpError("result type should be the same as "
565 "the composite type, but found ")
566 << getComposite().getType() << " vs " << getType();
567 }
568
569 return success();
570}
571
572void spirv::CompositeInsertOp::print(OpAsmPrinter &printer) {
573 printer << " " << getObject() << ", " << getComposite() << getIndices()
574 << " : " << getObject().getType() << " into "
575 << getComposite().getType();
576}
577
578//===----------------------------------------------------------------------===//
579// spirv.Constant
580//===----------------------------------------------------------------------===//
581
582ParseResult spirv::ConstantOp::parse(OpAsmParser &parser,
584 Attribute value;
585 StringRef valueAttrName = spirv::ConstantOp::getValueAttrName(result.name);
586 if (parser.parseAttribute(value, valueAttrName, result.attributes))
587 return failure();
588
589 Type type = NoneType::get(parser.getContext());
590 if (auto typedAttr = dyn_cast<TypedAttr>(value))
591 type = typedAttr.getType();
592 if (isa<NoneType, TensorType>(type)) {
593 if (parser.parseColonType(type))
594 return failure();
595 }
596
597 if (isa<TensorArmType>(type)) {
598 if (parser.parseOptionalColon().succeeded())
599 if (parser.parseType(type))
600 return failure();
601 }
602
603 return parser.addTypeToList(type, result.types);
604}
605
606void spirv::ConstantOp::print(OpAsmPrinter &printer) {
607 printer << ' ' << getValue();
608 if (isa<spirv::ArrayType, spirv::StructType>(getType()) &&
609 !isa<spirv::NullAttr>(getValue()))
610 printer << " : " << getType();
611}
612
613static LogicalResult verifyConstantType(spirv::ConstantOp op, Attribute value,
614 Type opType) {
615 if (isa<spirv::CooperativeMatrixType>(opType)) {
616 auto denseAttr = dyn_cast<DenseElementsAttr>(value);
617 if (!denseAttr || !denseAttr.isSplat())
618 return op.emitOpError("expected a splat dense attribute for cooperative "
619 "matrix constant, but found ")
620 << denseAttr;
621 }
622 if (isa<spirv::NullAttr>(value) &&
623 !isa<spirv::ArrayType, spirv::PointerType, spirv::StructType>(opType))
624 return op.emitOpError("must have spirv.ptr, spirv.array or spirv.struct "
625 "result type for null value");
626 if (isa<IntegerAttr, FloatAttr, spirv::NullAttr>(value)) {
627 auto valueType = cast<TypedAttr>(value).getType();
628 if (valueType != opType)
629 return op.emitOpError("result type (")
630 << opType << ") does not match value type (" << valueType << ")";
631 return success();
632 }
633 if (isa<DenseTypedElementsAttr, SparseElementsAttr>(value)) {
634 auto valueType = cast<TypedAttr>(value).getType();
635 if (valueType == opType)
636 return success();
637 auto arrayType = dyn_cast<spirv::ArrayType>(opType);
638 auto shapedType = dyn_cast<ShapedType>(valueType);
639 if (!arrayType)
640 return op.emitOpError("result or element type (")
641 << opType << ") does not match value type (" << valueType
642 << "), must be the same or spirv.array";
643
644 int numElements = arrayType.getNumElements();
645 auto opElemType = arrayType.getElementType();
646 while (auto t = dyn_cast<spirv::ArrayType>(opElemType)) {
647 numElements *= t.getNumElements();
648 opElemType = t.getElementType();
649 }
650 if (!opElemType.isIntOrFloat())
651 return op.emitOpError("only support nested array result type");
652
653 auto valueElemType = shapedType.getElementType();
654 if (valueElemType != opElemType) {
655 return op.emitOpError("result element type (")
656 << opElemType << ") does not match value element type ("
657 << valueElemType << ")";
658 }
659
660 if (numElements != shapedType.getNumElements()) {
661 return op.emitOpError("result number of elements (")
662 << numElements << ") does not match value number of elements ("
663 << shapedType.getNumElements() << ")";
664 }
665 return success();
666 }
667 if (auto arrayAttr = dyn_cast<ArrayAttr>(value)) {
668 if (auto structType = dyn_cast<spirv::StructType>(opType)) {
669 // Identified (possibly recursive) structs are not supported as constants.
670 if (structType.isIdentified())
671 return op.emitOpError(
672 "cannot have an identified struct as a constant type");
673 if (arrayAttr.size() != structType.getNumElements())
674 return op.emitOpError("number of constituents (")
675 << arrayAttr.size()
676 << ") does not match number of struct members ("
677 << structType.getNumElements() << ")";
678 for (auto [idx, element] : llvm::enumerate(arrayAttr.getValue())) {
679 if (failed(verifyConstantType(op, element,
680 structType.getElementType(idx))))
681 return failure();
682 }
683 return success();
684 }
685 auto arrayType = dyn_cast<spirv::ArrayType>(opType);
686 if (!arrayType)
687 return op.emitOpError(
688 "must have spirv.array or spirv.struct result type for array value");
689 Type elemType = arrayType.getElementType();
690 for (Attribute element : arrayAttr.getValue()) {
691 // Verify array elements recursively.
692 if (failed(verifyConstantType(op, element, elemType)))
693 return failure();
694 }
695 return success();
696 }
697 return op.emitOpError("cannot have attribute: ") << value;
698}
699
700LogicalResult spirv::ConstantOp::verify() {
701 // ODS already generates checks to make sure the result type is valid. We just
702 // need to additionally check that the value's attribute type is consistent
703 // with the result type.
704 return verifyConstantType(*this, getValueAttr(), getType());
705}
706
707bool spirv::ConstantOp::isBuildableWith(Type type) {
708 // Must be valid SPIR-V type first.
709 if (!isa<spirv::SPIRVType>(type))
710 return false;
711
712 if (isa<SPIRVDialect>(type.getDialect())) {
713 if (auto structType = dyn_cast<spirv::StructType>(type))
714 return !structType.isIdentified();
715 return isa<spirv::ArrayType>(type);
716 }
717
718 return true;
719}
720
721spirv::ConstantOp spirv::ConstantOp::getZero(Type type, Location loc,
722 OpBuilder &builder) {
723 if (auto intType = dyn_cast<IntegerType>(type)) {
724 unsigned width = intType.getWidth();
725 if (width == 1)
726 return spirv::ConstantOp::create(builder, loc, type,
727 builder.getBoolAttr(false));
728 return spirv::ConstantOp::create(
729 builder, loc, type, builder.getIntegerAttr(type, APInt(width, 0)));
730 }
731 if (auto floatType = dyn_cast<FloatType>(type)) {
732 return spirv::ConstantOp::create(builder, loc, type,
733 builder.getFloatAttr(floatType, 0.0));
734 }
735 if (auto vectorType = dyn_cast<VectorType>(type)) {
736 Type elemType = vectorType.getElementType();
737 if (isa<IntegerType>(elemType)) {
738 return spirv::ConstantOp::create(
739 builder, loc, type,
740 DenseElementsAttr::get(vectorType,
741 IntegerAttr::get(elemType, 0).getValue()));
742 }
743 if (isa<FloatType>(elemType)) {
744 return spirv::ConstantOp::create(
745 builder, loc, type,
746 DenseFPElementsAttr::get(vectorType,
747 FloatAttr::get(elemType, 0.0).getValue()));
748 }
749 }
750
751 llvm_unreachable("unimplemented types for ConstantOp::getZero()");
752}
753
754spirv::ConstantOp spirv::ConstantOp::getOne(Type type, Location loc,
755 OpBuilder &builder) {
756 if (auto intType = dyn_cast<IntegerType>(type)) {
757 unsigned width = intType.getWidth();
758 if (width == 1)
759 return spirv::ConstantOp::create(builder, loc, type,
760 builder.getBoolAttr(true));
761 return spirv::ConstantOp::create(
762 builder, loc, type, builder.getIntegerAttr(type, APInt(width, 1)));
763 }
764 if (auto floatType = dyn_cast<FloatType>(type)) {
765 return spirv::ConstantOp::create(builder, loc, type,
766 builder.getFloatAttr(floatType, 1.0));
767 }
768 if (auto vectorType = dyn_cast<VectorType>(type)) {
769 Type elemType = vectorType.getElementType();
770 if (isa<IntegerType>(elemType)) {
771 return spirv::ConstantOp::create(
772 builder, loc, type,
773 DenseElementsAttr::get(vectorType,
774 IntegerAttr::get(elemType, 1).getValue()));
775 }
776 if (isa<FloatType>(elemType)) {
777 return spirv::ConstantOp::create(
778 builder, loc, type,
779 DenseFPElementsAttr::get(vectorType,
780 FloatAttr::get(elemType, 1.0).getValue()));
781 }
782 }
783
784 llvm_unreachable("unimplemented types for ConstantOp::getOne()");
785}
786
787void mlir::spirv::ConstantOp::getAsmResultNames(
788 llvm::function_ref<void(mlir::Value, llvm::StringRef)> setNameFn) {
789 Type type = getType();
790
791 SmallString<32> specialNameBuffer;
792 llvm::raw_svector_ostream specialName(specialNameBuffer);
793 specialName << "cst";
794
795 IntegerType intTy = dyn_cast<IntegerType>(type);
796
797 if (IntegerAttr intCst = dyn_cast<IntegerAttr>(getValue())) {
798 assert(intTy);
799
800 if (intTy.getWidth() == 1) {
801 return setNameFn(getResult(), (intCst.getInt() ? "true" : "false"));
802 }
803
804 if (intTy.isSignless()) {
805 specialName << intCst.getInt();
806 } else if (intTy.isUnsigned()) {
807 specialName << intCst.getUInt();
808 } else {
809 specialName << intCst.getSInt();
810 }
811 }
812
813 if (intTy || isa<FloatType>(type)) {
814 specialName << '_' << type;
815 }
816
817 if (auto vecType = dyn_cast<VectorType>(type)) {
818 specialName << "_vec_";
819 specialName << vecType.getDimSize(0);
820
821 Type elementType = vecType.getElementType();
822
823 if (isa<IntegerType>(elementType) || isa<FloatType>(elementType)) {
824 specialName << "x" << elementType;
825 }
826 }
827
828 setNameFn(getResult(), specialName.str());
829}
830
831void mlir::spirv::AddressOfOp::getAsmResultNames(
832 llvm::function_ref<void(mlir::Value, llvm::StringRef)> setNameFn) {
833 SmallString<32> specialNameBuffer;
834 llvm::raw_svector_ostream specialName(specialNameBuffer);
835 specialName << getVariable() << "_addr";
836 setNameFn(getResult(), specialName.str());
837}
838
839//===----------------------------------------------------------------------===//
840// spirv.EXTConstantCompositeReplicate
841//===----------------------------------------------------------------------===//
842
843// Returns type of attribute. In case of a TypedAttr this will simply return
844// the type. But for an ArrayAttr which is untyped and can be multidimensional
845// it creates the ArrayType recursively.
847 if (auto typedAttr = dyn_cast<TypedAttr>(attr)) {
848 return typedAttr.getType();
849 }
850
851 if (auto arrayAttr = dyn_cast<ArrayAttr>(attr)) {
852 return spirv::ArrayType::get(getValueType(arrayAttr[0]), arrayAttr.size());
853 }
854
855 return nullptr;
856}
857
858LogicalResult spirv::EXTConstantCompositeReplicateOp::verify() {
859 Type valueType = getValueType(getValue());
860 if (!valueType)
861 return emitError("unknown value attribute type");
862
863 auto compositeType = dyn_cast<spirv::CompositeType>(getType());
864 if (!compositeType)
865 return emitError("result type is not a composite type");
866
867 Type compositeElementType = compositeType.getElementType(0);
868
869 SmallVector<Type, 3> possibleTypes = {compositeElementType};
870 while (auto type = dyn_cast<spirv::CompositeType>(compositeElementType)) {
871 compositeElementType = type.getElementType(0);
872 possibleTypes.push_back(compositeElementType);
873 }
874
875 if (!is_contained(possibleTypes, valueType)) {
876 return emitError("expected value attribute type ")
877 << interleaved(possibleTypes, " or ") << ", but got: " << valueType;
878 }
879
880 return success();
881}
882
883//===----------------------------------------------------------------------===//
884// spirv.ControlBarrierOp
885//===----------------------------------------------------------------------===//
886
887LogicalResult spirv::ControlBarrierOp::verify() {
888 return verifyMemorySemantics(getOperation(), getMemorySemantics());
889}
890
891//===----------------------------------------------------------------------===//
892// spirv.EntryPoint
893//===----------------------------------------------------------------------===//
894
895void spirv::EntryPointOp::build(OpBuilder &builder, OperationState &state,
896 spirv::ExecutionModel executionModel,
897 spirv::FuncOp function,
898 ArrayRef<Attribute> interfaceVars) {
899 build(builder, state,
900 spirv::ExecutionModelAttr::get(builder.getContext(), executionModel),
901 SymbolRefAttr::get(function), builder.getArrayAttr(interfaceVars));
902}
903
904ParseResult spirv::EntryPointOp::parse(OpAsmParser &parser,
906 spirv::ExecutionModel execModel;
907 SmallVector<Attribute, 4> interfaceVars;
908
910 if (parseEnumStrAttr<spirv::ExecutionModelAttr>(execModel, parser, result) ||
911 parser.parseAttribute(fn, Type(), kFnNameAttrName, result.attributes)) {
912 return failure();
913 }
914
915 if (!parser.parseOptionalComma()) {
916 // Parse the interface variables
917 if (parser.parseCommaSeparatedList([&]() -> ParseResult {
918 // The name of the interface variable attribute isnt important
919 FlatSymbolRefAttr var;
920 NamedAttrList attrs;
921 if (parser.parseAttribute(var, Type(), "var_symbol", attrs))
922 return failure();
923 interfaceVars.push_back(var);
924 return success();
925 }))
926 return failure();
927 }
928 result.addAttribute(spirv::EntryPointOp::getInterfaceAttrName(result.name),
929 parser.getBuilder().getArrayAttr(interfaceVars));
930 return success();
931}
932
933void spirv::EntryPointOp::print(OpAsmPrinter &printer) {
934 printer << " \"" << stringifyExecutionModel(getExecutionModel()) << "\" ";
935 printer.printSymbolName(getFn());
936 auto interfaceVars = getInterface().getValue();
937 if (!interfaceVars.empty())
938 printer << ", " << llvm::interleaved(interfaceVars);
939}
940
941LogicalResult spirv::EntryPointOp::verify() {
942 // Checks for fn and interface symbol reference are done in spirv::ModuleOp
943 // verification.
944 return success();
945}
946
947//===----------------------------------------------------------------------===//
948// spirv.ExecutionMode / spirv.ExecutionModeId
949//===----------------------------------------------------------------------===//
950
951namespace {
952// Describes the extra operands a SPIR-V ExecutionMode expects: whether they
953// are <id> operands (only valid on spirv.ExecutionModeId) or literal integers
954// (only valid on spirv.ExecutionMode), and how many of them are required.
955struct ExecutionModeOperandSchema {
956 bool isIdOperand;
957 unsigned numOperands;
958};
959
960ExecutionModeOperandSchema
961getExecutionModeOperandSchema(spirv::ExecutionMode mode) {
962 switch (mode) {
963 case spirv::ExecutionMode::Invocations:
964 case spirv::ExecutionMode::OutputVertices:
965 case spirv::ExecutionMode::VecTypeHint:
966 case spirv::ExecutionMode::SubgroupSize:
967 case spirv::ExecutionMode::SubgroupsPerWorkgroup:
968 case spirv::ExecutionMode::DenormPreserve:
969 case spirv::ExecutionMode::DenormFlushToZero:
970 case spirv::ExecutionMode::SignedZeroInfNanPreserve:
971 case spirv::ExecutionMode::RoundingModeRTE:
972 case spirv::ExecutionMode::RoundingModeRTZ:
973 case spirv::ExecutionMode::OutputPrimitivesEXT:
974 case spirv::ExecutionMode::SharedLocalMemorySizeINTEL:
975 case spirv::ExecutionMode::RoundingModeRTPINTEL:
976 case spirv::ExecutionMode::RoundingModeRTNINTEL:
977 case spirv::ExecutionMode::FloatingPointModeALTINTEL:
978 case spirv::ExecutionMode::FloatingPointModeIEEEINTEL:
979 case spirv::ExecutionMode::MaxWorkDimINTEL:
980 case spirv::ExecutionMode::NumSIMDWorkitemsINTEL:
981 case spirv::ExecutionMode::SchedulerTargetFmaxMhzINTEL:
982 case spirv::ExecutionMode::StreamingInterfaceINTEL:
983 case spirv::ExecutionMode::NamedBarrierCountINTEL:
984 return {/*isIdOperand=*/false, /*numOperands=*/1};
985 case spirv::ExecutionMode::LocalSize:
986 case spirv::ExecutionMode::LocalSizeHint:
987 case spirv::ExecutionMode::MaxWorkgroupSizeINTEL:
988 return {/*isIdOperand=*/false, /*numOperands=*/3};
989 case spirv::ExecutionMode::SubgroupsPerWorkgroupId:
990 return {/*isIdOperand=*/true, /*numOperands=*/1};
991 case spirv::ExecutionMode::FPFastMathDefault:
992 return {/*isIdOperand=*/true, /*numOperands=*/2};
993 case spirv::ExecutionMode::LocalSizeId:
994 case spirv::ExecutionMode::LocalSizeHintId:
995 return {/*isIdOperand=*/true, /*numOperands=*/3};
996 default:
997 return {/*isIdOperand=*/false, /*numOperands=*/0};
998 }
999}
1000} // namespace
1001
1002//===----------------------------------------------------------------------===//
1003// spirv.ExecutionMode
1004//===----------------------------------------------------------------------===//
1005
1006void spirv::ExecutionModeOp::build(OpBuilder &builder, OperationState &state,
1007 spirv::FuncOp function,
1008 spirv::ExecutionMode executionMode,
1009 ArrayRef<int32_t> params) {
1010 build(builder, state, SymbolRefAttr::get(function),
1011 spirv::ExecutionModeAttr::get(builder.getContext(), executionMode),
1012 builder.getI32ArrayAttr(params));
1013}
1014
1015ParseResult spirv::ExecutionModeOp::parse(OpAsmParser &parser,
1017 spirv::ExecutionMode execMode;
1018 Attribute fn;
1019 if (parser.parseAttribute(fn, kFnNameAttrName, result.attributes) ||
1021 return failure();
1022 }
1023
1025 Type i32Type = parser.getBuilder().getIntegerType(32);
1026 while (!parser.parseOptionalComma()) {
1027 NamedAttrList attr;
1028 Attribute value;
1029 if (parser.parseAttribute(value, i32Type, "value", attr)) {
1030 return failure();
1031 }
1032 values.push_back(cast<IntegerAttr>(value).getInt());
1033 }
1034 StringRef valuesAttrName =
1035 spirv::ExecutionModeOp::getValuesAttrName(result.name);
1036 result.addAttribute(valuesAttrName,
1037 parser.getBuilder().getI32ArrayAttr(values));
1038 return success();
1039}
1040
1041void spirv::ExecutionModeOp::print(OpAsmPrinter &printer) {
1042 printer << " ";
1043 printer.printSymbolName(getFn());
1044 printer << " \"" << stringifyExecutionMode(getExecutionMode()) << "\"";
1045 ArrayAttr values = this->getValues();
1046 if (!values.empty())
1047 printer << ", " << llvm::interleaved(values.getAsValueRange<IntegerAttr>());
1048}
1049
1050LogicalResult spirv::ExecutionModeOp::verify() {
1051 ExecutionModeOperandSchema schema =
1052 getExecutionModeOperandSchema(getExecutionMode());
1053
1054 if (schema.isIdOperand)
1055 return emitOpError("expected ExecutionMode that takes extra operands "
1056 "that are not <id> operands, got: ")
1057 << stringifyExecutionMode(getExecutionMode());
1058
1059 if (getValues().size() != schema.numOperands)
1060 return emitOpError("expected ")
1061 << schema.numOperands << " value operand(s), got "
1062 << getValues().size();
1063
1064 return success();
1065}
1066
1067//===----------------------------------------------------------------------===//
1068// spirv.ExecutionModeId
1069//===----------------------------------------------------------------------===//
1070
1071ParseResult spirv::ExecutionModeIdOp::parse(OpAsmParser &parser,
1073 ExecutionMode execMode;
1074 if (Attribute fn;
1075 parser.parseAttribute(fn, kFnNameAttrName, result.attributes) ||
1076 parseEnumStrAttr<ExecutionModeAttr>(execMode, parser, result)) {
1077 return failure();
1078 }
1079
1081 if (parser.parseCommaSeparatedList([&]() -> ParseResult {
1082 Attribute attr;
1083 if (parser.parseAttribute(attr))
1084 return failure();
1085 values.push_back(attr);
1086 return success();
1087 })) {
1088 return failure();
1089 }
1090
1091 StringRef valuesAttrName = getValuesAttrName(result.name);
1092 ArrayAttr valuesAttr = parser.getBuilder().getArrayAttr(values);
1093 result.addAttribute(valuesAttrName, valuesAttr);
1094 return success();
1095}
1096
1097void spirv::ExecutionModeIdOp::print(OpAsmPrinter &printer) {
1098 printer << " ";
1099 printer.printSymbolName(getFn());
1100 printer << " \"" << stringifyExecutionMode(getExecutionMode()) << "\" ";
1101
1102 llvm::interleaveComma(getValues(), printer);
1103}
1104
1105LogicalResult spirv::ExecutionModeIdOp::verify() {
1106 ExecutionModeOperandSchema schema =
1107 getExecutionModeOperandSchema(getExecutionMode());
1108
1109 if (!schema.isIdOperand)
1110 return emitOpError("expected ExecutionMode that takes extra operands that "
1111 "are <id> operands, got: ")
1112 << stringifyExecutionMode(getExecutionMode());
1113
1114 if (getValues().size() != schema.numOperands)
1115 return emitOpError("expected ")
1116 << schema.numOperands << " value operand(s), got "
1117 << getValues().size();
1118
1119 if (getExecutionMode() == ExecutionMode::FPFastMathDefault) {
1120 auto targetType = dyn_cast<TypeAttr>(getValues()[0]);
1121 if (!targetType || !isa<FloatType>(targetType.getValue()) ||
1122 !isa<ScalarType>(targetType.getValue()))
1123 return emitOpError("expected Target Type to be a scalar float type");
1124 auto fastMathMode = dyn_cast<IntegerAttr>(getValues()[1]);
1125 if (!fastMathMode || !fastMathMode.getType().isInteger(32))
1126 return emitOpError("expected Fast-Math Mode to be an i32 constant");
1127 std::optional<FPFastMathMode> mode =
1128 symbolizeFPFastMathMode(fastMathMode.getValue().getZExtValue());
1129 if (!mode)
1130 return emitOpError("expected Fast-Math Mode to be a valid bitmask");
1131 if (bitEnumContainsAny(*mode, FPFastMathMode::Fast))
1132 return emitOpError("expected Fast-Math Mode to not include Fast");
1133 if (bitEnumContainsAny(*mode, FPFastMathMode::AllowTransform) &&
1134 !bitEnumContainsAll(*mode, FPFastMathMode::AllowContract |
1135 FPFastMathMode::AllowReassoc))
1136 return emitOpError("expected Fast-Math Mode with AllowTransform to "
1137 "include AllowContract and AllowReassoc");
1138 return success();
1139 }
1140
1141 if (!llvm::all_of(getValues(), llvm::IsaPred<FlatSymbolRefAttr>))
1142 return emitOpError("expected value operands to be symbol reference");
1143
1144 return success();
1145}
1146
1147LogicalResult
1148spirv::ExecutionModeIdOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1149 for (Attribute value : getValues()) {
1150 auto valueSymbol = dyn_cast<FlatSymbolRefAttr>(value);
1151 if (!valueSymbol)
1152 continue;
1153 if (!symbolTable.lookupNearestSymbolFrom(*this, valueSymbol))
1154 return emitOpError("cannot find symbol referenced by value operand: ")
1155 << valueSymbol.getValue();
1156 }
1157 return success();
1158}
1159
1160//===----------------------------------------------------------------------===//
1161// spirv.func
1162//===----------------------------------------------------------------------===//
1163
1164ParseResult spirv::FuncOp::parse(OpAsmParser &parser, OperationState &result) {
1166 SmallVector<DictionaryAttr> resultAttrs;
1167 SmallVector<Type> resultTypes;
1168 auto &builder = parser.getBuilder();
1169
1171
1172 // Parse the name as a symbol.
1173 StringAttr nameAttr;
1174 if (parser.parseSymbolName(nameAttr, getSymNameAttrName(result.name),
1175 result.attributes))
1176 return failure();
1177
1178 // Parse the function signature.
1179 bool isVariadic = false;
1181 parser, /*allowVariadic=*/false, entryArgs, isVariadic, resultTypes,
1182 resultAttrs))
1183 return failure();
1184
1185 SmallVector<Type> argTypes;
1186 for (auto &arg : entryArgs)
1187 argTypes.push_back(arg.type);
1188 auto fnType = builder.getFunctionType(argTypes, resultTypes);
1189 result.addAttribute(getFunctionTypeAttrName(result.name),
1190 TypeAttr::get(fnType));
1191
1192 // Parse the optional function control keyword.
1193 spirv::FunctionControl fnControl;
1195 return failure();
1196
1197 // If additional attributes are present, parse them.
1198 if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
1199 return failure();
1200
1201 // Add the attributes to the function arguments.
1202 assert(resultAttrs.size() == resultTypes.size());
1204 builder, result, entryArgs, resultAttrs, getArgAttrsAttrName(result.name),
1205 getResAttrsAttrName(result.name));
1206
1207 // Parse the optional function body.
1208 auto *body = result.addRegion();
1209 OptionalParseResult parseResult =
1210 parser.parseOptionalRegion(*body, entryArgs);
1211 return failure(parseResult.has_value() && failed(*parseResult));
1212}
1213
1214void spirv::FuncOp::print(OpAsmPrinter &printer) {
1215 // Print function name, signature, and control.
1216 printer << ' ';
1217 if (StringAttr visibility = getSymVisibilityAttr())
1218 printer << visibility.getValue() << ' ';
1219 printer.printSymbolName(getSymName());
1220 auto fnType = getFunctionType();
1222 printer, *this, fnType.getInputs(),
1223 /*isVariadic=*/false, fnType.getResults());
1224 printer << " \"" << spirv::stringifyFunctionControl(getFunctionControl())
1225 << "\"";
1227 printer, *this,
1229 getFunctionTypeAttrName(), getArgAttrsAttrName(), getResAttrsAttrName(),
1230 getFunctionControlAttrName(), getSymVisibilityAttrName()});
1231
1232 // Print the body if this is not an external function.
1233 Region &body = this->getBody();
1234 if (!body.empty()) {
1235 printer << ' ';
1236 printer.printRegion(body, /*printEntryBlockArgs=*/false,
1237 /*printBlockTerminators=*/true);
1238 }
1239}
1240
1241LogicalResult spirv::FuncOp::verifyType() {
1242 FunctionType fnType = getFunctionType();
1243 if (fnType.getNumResults() > 1)
1244 return emitOpError("cannot have more than one result");
1245
1246 auto hasDecorationAttr = [&](spirv::Decoration decoration,
1247 unsigned argIndex) {
1248 auto func = cast<FunctionOpInterface>(getOperation());
1249 for (auto argAttr : cast<FunctionOpInterface>(func).getArgAttrs(argIndex)) {
1250 if (argAttr.getName() != spirv::DecorationAttr::name)
1251 continue;
1252 if (auto decAttr = dyn_cast<spirv::DecorationAttr>(argAttr.getValue()))
1253 return decAttr.getValue() == decoration;
1254 }
1255 return false;
1256 };
1257
1258 for (unsigned i = 0, e = this->getNumArguments(); i != e; ++i) {
1259 Type param = fnType.getInputs()[i];
1260 auto inputPtrType = dyn_cast<spirv::PointerType>(param);
1261 if (!inputPtrType)
1262 continue;
1263
1264 auto pointeePtrType =
1265 dyn_cast<spirv::PointerType>(inputPtrType.getPointeeType());
1266 if (pointeePtrType) {
1267 // SPIR-V spec, from SPV_KHR_physical_storage_buffer:
1268 // > If an OpFunctionParameter is a pointer (or contains a pointer)
1269 // > and the type it points to is a pointer in the PhysicalStorageBuffer
1270 // > storage class, the function parameter must be decorated with exactly
1271 // > one of AliasedPointer or RestrictPointer.
1272 if (pointeePtrType.getStorageClass() !=
1273 spirv::StorageClass::PhysicalStorageBuffer)
1274 continue;
1275
1276 bool hasAliasedPtr =
1277 hasDecorationAttr(spirv::Decoration::AliasedPointer, i);
1278 bool hasRestrictPtr =
1279 hasDecorationAttr(spirv::Decoration::RestrictPointer, i);
1280 if (!hasAliasedPtr && !hasRestrictPtr)
1281 return emitOpError()
1282 << "with a pointer points to a physical buffer pointer must "
1283 "be decorated either 'AliasedPointer' or 'RestrictPointer'";
1284 continue;
1285 }
1286 // SPIR-V spec, from SPV_KHR_physical_storage_buffer:
1287 // > If an OpFunctionParameter is a pointer (or contains a pointer) in
1288 // > the PhysicalStorageBuffer storage class, the function parameter must
1289 // > be decorated with exactly one of Aliased or Restrict.
1290 if (auto pointeeArrayType =
1291 dyn_cast<spirv::ArrayType>(inputPtrType.getPointeeType())) {
1292 pointeePtrType =
1293 dyn_cast<spirv::PointerType>(pointeeArrayType.getElementType());
1294 } else {
1295 pointeePtrType = inputPtrType;
1296 }
1297
1298 if (!pointeePtrType || pointeePtrType.getStorageClass() !=
1299 spirv::StorageClass::PhysicalStorageBuffer)
1300 continue;
1301
1302 bool hasAliased = hasDecorationAttr(spirv::Decoration::Aliased, i);
1303 bool hasRestrict = hasDecorationAttr(spirv::Decoration::Restrict, i);
1304 if (!hasAliased && !hasRestrict)
1305 return emitOpError() << "with physical buffer pointer must be decorated "
1306 "either 'Aliased' or 'Restrict'";
1307 }
1308
1309 return success();
1310}
1311
1312LogicalResult spirv::FuncOp::verifyBody() {
1313 FunctionType fnType = getFunctionType();
1314 if (!isExternal()) {
1315 Block &entryBlock = front();
1316
1317 unsigned numArguments = this->getNumArguments();
1318 if (entryBlock.getNumArguments() != numArguments)
1319 return emitOpError("entry block must have ")
1320 << numArguments << " arguments to match function signature";
1321
1322 for (auto [index, fnArgType, blockArgType] :
1323 llvm::enumerate(getArgumentTypes(), entryBlock.getArgumentTypes())) {
1324 if (blockArgType != fnArgType) {
1325 return emitOpError("type of entry block argument #")
1326 << index << '(' << blockArgType
1327 << ") must match the type of the corresponding argument in "
1328 << "function signature(" << fnArgType << ')';
1329 }
1330 }
1331 }
1332
1333 auto walkResult = walk([fnType](Operation *op) -> WalkResult {
1334 if (auto retOp = dyn_cast<spirv::ReturnOp>(op)) {
1335 if (fnType.getNumResults() != 0)
1336 return retOp.emitOpError("cannot be used in functions returning value");
1337 } else if (auto retOp = dyn_cast<spirv::ReturnValueOp>(op)) {
1338 if (fnType.getNumResults() != 1)
1339 return retOp.emitOpError(
1340 "returns 1 value but enclosing function requires ")
1341 << fnType.getNumResults() << " results";
1342
1343 auto retOperandType = retOp.getValue().getType();
1344 auto fnResultType = fnType.getResult(0);
1345 if (retOperandType != fnResultType)
1346 return retOp.emitOpError(" return value's type (")
1347 << retOperandType << ") mismatch with function's result type ("
1348 << fnResultType << ")";
1349 }
1350 return WalkResult::advance();
1351 });
1352
1353 // TODO: verify other bits like linkage type.
1354
1355 return failure(walkResult.wasInterrupted());
1356}
1357
1358void spirv::FuncOp::build(OpBuilder &builder, OperationState &state,
1359 StringRef name, FunctionType type,
1360 spirv::FunctionControl control,
1362 state.addAttribute(getSymNameAttrName(state.name),
1363 builder.getStringAttr(name));
1364 state.addAttribute(getFunctionTypeAttrName(state.name), TypeAttr::get(type));
1366 builder.getAttr<spirv::FunctionControlAttr>(control));
1367 state.attributes.append(attrs.begin(), attrs.end());
1368 state.addRegion();
1369}
1370
1371//===----------------------------------------------------------------------===//
1372// spirv.GLFClampOp
1373//===----------------------------------------------------------------------===//
1374
1375ParseResult spirv::GLFClampOp::parse(OpAsmParser &parser,
1378}
1379void spirv::GLFClampOp::print(OpAsmPrinter &p) { printOneResultOp(*this, p); }
1380
1381//===----------------------------------------------------------------------===//
1382// spirv.GLUClampOp
1383//===----------------------------------------------------------------------===//
1384
1385ParseResult spirv::GLUClampOp::parse(OpAsmParser &parser,
1388}
1389void spirv::GLUClampOp::print(OpAsmPrinter &p) { printOneResultOp(*this, p); }
1390
1391//===----------------------------------------------------------------------===//
1392// spirv.GLSClampOp
1393//===----------------------------------------------------------------------===//
1394
1395ParseResult spirv::GLSClampOp::parse(OpAsmParser &parser,
1398}
1399void spirv::GLSClampOp::print(OpAsmPrinter &p) { printOneResultOp(*this, p); }
1400
1401//===----------------------------------------------------------------------===//
1402// spirv.GLNClampOp
1403//===----------------------------------------------------------------------===//
1404
1405ParseResult spirv::GLNClampOp::parse(OpAsmParser &parser,
1408}
1409void spirv::GLNClampOp::print(OpAsmPrinter &p) { printOneResultOp(*this, p); }
1410
1411//===----------------------------------------------------------------------===//
1412// spirv.GLSmoothStepOp
1413//===----------------------------------------------------------------------===//
1414
1415ParseResult spirv::GLSmoothStepOp::parse(OpAsmParser &parser,
1418}
1419void spirv::GLSmoothStepOp::print(OpAsmPrinter &p) {
1420 printOneResultOp(*this, p);
1421}
1422
1423//===----------------------------------------------------------------------===//
1424// spirv.GLFmaOp
1425//===----------------------------------------------------------------------===//
1426
1427ParseResult spirv::GLFmaOp::parse(OpAsmParser &parser, OperationState &result) {
1429}
1430void spirv::GLFmaOp::print(OpAsmPrinter &p) { printOneResultOp(*this, p); }
1431
1432//===----------------------------------------------------------------------===//
1433// spirv.GlobalVariable
1434//===----------------------------------------------------------------------===//
1435
1436void spirv::GlobalVariableOp::build(OpBuilder &builder, OperationState &state,
1437 Type type, StringRef name,
1438 unsigned descriptorSet, unsigned binding) {
1439 build(builder, state, TypeAttr::get(type), builder.getStringAttr(name));
1440 state.addAttribute(
1441 spirv::SPIRVDialect::getAttributeName(spirv::Decoration::DescriptorSet),
1442 builder.getI32IntegerAttr(descriptorSet));
1443 state.addAttribute(
1444 spirv::SPIRVDialect::getAttributeName(spirv::Decoration::Binding),
1445 builder.getI32IntegerAttr(binding));
1446}
1447
1448void spirv::GlobalVariableOp::build(OpBuilder &builder, OperationState &state,
1449 Type type, StringRef name,
1450 spirv::BuiltIn builtin) {
1451 build(builder, state, TypeAttr::get(type), builder.getStringAttr(name));
1452 state.addAttribute(
1453 spirv::SPIRVDialect::getAttributeName(spirv::Decoration::BuiltIn),
1454 builder.getStringAttr(spirv::stringifyBuiltIn(builtin)));
1455}
1456
1457ParseResult spirv::GlobalVariableOp::parse(OpAsmParser &parser,
1460
1461 // Parse variable name.
1462 StringAttr nameAttr;
1463 StringRef initializerAttrName =
1464 spirv::GlobalVariableOp::getInitializerAttrName(result.name);
1465 if (parser.parseSymbolName(nameAttr, getSymNameAttrName(result.name),
1466 result.attributes)) {
1467 return failure();
1468 }
1469
1470 // Parse optional data type
1471 StringRef dataTypeAttrName =
1472 spirv::GlobalVariableOp::getDataTypeAttrName(result.name);
1473 if (succeeded(parser.parseOptionalKeyword(dataTypeAttrName))) {
1474 Type dataType;
1475 if (parser.parseLParen() || parser.parseType(dataType) ||
1476 parser.parseRParen())
1477 return failure();
1478 result.addAttribute(dataTypeAttrName, TypeAttr::get(dataType));
1479 }
1480
1481 // Parse optional initializer
1482 if (succeeded(parser.parseOptionalKeyword(initializerAttrName))) {
1483 FlatSymbolRefAttr initSymbol;
1484 if (parser.parseLParen() ||
1485 parser.parseAttribute(initSymbol, Type(), initializerAttrName,
1486 result.attributes) ||
1487 parser.parseRParen())
1488 return failure();
1489 }
1490
1491 if (parseVariableDecorations(parser, result)) {
1492 return failure();
1493 }
1494
1495 Type type;
1496 StringRef typeAttrName =
1497 spirv::GlobalVariableOp::getTypeAttrName(result.name);
1498 auto loc = parser.getCurrentLocation();
1499 if (parser.parseColonType(type)) {
1500 return failure();
1501 }
1502 if (!isa<spirv::PointerType, spirv::UntypedPointerType>(type)) {
1503 return parser.emitError(loc,
1504 "expected spirv.ptr or spirv.untyped_ptr type");
1505 }
1506 result.addAttribute(typeAttrName, TypeAttr::get(type));
1507
1508 return success();
1509}
1510
1511void spirv::GlobalVariableOp::print(OpAsmPrinter &printer) {
1512 SmallVector<StringRef, 4> elidedAttrs{
1514
1515 // Print variable name.
1516 printer << ' ';
1517 if (StringAttr visibility = getSymVisibilityAttr())
1518 printer << visibility.getValue() << ' ';
1519 printer.printSymbolName(getSymName());
1520 elidedAttrs.push_back(getSymNameAttrName());
1521 elidedAttrs.push_back(getSymVisibilityAttrName());
1522
1523 // Print optional data type
1524 if (std::optional<Type> dataType = getDataType()) {
1525 StringRef dataTypeAttrName = getDataTypeAttrName();
1526 printer << " " << dataTypeAttrName << '(' << *dataType << ')';
1527 elidedAttrs.push_back(dataTypeAttrName);
1528 }
1529
1530 StringRef initializerAttrName = this->getInitializerAttrName();
1531 // Print optional initializer
1532 if (auto initializer = this->getInitializer()) {
1533 printer << " " << initializerAttrName << '(';
1534 printer.printSymbolName(*initializer);
1535 printer << ')';
1536 elidedAttrs.push_back(initializerAttrName);
1537 }
1538
1539 StringRef typeAttrName = this->getTypeAttrName();
1540 elidedAttrs.push_back(typeAttrName);
1541 spirv::printVariableDecorations(*this, printer, elidedAttrs);
1542 printer << " : " << getType();
1543}
1544
1545LogicalResult spirv::GlobalVariableOp::verify() {
1546 if (!isa<spirv::PointerType, spirv::UntypedPointerType>(getType()))
1547 return emitOpError("result must be of a !spv.ptr or !spv.untyped_ptr type");
1548
1549 // SPIR-V spec: "Storage Class is the Storage Class of the memory holding the
1550 // object. It cannot be Generic. It must be the same as the Storage Class
1551 // operand of the Result Type."
1552 // Also, Function storage class is reserved by spirv.Variable.
1553 auto storageClass = this->storageClass();
1554 if (storageClass == spirv::StorageClass::Generic ||
1555 storageClass == spirv::StorageClass::Function) {
1556 return emitOpError("storage class cannot be '")
1557 << stringifyStorageClass(storageClass) << "'";
1558 }
1559
1560 std::optional<Type> dataType = getDataType();
1561 if (dataType && isa<NoneType>(*dataType))
1562 return emitOpError("data type cannot be void");
1563 if (auto ptrType = dyn_cast<spirv::PointerType>(getType())) {
1564 if (dataType)
1565 return emitOpError("data type requires an untyped pointer type");
1566 dataType = ptrType.getPointeeType();
1567 } else if (!dataType) {
1568 // SPIR-V spec: "Data Type must be specified if Storage Class is Function,
1569 // Private, or Workgroup."
1570 if (storageClass == spirv::StorageClass::Private ||
1571 storageClass == spirv::StorageClass::Workgroup)
1572 return emitOpError("with '") << stringifyStorageClass(storageClass)
1573 << "' storage class requires a data type";
1574 // SPIR-V spec: "Initializer must have the same type as Data Type."
1575 if (getInitializer())
1576 return emitOpError("with an initializer requires a data type");
1577 }
1578
1579 if (dataType && storageClass != spirv::StorageClass::Private &&
1580 containsMicroscalingType(*dataType, /*subByteOnly=*/true))
1581 return emitOpError("FP4 and FP6 types require Function or Private storage");
1582
1583 // SPIR-V spec: "A module-scope OpVariable with an Initializer operand must
1584 // not be decorated with the Import Linkage Type."
1585 if (std::optional<spirv::LinkageAttributesAttr> linkage =
1586 getLinkageAttributes()) {
1587 if (linkage->getLinkageType().getValue() == spirv::LinkageType::Import &&
1588 getInitializer()) {
1589 return emitOpError(
1590 "with Import linkage type must not have an initializer");
1591 }
1592 }
1593
1594 if (!dataType)
1595 return success();
1596 return verifyPhysicalStorageBufferDecorations(getOperation(), *dataType);
1597}
1598
1599LogicalResult
1600spirv::GlobalVariableOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1601 if (FlatSymbolRefAttr init = getInitializerAttr()) {
1602 Operation *initOp = symbolTable.lookupNearestSymbolFrom(*this, init);
1603 // TODO: Currently only variable initialization with specialization
1604 // constants is supported. There could be normal constants in the module
1605 // scope as well.
1606 //
1607 // In the current setup we also cannot initialize one global variable with
1608 // another. The problem is that if we try to initialize pointer of type X
1609 // with another pointer type, the validator fails because it expects the
1610 // variable to be initialized to be type X, not pointer to X. Now
1611 // `spirv.GlobalVariable` only allows pointer type, so in the current design
1612 // we cannot initialize one `spirv.GlobalVariable` with another.
1613 if (!initOp ||
1614 !isa<spirv::SpecConstantOp, spirv::SpecConstantCompositeOp>(initOp)) {
1615 return emitOpError("initializer must be result of a "
1616 "spirv.SpecConstant or "
1617 "spirv.SpecConstantCompositeOp op");
1618 }
1619 }
1620
1621 return success();
1622}
1623
1624//===----------------------------------------------------------------------===//
1625// spirv.INTEL.ConstantFunctionPointer
1626//===----------------------------------------------------------------------===//
1627
1628LogicalResult spirv::INTELConstantFunctionPointerOp::verifySymbolUses(
1629 SymbolTableCollection &symbolTable) {
1630 auto funcOp = symbolTable.lookupNearestSymbolFrom<spirv::FuncOp>(
1631 *this, getFunctionAttr());
1632 if (!funcOp) {
1633 return emitOpError("function '")
1634 << getFunction() << "' not found in nearest symbol table";
1635 }
1636 Type pointeeType = cast<spirv::PointerType>(getType()).getPointeeType();
1637 if (pointeeType != funcOp.getFunctionType()) {
1638 return emitOpError("result pointee type mismatch: expected ")
1639 << funcOp.getFunctionType() << ", but provided " << pointeeType;
1640 }
1641 return success();
1642}
1643
1644//===----------------------------------------------------------------------===//
1645// spirv.INTEL.FunctionPointerCall
1646//===----------------------------------------------------------------------===//
1647
1648LogicalResult spirv::INTELFunctionPointerCallOp::verify() {
1649 auto functionType = cast<FunctionType>(
1650 cast<spirv::PointerType>(getFunctionPointer().getType())
1651 .getPointeeType());
1652
1653 OperandRange arguments = getArguments();
1654 if (functionType.getNumInputs() != arguments.size()) {
1655 return emitOpError("has incorrect number of operands for callee: expected ")
1656 << functionType.getNumInputs() << ", but provided "
1657 << arguments.size();
1658 }
1659
1660 for (auto [i, expected, argument] :
1661 llvm::enumerate(functionType.getInputs(), arguments)) {
1662 if (argument.getType() != expected) {
1663 return emitOpError("operand type mismatch: expected operand type ")
1664 << expected << ", but provided " << argument.getType()
1665 << " for operand number " << i;
1666 }
1667 }
1668
1669 if (functionType.getNumResults() != getNumResults()) {
1670 return emitOpError("has incorrect number of results for callee: expected ")
1671 << functionType.getNumResults() << ", but provided "
1672 << getNumResults();
1673 }
1674
1675 if (getReturnValue() &&
1676 getReturnValue().getType() != functionType.getResult(0)) {
1677 return emitOpError("result type mismatch: expected ")
1678 << functionType.getResult(0) << ", but provided "
1679 << getReturnValue().getType();
1680 }
1681
1682 return success();
1683}
1684
1685//===----------------------------------------------------------------------===//
1686// spirv.INTEL.SubgroupBlockRead
1687//===----------------------------------------------------------------------===//
1688
1689LogicalResult spirv::INTELSubgroupBlockReadOp::verify() {
1690 if (failed(verifyBlockReadWritePtrAndValTypes(*this, getPtr(), getValue())))
1691 return failure();
1692
1693 return success();
1694}
1695
1696//===----------------------------------------------------------------------===//
1697// spirv.INTEL.SubgroupBlockWrite
1698//===----------------------------------------------------------------------===//
1699
1700ParseResult spirv::INTELSubgroupBlockWriteOp::parse(OpAsmParser &parser,
1702 // Parse the storage class specification
1703 spirv::StorageClass storageClass;
1705 auto loc = parser.getCurrentLocation();
1706 Type elementType;
1707 if (parseEnumStrAttr(storageClass, parser) ||
1708 parser.parseOperandList(operandInfo, 2) || parser.parseColon() ||
1709 parser.parseType(elementType)) {
1710 return failure();
1711 }
1712
1713 auto ptrType = spirv::PointerType::get(elementType, storageClass);
1714 if (auto valVecTy = dyn_cast<VectorType>(elementType))
1715 ptrType = spirv::PointerType::get(valVecTy.getElementType(), storageClass);
1716
1717 if (parser.resolveOperands(operandInfo, {ptrType, elementType}, loc,
1718 result.operands)) {
1719 return failure();
1720 }
1721 return success();
1722}
1723
1724void spirv::INTELSubgroupBlockWriteOp::print(OpAsmPrinter &printer) {
1725 StringRef sc = stringifyStorageClass(
1726 cast<spirv::PointerType>(getPtr().getType()).getStorageClass());
1727 printer << " \"" << sc << "\" " << getPtr() << ", " << getValue() << " : "
1728 << getValue().getType();
1729}
1730
1731LogicalResult spirv::INTELSubgroupBlockWriteOp::verify() {
1732 if (failed(verifyBlockReadWritePtrAndValTypes(*this, getPtr(), getValue())))
1733 return failure();
1734
1735 return success();
1736}
1737
1738//===----------------------------------------------------------------------===//
1739// spirv.IAddCarryOp
1740//===----------------------------------------------------------------------===//
1741
1742LogicalResult spirv::IAddCarryOp::verify() {
1743 return ::verifyArithmeticExtendedBinaryOp(*this);
1744}
1745
1746ParseResult spirv::IAddCarryOp::parse(OpAsmParser &parser,
1748 return ::parseArithmeticExtendedBinaryOp(parser, result);
1749}
1750
1751void spirv::IAddCarryOp::print(OpAsmPrinter &printer) {
1752 ::printArithmeticExtendedBinaryOp(*this, printer);
1753}
1754
1755//===----------------------------------------------------------------------===//
1756// spirv.ISubBorrowOp
1757//===----------------------------------------------------------------------===//
1758
1759LogicalResult spirv::ISubBorrowOp::verify() {
1760 return ::verifyArithmeticExtendedBinaryOp(*this);
1761}
1762
1763ParseResult spirv::ISubBorrowOp::parse(OpAsmParser &parser,
1765 return ::parseArithmeticExtendedBinaryOp(parser, result);
1766}
1767
1768void spirv::ISubBorrowOp::print(OpAsmPrinter &printer) {
1769 ::printArithmeticExtendedBinaryOp(*this, printer);
1770}
1771
1772//===----------------------------------------------------------------------===//
1773// spirv.SMulExtended
1774//===----------------------------------------------------------------------===//
1775
1776LogicalResult spirv::SMulExtendedOp::verify() {
1777 return ::verifyArithmeticExtendedBinaryOp(*this);
1778}
1779
1780ParseResult spirv::SMulExtendedOp::parse(OpAsmParser &parser,
1782 return ::parseArithmeticExtendedBinaryOp(parser, result);
1783}
1784
1785void spirv::SMulExtendedOp::print(OpAsmPrinter &printer) {
1786 ::printArithmeticExtendedBinaryOp(*this, printer);
1787}
1788
1789//===----------------------------------------------------------------------===//
1790// spirv.UMulExtended
1791//===----------------------------------------------------------------------===//
1792
1793LogicalResult spirv::UMulExtendedOp::verify() {
1794 return ::verifyArithmeticExtendedBinaryOp(*this);
1795}
1796
1797ParseResult spirv::UMulExtendedOp::parse(OpAsmParser &parser,
1799 return ::parseArithmeticExtendedBinaryOp(parser, result);
1800}
1801
1802void spirv::UMulExtendedOp::print(OpAsmPrinter &printer) {
1803 ::printArithmeticExtendedBinaryOp(*this, printer);
1804}
1805
1806//===----------------------------------------------------------------------===//
1807// spirv.MemoryBarrierOp
1808//===----------------------------------------------------------------------===//
1809
1810LogicalResult spirv::MemoryBarrierOp::verify() {
1811 return verifyMemorySemantics(getOperation(), getMemorySemantics());
1812}
1813
1814//===----------------------------------------------------------------------===//
1815// spirv.MemoryNamedBarrierOp
1816//===----------------------------------------------------------------------===//
1817
1818LogicalResult spirv::MemoryNamedBarrierOp::verify() {
1819 return verifyMemorySemantics(getOperation(), getMemorySemantics());
1820}
1821
1822//===----------------------------------------------------------------------===//
1823// spirv.module
1824//===----------------------------------------------------------------------===//
1825
1826void spirv::ModuleOp::build(OpBuilder &builder, OperationState &state,
1827 std::optional<StringRef> name) {
1828 OpBuilder::InsertionGuard guard(builder);
1829 builder.createBlock(state.addRegion());
1830 if (name) {
1831 state.attributes.append(getSymNameAttrName(state.name),
1832 builder.getStringAttr(*name));
1833 }
1834}
1835
1836void spirv::ModuleOp::build(OpBuilder &builder, OperationState &state,
1837 spirv::AddressingModel addressingModel,
1838 spirv::MemoryModel memoryModel,
1839 std::optional<VerCapExtAttr> vceTriple,
1840 std::optional<StringRef> name) {
1841 state.addAttribute(
1842 "addressing_model",
1843 builder.getAttr<spirv::AddressingModelAttr>(addressingModel));
1844 state.addAttribute("memory_model",
1845 builder.getAttr<spirv::MemoryModelAttr>(memoryModel));
1846 OpBuilder::InsertionGuard guard(builder);
1847 builder.createBlock(state.addRegion());
1848 if (vceTriple)
1849 state.addAttribute(getVCETripleAttrName(), *vceTriple);
1850 if (name)
1851 state.addAttribute(getSymNameAttrName(state.name),
1852 builder.getStringAttr(*name));
1853}
1854
1855ParseResult spirv::ModuleOp::parse(OpAsmParser &parser,
1857 Region *body = result.addRegion();
1858
1860
1861 // If the name is present, parse it.
1862 StringAttr nameAttr;
1864 nameAttr, getSymNameAttrName(result.name), result.attributes);
1865
1866 // Parse attributes
1867 spirv::AddressingModel addrModel;
1868 spirv::MemoryModel memoryModel;
1870 result) ||
1872 result))
1873 return failure();
1874
1875 if (succeeded(parser.parseOptionalKeyword("requires"))) {
1876 spirv::VerCapExtAttr vceTriple;
1877 if (parser.parseAttribute(vceTriple,
1878 spirv::ModuleOp::getVCETripleAttrName(),
1879 result.attributes))
1880 return failure();
1881 }
1882
1883 if (parser.parseOptionalAttrDictWithKeyword(result.attributes) ||
1884 parser.parseRegion(*body, /*arguments=*/{}))
1885 return failure();
1886
1887 // Make sure we have at least one block.
1888 if (body->empty())
1889 body->push_back(new Block());
1890
1891 return success();
1892}
1893
1894void spirv::ModuleOp::print(OpAsmPrinter &printer) {
1895 if (StringAttr visibility = getSymVisibilityAttr())
1896 printer << ' ' << visibility.getValue();
1897 if (std::optional<StringRef> name = getName()) {
1898 printer << ' ';
1899 printer.printSymbolName(*name);
1900 }
1901
1902 SmallVector<StringRef, 2> elidedAttrs;
1903
1904 printer << " " << spirv::stringifyAddressingModel(getAddressingModel()) << " "
1905 << spirv::stringifyMemoryModel(getMemoryModel());
1906 auto addressingModelAttrName = spirv::attributeName<spirv::AddressingModel>();
1907 auto memoryModelAttrName = spirv::attributeName<spirv::MemoryModel>();
1908 elidedAttrs.assign({addressingModelAttrName, memoryModelAttrName,
1909 getSymNameAttrName(), getSymVisibilityAttrName()});
1910
1911 if (std::optional<spirv::VerCapExtAttr> triple = getVceTriple()) {
1912 printer << " requires " << *triple;
1913 elidedAttrs.push_back(spirv::ModuleOp::getVCETripleAttrName());
1914 }
1915
1917 (*this)->getDiscardableAttrDictionary().getValue(), elidedAttrs);
1918 printer << ' ';
1919 printer.printRegion(getRegion());
1920}
1921
1922LogicalResult spirv::ModuleOp::verifyRegions() {
1923 Dialect *dialect = (*this)->getDialect();
1925 entryPoints;
1926 mlir::SymbolTable table(*this);
1927
1928 for (auto &op : *getBody()) {
1929 if (op.getDialect() != dialect)
1930 return op.emitError("'spirv.module' can only contain spirv.* ops");
1931
1932 // For EntryPoint op, check that the function and execution model is not
1933 // duplicated in EntryPointOps. Also verify that the interface specified
1934 // comes from globalVariables here to make this check cheaper.
1935 if (auto entryPointOp = dyn_cast<spirv::EntryPointOp>(op)) {
1936 auto funcOp = table.lookup<spirv::FuncOp>(entryPointOp.getFn());
1937 if (!funcOp) {
1938 return entryPointOp.emitError("function '")
1939 << entryPointOp.getFn() << "' not found in 'spirv.module'";
1940 }
1941 if (auto interface = entryPointOp.getInterface()) {
1942 for (Attribute varRef : interface) {
1943 auto varSymRef = dyn_cast<FlatSymbolRefAttr>(varRef);
1944 if (!varSymRef) {
1945 return entryPointOp.emitError(
1946 "expected symbol reference for interface "
1947 "specification instead of '")
1948 << varRef;
1949 }
1950 auto variableOp =
1951 table.lookup<spirv::GlobalVariableOp>(varSymRef.getValue());
1952 if (!variableOp) {
1953 return entryPointOp.emitError("expected spirv.GlobalVariable "
1954 "symbol reference instead of'")
1955 << varSymRef << "'";
1956 }
1957 }
1958 }
1959
1960 auto key = std::pair<spirv::FuncOp, spirv::ExecutionModel>(
1961 funcOp, entryPointOp.getExecutionModel());
1962 if (!entryPoints.try_emplace(key, entryPointOp).second)
1963 return entryPointOp.emitError("duplicate of a previous EntryPointOp");
1964 } else if (auto funcOp = dyn_cast<spirv::FuncOp>(op)) {
1965 // If the function is external and does not have 'Import'
1966 // linkage_attributes(LinkageAttributes), throw an error. 'Import'
1967 // LinkageAttributes is used to import external functions.
1968 auto linkageAttr = funcOp.getLinkageAttributes();
1969 auto hasImportLinkage =
1970 linkageAttr && (linkageAttr.value().getLinkageType().getValue() ==
1971 spirv::LinkageType::Import);
1972 if (funcOp.isExternal() && !hasImportLinkage)
1973 return op.emitError(
1974 "'spirv.module' cannot contain external functions "
1975 "without 'Import' linkage_attributes (LinkageAttributes)");
1976
1977 // TODO: move this check to spirv.func.
1978 for (auto &block : funcOp)
1979 for (auto &op : block) {
1980 if (op.getDialect() != dialect)
1981 return op.emitError(
1982 "functions in 'spirv.module' can only contain spirv.* ops");
1983 }
1984 }
1985 }
1986
1987 return success();
1988}
1989
1990//===----------------------------------------------------------------------===//
1991// spirv.mlir.referenceof
1992//===----------------------------------------------------------------------===//
1993
1994LogicalResult
1995spirv::ReferenceOfOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1996 Operation *specConstSym =
1997 symbolTable.lookupNearestSymbolFrom(*this, getSpecConstAttr());
1998 Type constType;
1999
2000 auto specConstOp = dyn_cast_or_null<spirv::SpecConstantOp>(specConstSym);
2001 if (specConstOp)
2002 constType = specConstOp.getDefaultValue().getType();
2003
2004 auto specConstCompositeOp =
2005 dyn_cast_or_null<spirv::SpecConstantCompositeOp>(specConstSym);
2006 if (specConstCompositeOp)
2007 constType = specConstCompositeOp.getType();
2008
2009 if (!specConstOp && !specConstCompositeOp)
2010 return emitOpError(
2011 "expected spirv.SpecConstant or spirv.SpecConstantComposite symbol");
2012
2013 if (getReference().getType() != constType)
2014 return emitOpError("result type mismatch with the referenced "
2015 "specialization constant's type");
2016
2017 return success();
2018}
2019
2020//===----------------------------------------------------------------------===//
2021// spirv.SpecConstant
2022//===----------------------------------------------------------------------===//
2023
2024ParseResult spirv::SpecConstantOp::parse(OpAsmParser &parser,
2027
2028 StringAttr nameAttr;
2029 Attribute valueAttr;
2030 StringRef defaultValueAttrName =
2031 spirv::SpecConstantOp::getDefaultValueAttrName(result.name);
2032
2033 if (parser.parseSymbolName(nameAttr, getSymNameAttrName(result.name),
2034 result.attributes))
2035 return failure();
2036
2037 // Parse optional spec_id.
2038 if (succeeded(parser.parseOptionalKeyword(kSpecIdAttrName))) {
2039 IntegerAttr specIdAttr;
2040 if (parser.parseLParen() ||
2041 parser.parseAttribute(specIdAttr, kSpecIdAttrName, result.attributes) ||
2042 parser.parseRParen())
2043 return failure();
2044 }
2045
2046 if (parser.parseEqual() ||
2047 parser.parseAttribute(valueAttr, defaultValueAttrName, result.attributes))
2048 return failure();
2049
2050 return success();
2051}
2052
2053void spirv::SpecConstantOp::print(OpAsmPrinter &printer) {
2054 printer << ' ';
2055 if (StringAttr visibility = getSymVisibilityAttr())
2056 printer << visibility.getValue() << ' ';
2057 printer.printSymbolName(getSymName());
2058 if (auto specID =
2059 (*this)->getDiscardableAttrOfType<IntegerAttr>(kSpecIdAttrName))
2060 printer << ' ' << kSpecIdAttrName << '(' << specID.getInt() << ')';
2061 printer << " = " << getDefaultValue();
2062}
2063
2064LogicalResult spirv::SpecConstantOp::verify() {
2065 if (auto specID =
2066 (*this)->getDiscardableAttrOfType<IntegerAttr>(kSpecIdAttrName))
2067 if (specID.getValue().isNegative())
2068 return emitOpError("SpecId cannot be negative");
2069
2070 auto value = getDefaultValue();
2071 if (isa<IntegerAttr, FloatAttr>(value)) {
2072 // Make sure bitwidth is allowed.
2073 if (!isa<spirv::SPIRVType>(value.getType()))
2074 return emitOpError("default value bitwidth disallowed");
2075 return success();
2076 }
2077 return emitOpError(
2078 "default value can only be a bool, integer, or float scalar");
2079}
2080
2081//===----------------------------------------------------------------------===//
2082// spirv.VectorShuffle
2083//===----------------------------------------------------------------------===//
2084
2085LogicalResult spirv::VectorShuffleOp::verify() {
2086 VectorType resultType = cast<VectorType>(getType());
2087
2088 size_t numResultElements = resultType.getNumElements();
2089 if (numResultElements != getComponents().size())
2090 return emitOpError("result type element count (")
2091 << numResultElements
2092 << ") mismatch with the number of component selectors ("
2093 << getComponents().size() << ")";
2094
2095 size_t totalSrcElements =
2096 cast<VectorType>(getVector1().getType()).getNumElements() +
2097 cast<VectorType>(getVector2().getType()).getNumElements();
2098
2099 for (const auto &selector : getComponents().getAsValueRange<IntegerAttr>()) {
2100 uint32_t index = selector.getZExtValue();
2101 if (index >= totalSrcElements &&
2102 index != std::numeric_limits<uint32_t>().max())
2103 return emitOpError("component selector ")
2104 << index << " out of range: expected to be in [0, "
2105 << totalSrcElements << ") or 0xffffffff";
2106 }
2107 return success();
2108}
2109
2110//===----------------------------------------------------------------------===//
2111// spirv.SpecConstantComposite
2112//===----------------------------------------------------------------------===//
2113
2114ParseResult spirv::SpecConstantCompositeOp::parse(OpAsmParser &parser,
2116
2118
2119 StringAttr compositeName;
2120 if (parser.parseSymbolName(compositeName, getSymNameAttrName(result.name),
2121 result.attributes))
2122 return failure();
2123
2124 if (parser.parseLParen())
2125 return failure();
2126
2127 SmallVector<Attribute, 4> constituents;
2128
2129 do {
2130 // The name of the constituent attribute isn't important
2131 const char *attrName = "spec_const";
2132 FlatSymbolRefAttr specConstRef;
2133 NamedAttrList attrs;
2134
2135 if (parser.parseAttribute(specConstRef, Type(), attrName, attrs))
2136 return failure();
2137
2138 constituents.push_back(specConstRef);
2139 } while (!parser.parseOptionalComma());
2140
2141 if (parser.parseRParen())
2142 return failure();
2143
2144 StringAttr compositeSpecConstituentsName =
2145 spirv::SpecConstantCompositeOp::getConstituentsAttrName(result.name);
2146 result.addAttribute(compositeSpecConstituentsName,
2147 parser.getBuilder().getArrayAttr(constituents));
2148
2149 Type type;
2150 if (parser.parseColonType(type))
2151 return failure();
2152
2153 StringAttr typeAttrName =
2154 spirv::SpecConstantCompositeOp::getTypeAttrName(result.name);
2155 result.addAttribute(typeAttrName, TypeAttr::get(type));
2156
2157 return success();
2158}
2159
2160void spirv::SpecConstantCompositeOp::print(OpAsmPrinter &printer) {
2161 printer << ' ';
2162 if (StringAttr visibility = getSymVisibilityAttr())
2163 printer << visibility.getValue() << ' ';
2164 printer.printSymbolName(getSymName());
2165 printer << " (" << llvm::interleaved(this->getConstituents().getValue())
2166 << ") : " << getType();
2167}
2168
2169LogicalResult spirv::SpecConstantCompositeOp::verify() {
2170 auto cType = dyn_cast<spirv::CompositeType>(getType());
2171 auto constituents = this->getConstituents().getValue();
2172
2173 if (!cType)
2174 return emitError("result type must be a composite type, but provided ")
2175 << getType();
2176
2177 if (isa<spirv::CooperativeMatrixType>(cType))
2178 return emitError("unsupported composite type ") << cType;
2179 if (constituents.size() != cType.getNumElements())
2180 return emitError("has incorrect number of operands: expected ")
2181 << cType.getNumElements() << ", but provided "
2182 << constituents.size();
2183
2184 return success();
2185}
2186
2187LogicalResult spirv::SpecConstantCompositeOp::verifySymbolUses(
2188 SymbolTableCollection &symbolTable) {
2189 auto cType = cast<spirv::CompositeType>(getType());
2190 ArrayRef<Attribute> constituents = getConstituents().getValue();
2191
2192 for (auto index : llvm::seq<uint32_t>(0, constituents.size())) {
2193 auto constituent = cast<FlatSymbolRefAttr>(constituents[index]);
2194
2195 Operation *constituentOp =
2196 symbolTable.lookupNearestSymbolFrom(*this, constituent);
2197
2198 if (!constituentOp)
2199 return emitError("unknown constituent symbol ") << constituent.getAttr();
2200
2201 Type constituentType;
2202 if (auto specConstOp = dyn_cast<spirv::SpecConstantOp>(constituentOp)) {
2203 constituentType = specConstOp.getDefaultValue().getType();
2204 } else if (auto specConstCompositeOp =
2205 dyn_cast<spirv::SpecConstantCompositeOp>(constituentOp)) {
2206 constituentType = specConstCompositeOp.getType();
2207 } else {
2208 return emitError("unsupported constituent ")
2209 << constituent.getAttr()
2210 << ": must reference a spirv.SpecConstant or "
2211 "spirv.SpecConstantComposite";
2212 }
2213
2214 if (constituentType != cType.getElementType(index))
2215 return emitError("has incorrect types of operands: expected ")
2216 << cType.getElementType(index) << ", but provided "
2217 << constituentType;
2218 }
2219
2220 return success();
2221}
2222
2223//===----------------------------------------------------------------------===//
2224// spirv.EXTSpecConstantCompositeReplicateOp
2225//===----------------------------------------------------------------------===//
2226
2227ParseResult
2228spirv::EXTSpecConstantCompositeReplicateOp::parse(OpAsmParser &parser,
2231
2232 StringAttr compositeName;
2233 FlatSymbolRefAttr specConstRef;
2234 const char *attrName = "spec_const";
2235 NamedAttrList attrs;
2236 Type type;
2237
2238 if (parser.parseSymbolName(compositeName, getSymNameAttrName(result.name),
2239 result.attributes) ||
2240 parser.parseLParen() ||
2241 parser.parseAttribute(specConstRef, Type(), attrName, attrs) ||
2242 parser.parseRParen() || parser.parseColonType(type))
2243 return failure();
2244
2245 StringAttr compositeSpecConstituentName =
2246 spirv::EXTSpecConstantCompositeReplicateOp::getConstituentAttrName(
2247 result.name);
2248 result.addAttribute(compositeSpecConstituentName, specConstRef);
2249
2250 StringAttr typeAttrName =
2251 spirv::EXTSpecConstantCompositeReplicateOp::getTypeAttrName(result.name);
2252 result.addAttribute(typeAttrName, TypeAttr::get(type));
2253
2254 return success();
2255}
2256
2257void spirv::EXTSpecConstantCompositeReplicateOp::print(OpAsmPrinter &printer) {
2258 printer << ' ';
2259 if (StringAttr visibility = getSymVisibilityAttr())
2260 printer << visibility.getValue() << ' ';
2261 printer.printSymbolName(getSymName());
2262 printer << " (" << this->getConstituent() << ") : " << getType();
2263}
2264
2265LogicalResult spirv::EXTSpecConstantCompositeReplicateOp::verify() {
2266 if (!isa<spirv::CompositeType>(getType()))
2267 return emitError("result type must be a composite type, but provided ")
2268 << getType();
2269
2270 return success();
2271}
2272
2273LogicalResult spirv::EXTSpecConstantCompositeReplicateOp::verifySymbolUses(
2274 SymbolTableCollection &symbolTable) {
2275 auto compositeType = cast<spirv::CompositeType>(getType());
2276 Operation *constituentOp =
2277 symbolTable.lookupNearestSymbolFrom(*this, getConstituent());
2278 if (!constituentOp)
2279 return emitError(
2280 "splat spec constant reference defining constituent not found");
2281
2282 auto constituentSpecConstOp = dyn_cast<spirv::SpecConstantOp>(constituentOp);
2283 if (!constituentSpecConstOp)
2284 return emitError("constituent is not a spec constant");
2285
2286 Type constituentType = constituentSpecConstOp.getDefaultValue().getType();
2287 Type compositeElementType = compositeType.getElementType(0);
2288 if (constituentType != compositeElementType)
2289 return emitError("constituent has incorrect type: expected ")
2290 << compositeElementType << ", but provided " << constituentType;
2291
2292 return success();
2293}
2294
2295//===----------------------------------------------------------------------===//
2296// spirv.SpecConstantOperation
2297//===----------------------------------------------------------------------===//
2298
2299ParseResult spirv::SpecConstantOperationOp::parse(OpAsmParser &parser,
2301 Region *body = result.addRegion();
2302
2303 if (parser.parseKeyword("wraps"))
2304 return failure();
2305
2306 body->push_back(new Block);
2307 Block &block = body->back();
2308 Operation *wrappedOp = parser.parseGenericOperation(&block, block.begin());
2309
2310 if (!wrappedOp)
2311 return failure();
2312
2313 OpBuilder builder(parser.getContext());
2314 builder.setInsertionPointToEnd(&block);
2315 spirv::YieldOp::create(builder, wrappedOp->getLoc(), wrappedOp->getResult(0));
2316 result.location = wrappedOp->getLoc();
2317
2318 result.addTypes(wrappedOp->getResult(0).getType());
2319
2320 if (parser.parseOptionalAttrDict(result.attributes))
2321 return failure();
2322
2323 return success();
2324}
2325
2326void spirv::SpecConstantOperationOp::print(OpAsmPrinter &printer) {
2327 printer << " wraps ";
2328 printer.printGenericOp(&getBody().front().front());
2329}
2330
2331LogicalResult spirv::SpecConstantOperationOp::verifyRegions() {
2332 Block &block = getRegion().getBlocks().front();
2333
2334 if (block.getOperations().size() != 2)
2335 return emitOpError("expected exactly 2 nested ops");
2336
2337 Operation &enclosedOp = block.getOperations().front();
2338
2340 return emitOpError("invalid enclosed op");
2341
2342 for (auto operand : enclosedOp.getOperands())
2343 if (!isa_and_present<spirv::ConstantOp, spirv::ReferenceOfOp,
2344 spirv::SpecConstantOperationOp>(
2345 operand.getDefiningOp()))
2346 return emitOpError(
2347 "invalid operand, must be defined by a constant operation");
2348
2349 return success();
2350}
2351
2352//===----------------------------------------------------------------------===//
2353// spirv.GL.FrexpStruct
2354//===----------------------------------------------------------------------===//
2355
2356LogicalResult spirv::GLFrexpStructOp::verify() {
2357 spirv::StructType structTy =
2358 dyn_cast<spirv::StructType>(getResult().getType());
2359
2360 if (structTy.getNumElements() != 2)
2361 return emitError("result type must be a struct type with two memebers");
2362
2363 Type significandTy = structTy.getElementType(0);
2364 Type exponentTy = structTy.getElementType(1);
2365 VectorType exponentVecTy = dyn_cast<VectorType>(exponentTy);
2366 IntegerType exponentIntTy = dyn_cast<IntegerType>(exponentTy);
2367
2368 Type operandTy = getOperand().getType();
2369 VectorType operandVecTy = dyn_cast<VectorType>(operandTy);
2370 FloatType operandFTy = dyn_cast<FloatType>(operandTy);
2371
2372 if (significandTy != operandTy)
2373 return emitError("member zero of the resulting struct type must be the "
2374 "same type as the operand");
2375
2376 if (exponentVecTy) {
2377 IntegerType componentIntTy =
2378 dyn_cast<IntegerType>(exponentVecTy.getElementType());
2379 if (!componentIntTy || componentIntTy.getWidth() != 32)
2380 return emitError("member one of the resulting struct type must"
2381 "be a scalar or vector of 32 bit integer type");
2382 } else if (!exponentIntTy || exponentIntTy.getWidth() != 32) {
2383 return emitError("member one of the resulting struct type "
2384 "must be a scalar or vector of 32 bit integer type");
2385 }
2386
2387 // Check that the two member types have the same number of components
2388 if (operandVecTy && exponentVecTy &&
2389 (exponentVecTy.getNumElements() == operandVecTy.getNumElements()))
2390 return success();
2391
2392 if (operandFTy && exponentIntTy)
2393 return success();
2394
2395 return emitError("member one of the resulting struct type must have the same "
2396 "number of components as the operand type");
2397}
2398
2399//===----------------------------------------------------------------------===//
2400// spirv.GL.Ldexp
2401//===----------------------------------------------------------------------===//
2402
2403static LogicalResult verifyFloatIntegerBuiltin(Operation *op, Type floatType,
2404 Type integerType) {
2405 if (isa<FloatType>(floatType) != isa<IntegerType>(integerType))
2406 return op->emitOpError("operands must both be scalars or vectors");
2407
2408 auto getNumElements = [](Type type) -> unsigned {
2409 if (auto vectorType = dyn_cast<VectorType>(type))
2410 return vectorType.getNumElements();
2411 return 1;
2412 };
2413
2414 if (getNumElements(floatType) != getNumElements(integerType))
2415 return op->emitOpError("operands must have the same number of elements");
2416
2417 return success();
2418}
2419
2420LogicalResult spirv::GLLdexpOp::verify() {
2421 return verifyFloatIntegerBuiltin(getOperation(), getX().getType(),
2422 getExp().getType());
2423}
2424
2425//===----------------------------------------------------------------------===//
2426// spirv.CL.ldexp
2427//===----------------------------------------------------------------------===//
2428
2429LogicalResult spirv::CLLdexpOp::verify() {
2430 return verifyFloatIntegerBuiltin(getOperation(), getX().getType(),
2431 getExp().getType());
2432}
2433
2434//===----------------------------------------------------------------------===//
2435// spirv.CL.pown
2436//===----------------------------------------------------------------------===//
2437
2438LogicalResult spirv::CLPownOp::verify() {
2439 return verifyFloatIntegerBuiltin(getOperation(), getX().getType(),
2440 getY().getType());
2441}
2442
2443//===----------------------------------------------------------------------===//
2444// spirv.CL.rootn
2445//===----------------------------------------------------------------------===//
2446
2447LogicalResult spirv::CLRootnOp::verify() {
2448 return verifyFloatIntegerBuiltin(getOperation(), getX().getType(),
2449 getN().getType());
2450}
2451
2452//===----------------------------------------------------------------------===//
2453// spirv.CL.sincos
2454//===----------------------------------------------------------------------===//
2455
2456LogicalResult spirv::CLSincosOp::verify() {
2457 auto storageClass =
2458 cast<spirv::PointerType>(getCosval().getType()).getStorageClass();
2459 if (!llvm::is_contained(
2460 {spirv::StorageClass::CrossWorkgroup, spirv::StorageClass::Workgroup,
2461 spirv::StorageClass::Function, spirv::StorageClass::Generic},
2462 storageClass))
2463 return emitOpError("cosval must point to CrossWorkgroup, Workgroup, "
2464 "Function, or Generic storage");
2465 return success();
2466}
2467
2468//===----------------------------------------------------------------------===//
2469// spirv.ShiftLeftLogicalOp
2470//===----------------------------------------------------------------------===//
2471
2472LogicalResult spirv::ShiftLeftLogicalOp::verify() {
2473 return verifyShiftOp(*this);
2474}
2475
2476//===----------------------------------------------------------------------===//
2477// spirv.ShiftRightArithmeticOp
2478//===----------------------------------------------------------------------===//
2479
2480LogicalResult spirv::ShiftRightArithmeticOp::verify() {
2481 return verifyShiftOp(*this);
2482}
2483
2484//===----------------------------------------------------------------------===//
2485// spirv.ShiftRightLogicalOp
2486//===----------------------------------------------------------------------===//
2487
2488LogicalResult spirv::ShiftRightLogicalOp::verify() {
2489 return verifyShiftOp(*this);
2490}
2491
2492//===----------------------------------------------------------------------===//
2493// spirv.VectorTimesScalarOp
2494//===----------------------------------------------------------------------===//
2495
2496LogicalResult spirv::VectorTimesScalarOp::verify() {
2497 if (getVector().getType() != getType())
2498 return emitOpError("vector operand and result type mismatch");
2499 auto scalarType = cast<VectorType>(getType()).getElementType();
2500 if (getScalar().getType() != scalarType)
2501 return emitOpError("scalar operand and result element type match");
2502 return success();
2503}
static Value getPointer(Location loc, Value value, ConversionPatternRewriter &rewriter)
return success()
static int64_t getNumElements(Type t)
Compute the total number of elements in the given type, also taking into account nested types.
ArrayAttr()
static Value max(ImplicitLocOpBuilder &builder, Value value, Value bound)
static ParseResult parseArithmeticExtendedBinaryOp(OpAsmParser &parser, OperationState &result)
Definition SPIRVOps.cpp:311
static Type getValueType(Attribute attr)
Definition SPIRVOps.cpp:846
static LogicalResult verifyConstantType(spirv::ConstantOp op, Attribute value, Type opType)
Definition SPIRVOps.cpp:613
static ParseResult parseOneResultSameOperandTypeOp(OpAsmParser &parser, OperationState &result)
Definition SPIRVOps.cpp:165
static LogicalResult verifyArithmeticExtendedBinaryOp(ExtendedBinaryOp op)
Definition SPIRVOps.cpp:297
static LogicalResult verifyFloatIntegerBuiltin(Operation *op, Type floatType, Type integerType)
static LogicalResult verifyShiftOp(Operation *op)
Definition SPIRVOps.cpp:343
static LogicalResult verifyBlockReadWritePtrAndValTypes(BlockReadWriteOpTy op, Value ptr, Value val)
Definition SPIRVOps.cpp:214
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
Definition SPIRVOps.cpp:230
static void printOneResultOp(Operation *op, OpAsmPrinter &p)
Definition SPIRVOps.cpp:194
static void printArithmeticExtendedBinaryOp(Operation *op, OpAsmPrinter &printer)
Definition SPIRVOps.cpp:335
ParseResult parseSymbolName(StringAttr &result)
Parse an -identifier and store it (without the '@' symbol) in a string attribute.
virtual ParseResult parseOptionalSymbolName(StringAttr &result)=0
Parse an optional -identifier and store it (without the '@' symbol) in a string attribute.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())=0
Parse a list of comma-separated items with an optional delimiter.
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
MLIRContext * getContext() const
virtual ParseResult parseRParen()=0
Parse a ) token.
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseOptionalColon()=0
Parse a : token if present.
ParseResult addTypeToList(Type type, SmallVectorImpl< Type > &result)
Add the specified type to the end of the specified type list and return success.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result)=0
Parse a named dictionary into 'result' if the attributes keyword is present.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual ParseResult parseOptionalComma()=0
Parse a , token if present.
virtual ParseResult parseColon()=0
Parse a : token.
ParseResult addTypesToList(ArrayRef< Type > types, SmallVectorImpl< Type > &result)
Add the specified types to the end of the specified type list and return success.
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseOptionalLParen()=0
Parse a ( token if present.
ParseResult parseKeywordType(const char *keyword, Type &result)
Parse a keyword followed by a type.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
virtual void printSymbolName(StringRef symbolRef)
Print the given string as a symbol reference, i.e.
Attributes are known-constant values of operations.
Definition Attributes.h:25
Block represents an ordered list of Operations.
Definition Block.h:34
ValueTypeRange< BlockArgListType > getArgumentTypes()
Return a range containing the types of the arguments for this block.
Definition Block.cpp:154
unsigned getNumArguments()
Definition Block.h:153
OpListType & getOperations()
Definition Block.h:162
Operation & front()
Definition Block.h:178
iterator begin()
Definition Block.h:168
IntegerAttr getI32IntegerAttr(int32_t value)
Definition Builders.cpp:208
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
ArrayAttr getI32ArrayAttr(ArrayRef< int32_t > values)
Definition Builders.cpp:285
FloatAttr getFloatAttr(Type type, double value)
Definition Builders.cpp:263
FunctionType getFunctionType(TypeRange inputs, TypeRange results)
Definition Builders.cpp:84
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:75
BoolAttr getBoolAttr(bool value)
Definition Builders.cpp:108
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
Definition Builders.cpp:275
MLIRContext * getContext() const
Definition Builders.h:56
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
Definition Builders.h:101
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
static DenseFPElementsAttr get(const ShapedType &type, Arg &&arg)
Get an instance of a DenseFPElementsAttr with the given arguments.
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
Definition Dialect.h:38
A symbol reference with a reference path containing a single element.
This class represents a diagnostic that is inflight and set to be reported.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
Attribute get(StringAttr name) const
Return the specified attribute if present, null otherwise.
void append(StringRef name, Attribute attr)
Add an attribute with the specified name.
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual ParseResult parseRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
virtual OptionalParseResult parseOptionalRegion(Region &region, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region if present.
virtual Operation * parseGenericOperation(Block *insertBlock, Block::iterator insertPt)=0
Parse an operation in its generic form.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDictWithKeyword(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary prefixed with 'attribute...
void printOperands(OperandRange operands)
Print a comma separated range of operation operands out of line to avoid instantiating the range iter...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
virtual void printGenericOp(Operation *op, bool printOpName=true)=0
Print the entire operation with the default generic assembly form.
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Definition Builders.cpp:439
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Definition Builders.h:439
A trait to mark ops that can be enclosed/wrapped in a SpecConstantOperation op.
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
type_range getType() const
void populateInherentAttrs(Operation *op, NamedAttrList &attrs) const
Append the inherent attributes stored in the properties of op to attrs.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Attribute getDiscardableAttr(StringRef name)
Access a discardable attribute by name, returns a null Attribute if the discardable attribute does no...
Definition Operation.h:487
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
Definition Operation.h:237
Value getOperand(unsigned idx)
Definition Operation.h:377
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
Definition Operation.h:555
operand_type_range getOperandTypes()
Definition Operation.h:424
result_type_range getResultTypes()
Definition Operation.h:455
operand_range getOperands()
Returns an iterator on the underlying Value's.
Definition Operation.h:405
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
This class implements Optional functionality for ParseResult.
bool has_value() const
Returns true if we contain a valid ParseResult value.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
void push_back(Block *block)
Definition Region.h:61
Block & back()
Definition Region.h:64
bool empty()
Definition Region.h:60
This class represents a collection of SymbolTables.
virtual Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
This class allows for representing and managing the symbol table used by operations with the 'SymbolT...
Definition SymbolTable.h:25
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
Dialect & getDialect() const
Get the dialect this type is registered to.
Definition Types.h:107
Type front()
Return first type in the range.
Definition TypeRange.h:164
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
A utility result that is used to signal how to proceed with an ongoing walk:
Definition WalkResult.h:29
static WalkResult advance()
Definition WalkResult.h:47
static ArrayType get(Type elementType, unsigned elementCount)
static PointerType get(Type pointeeType, StorageClass storageClass)
SPIR-V struct type.
Definition SPIRVTypes.h:314
unsigned getNumElements() const
Type getElementType(unsigned) const
An attribute that specifies the SPIR-V (version, capabilities, extensions) triple.
void addArgAndResultAttrs(Builder &builder, OperationState &result, ArrayRef< DictionaryAttr > argAttrs, ArrayRef< DictionaryAttr > resultAttrs, StringAttr argAttrsName, StringAttr resAttrsName)
Adds argument and result attributes, provided as argAttrs and resultAttrs arguments,...
void walk(Operation *op, function_ref< void(Region *)> callback, WalkOrder order)
Walk all of the regions, blocks, or operations nested under (and including) the given operation.
Definition Visitors.h:102
ArrayRef< NamedAttribute > getArgAttrs(FunctionOpInterface op, unsigned index)
Return all of the attributes for the argument at 'index'.
ParseResult parseFunctionSignatureWithArguments(OpAsmParser &parser, bool allowVariadic, SmallVectorImpl< OpAsmParser::Argument > &arguments, bool &isVariadic, SmallVectorImpl< Type > &resultTypes, SmallVectorImpl< DictionaryAttr > &resultAttrs)
Parses a function signature using parser.
void printFunctionAttributes(OpAsmPrinter &p, Operation *op, ArrayRef< StringRef > elided={})
Prints the list of function prefixed with the "attributes" keyword.
void printFunctionSignature(OpAsmPrinter &p, FunctionOpInterface op, ArrayRef< Type > argTypes, bool isVariadic, ArrayRef< Type > resultTypes)
Prints the signature of the function-like operation op.
ParseResult parseOptionalVisibilityKeyword(OpAsmParser &parser, NamedAttrList &attrs)
Parse an optional visibility attribute keyword (i.e., public, private, or nested) without quotes in a...
Operation::operand_range getIndices(Operation *op)
Get the indices that the given load/store operation is operating on.
Definition Utils.cpp:18
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
uint64_t getN(LevelType lt)
Definition Enums.h:442
constexpr char kFnNameAttrName[]
constexpr char kSpecIdAttrName[]
LogicalResult verifyMemorySemantics(Operation *op, spirv::MemorySemantics memorySemantics)
Definition SPIRVOps.cpp:70
ParseResult parseEnumStrAttr(EnumClass &value, OpAsmParser &parser, StringRef attrName=spirv::attributeName< EnumClass >())
Parses the next string attribute in parser as an enumerant of the given EnumClass.
ParseResult parseEnumKeywordAttr(EnumClass &value, ParserType &parser, StringRef attrName=spirv::attributeName< EnumClass >())
Parses the next keyword in parser as an enumerant of the given EnumClass.
void printVariableDecorations(Operation *op, OpAsmPrinter &printer, SmallVectorImpl< StringRef > &elidedAttrs)
Definition SPIRVOps.cpp:134
LogicalResult verifyPhysicalStorageBufferDecorations(Operation *op, Type pointeeType)
Verifies the SPV_KHR_physical_storage_buffer rule that a variable whose pointee is a pointer (or arra...
Definition SPIRVOps.cpp:94
bool containsMicroscalingType(Type type, bool subByteOnly=false)
Returns whether a type contains a microscaling element, including through composite types and pointer...
constexpr StringRef attributeName()
AddressingModel getAddressingModel(TargetEnvAttr targetAttr, bool use64bitAddress)
Returns addressing model selected based on target environment.
FailureOr< ExecutionModel > getExecutionModel(TargetEnvAttr targetAttr)
Returns execution model selected based on target environment.
FailureOr< MemoryModel > getMemoryModel(TargetEnvAttr targetAttr)
Returns memory model selected based on target environment.
LogicalResult extractValueFromConstOp(Operation *op, int32_t &value)
Definition SPIRVOps.cpp:50
std::string getDecorationString(Decoration decoration)
Converts a SPIR-V Decoration enum value to its snake_case string representation for use in MLIR attri...
ParseResult parseVariableDecorations(OpAsmParser &parser, OperationState &state)
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
This is the representation of an operand reference.
This represents an operation in an abstracted form, suitable for use with the builder APIs.
void addAttribute(StringRef name, Attribute attr)
Add an attribute with the specified name.
Region * addRegion()
Create a region that should be attached to the operation.