MLIR 24.0.0git
MemoryOps.cpp
Go to the documentation of this file.
1//===- MemoryOps.cpp - MLIR SPIR-V Memory Ops ----------------------------===//
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// Defines the memory operations in the SPIR-V dialect.
10//
11//===----------------------------------------------------------------------===//
12
15
16#include "SPIRVOpUtils.h"
17#include "SPIRVParsingUtils.h"
19#include "mlir/IR/Diagnostics.h"
20
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/Support/Casting.h"
23
24using namespace mlir::spirv::AttrNames;
25
26namespace mlir::spirv {
27
28/// Parses optional memory access (a.k.a. memory operand) attributes attached to
29/// a memory access operand/pointer. Specifically, parses the following syntax:
30/// (`[` memory-access `]`)?
31/// where:
32/// memory-access ::= `"None"` | `"Volatile"` | `"Aligned", `
33/// integer-literal | `"NonTemporal"`
34template <typename MemoryOpTy>
36 OperationState &state) {
37 // Parse an optional list of attributes staring with '['
38 if (parser.parseOptionalLSquare()) {
39 // Nothing to do
40 return success();
41 }
42
43 spirv::MemoryAccess memoryAccessAttr;
44 StringAttr memoryAccessAttrName =
45 MemoryOpTy::getMemoryAccessAttrName(state.name);
47 memoryAccessAttr, parser, state, memoryAccessAttrName))
48 return failure();
49
50 if (spirv::bitEnumContainsAll(memoryAccessAttr,
51 spirv::MemoryAccess::Aligned)) {
52 // Parse integer attribute for alignment.
53 Attribute alignmentAttr;
54 StringAttr alignmentAttrName = MemoryOpTy::getAlignmentAttrName(state.name);
55 Type i32Type = parser.getBuilder().getIntegerType(32);
56 if (parser.parseComma() ||
57 parser.parseAttribute(alignmentAttr, i32Type, alignmentAttrName,
58 state.attributes)) {
59 return failure();
60 }
61 }
62 return parser.parseRSquare();
63}
64
65// TODO Make sure to merge this and the previous function into one template
66// parameterized by memory access attribute name and alignment. Doing so now
67// results in VS2017 in producing an internal error (at the call site) that's
68// not detailed enough to understand what is happening.
69template <typename MemoryOpTy>
71 OperationState &state) {
72 // Parse an optional list of attributes staring with '['
73 if (parser.parseOptionalLSquare()) {
74 // Nothing to do
75 return success();
76 }
77
78 spirv::MemoryAccess memoryAccessAttr;
79 StringRef memoryAccessAttrName =
80 MemoryOpTy::getSourceMemoryAccessAttrName(state.name);
82 memoryAccessAttr, parser, state, memoryAccessAttrName))
83 return failure();
84
85 if (spirv::bitEnumContainsAll(memoryAccessAttr,
86 spirv::MemoryAccess::Aligned)) {
87 // Parse integer attribute for alignment.
88 Attribute alignmentAttr;
89 StringAttr alignmentAttrName =
90 MemoryOpTy::getSourceAlignmentAttrName(state.name);
91 Type i32Type = parser.getBuilder().getIntegerType(32);
92 if (parser.parseComma() ||
93 parser.parseAttribute(alignmentAttr, i32Type, alignmentAttrName,
94 state.attributes)) {
95 return failure();
96 }
97 }
98 return parser.parseRSquare();
99}
100
101// TODO Make sure to merge this and the previous function into one template
102// parameterized by memory access attribute name and alignment. Doing so now
103// results in VS2017 in producing an internal error (at the call site) that's
104// not detailed enough to understand what is happening.
105template <typename MemoryOpTy>
107 MemoryOpTy memoryOp, OpAsmPrinter &printer,
108 SmallVectorImpl<StringRef> &elidedAttrs,
109 std::optional<spirv::MemoryAccess> memoryAccessAtrrValue = std::nullopt,
110 std::optional<uint32_t> alignmentAttrValue = std::nullopt) {
111
112 // Print optional memory access attribute.
113 if (auto memAccess =
114 (memoryAccessAtrrValue ? memoryAccessAtrrValue
115 : memoryOp.getSourceMemoryAccess())) {
116 elidedAttrs.push_back(memoryOp.getSourceMemoryAccessAttrName());
117
118 printer << ", [\"" << stringifyMemoryAccess(*memAccess) << "\"";
119
120 if (spirv::bitEnumContainsAll(*memAccess, spirv::MemoryAccess::Aligned)) {
121 // Print integer alignment attribute.
122 if (auto alignment =
123 (alignmentAttrValue ? alignmentAttrValue
124 : memoryOp.getSourceAlignment())) {
125 elidedAttrs.push_back(memoryOp.getSourceAlignmentAttrName());
126 printer << ", " << *alignment;
127 }
128 }
129 printer << "]";
130 }
131 elidedAttrs.push_back(spirv::attributeName<spirv::StorageClass>());
132}
133
134template <typename MemoryOpTy>
136 MemoryOpTy memoryOp, OpAsmPrinter &printer,
137 SmallVectorImpl<StringRef> &elidedAttrs,
138 std::optional<spirv::MemoryAccess> memoryAccessAtrrValue = std::nullopt,
139 std::optional<uint32_t> alignmentAttrValue = std::nullopt) {
140 // Print optional memory access attribute.
141 if (auto memAccess = (memoryAccessAtrrValue ? memoryAccessAtrrValue
142 : memoryOp.getMemoryAccess())) {
143 elidedAttrs.push_back(memoryOp.getMemoryAccessAttrName());
144
145 printer << " [\"" << stringifyMemoryAccess(*memAccess) << "\"";
146
147 if (spirv::bitEnumContainsAll(*memAccess, spirv::MemoryAccess::Aligned)) {
148 // Print integer alignment attribute.
149 if (auto alignment = (alignmentAttrValue ? alignmentAttrValue
150 : memoryOp.getAlignment())) {
151 elidedAttrs.push_back(memoryOp.getAlignmentAttrName());
152 printer << ", " << *alignment;
153 }
154 }
155 printer << "]";
156 }
157 elidedAttrs.push_back(spirv::attributeName<spirv::StorageClass>());
158}
159
160template <typename LoadStoreOpTy>
161static LogicalResult verifyLoadStorePtrAndValTypes(LoadStoreOpTy op, Value ptr,
162 Value val) {
163 // ODS already checks ptr is a pointer. For a typed pointer, just check that
164 // the pointee type of the pointer and the type of the value are the same
165 //
166 // TODO: Check that the value type satisfies restrictions of
167 // SPIR-V OpLoad/OpStore operations
168 if (auto ptrType = dyn_cast<spirv::PointerType>(ptr.getType())) {
169 if (val.getType() != ptrType.getPointeeType())
170 return op.emitOpError("mismatch in result type and pointer type");
171 return success();
172 }
173 // Untyped pointers must still not access types like none that no typed
174 // pointer can point to.
175 if (!isa<spirv::SPIRVType>(val.getType()))
176 return op.emitOpError("cannot access a value of type ")
177 << val.getType() << " through an untyped pointer";
178 return success();
179}
180
181namespace {
182/// Whether the pointer a memory operands mask applies to is read through,
183/// written through, or both.
184enum class MemoryAccessKind { Read, Write, ReadWrite };
185} // namespace
186
187/// Verifies the memory operands mask `memAccessAttr` of `op` and its companion
188/// alignment attribute `alignmentAttr`. `kind` tells how the pointer the mask
189/// applies to is accessed.
190static LogicalResult
192 spirv::MemoryAccessAttr memAccessAttr,
193 Attribute alignmentAttr, MemoryAccessKind kind) {
194 // ODS checks for attributes values. Just need to verify that if the
195 // memory-access attribute is Aligned, then the alignment attribute must be
196 // present.
197 if (!memAccessAttr) {
198 // Alignment attribute shouldn't be present if memory access attribute is
199 // not present.
200 if (alignmentAttr) {
201 return op->emitOpError(
202 "invalid alignment specification without aligned memory access "
203 "specification");
204 }
205 return success();
206 }
207
208 spirv::MemoryAccess memAccess = memAccessAttr.getValue();
209
210 // MakePointerAvailable applies to writes through the pointer.
211 if (kind == MemoryAccessKind::Read &&
212 spirv::bitEnumContainsAll(memAccess,
213 spirv::MemoryAccess::MakePointerAvailable)) {
214 return op->emitOpError(
215 "not compatible with memory operand 'MakePointerAvailable'");
216 }
217
218 // MakePointerVisible applies to reads through the pointer.
219 if (kind == MemoryAccessKind::Write &&
220 spirv::bitEnumContainsAll(memAccess,
221 spirv::MemoryAccess::MakePointerVisible)) {
222 return op->emitOpError(
223 "not compatible with memory operand 'MakePointerVisible'");
224 }
225
226 if (spirv::bitEnumContainsAny(memAccess,
227 spirv::MemoryAccess::MakePointerAvailable |
228 spirv::MemoryAccess::MakePointerVisible) &&
229 !spirv::bitEnumContainsAll(memAccess,
230 spirv::MemoryAccess::NonPrivatePointer)) {
231 return op->emitOpError(
232 "memory operand 'MakePointerAvailable' or 'MakePointerVisible' "
233 "requires 'NonPrivatePointer' to also be specified");
234 }
235
236 if (spirv::bitEnumContainsAll(memAccess, spirv::MemoryAccess::Aligned)) {
237 if (!alignmentAttr) {
238 return op->emitOpError("missing alignment value");
239 }
240 } else {
241 if (alignmentAttr) {
242 return op->emitOpError(
243 "invalid alignment specification with non-aligned memory access "
244 "specification");
245 }
246 }
247 return success();
248}
249
250/// Verifies the default (non-Source) memory operands mask of `memoryOp`.
251template <typename MemoryOpTy>
252static LogicalResult verifyMemoryAccessAttribute(MemoryOpTy memoryOp,
253 MemoryAccessKind kind) {
254 return verifyMemoryAccessAttribute(memoryOp.getOperation(),
255 memoryOp.getMemoryAccessAttr(),
256 memoryOp.getAlignmentAttr(), kind);
257}
258
259//===----------------------------------------------------------------------===//
260// spirv.AccessChainOp
261//===----------------------------------------------------------------------===//
262
264 auto ptrType = dyn_cast<spirv::PointerType>(type);
265 if (!ptrType) {
266 emitError(baseLoc, "'spirv.AccessChain' op expected a pointer "
267 "to composite type, but provided ")
268 << type;
269 return nullptr;
270 }
271
272 auto resultType = ptrType.getPointeeType();
273 auto resultStorageClass = ptrType.getStorageClass();
274 int32_t index = 0;
275
276 for (auto indexSSA : indices) {
277 auto cType = dyn_cast<spirv::CompositeType>(resultType);
278 if (!cType) {
279 emitError(
280 baseLoc,
281 "'spirv.AccessChain' op cannot extract from non-composite type ")
282 << resultType << " with index " << index;
283 return nullptr;
284 }
285 index = 0;
286 if (isa<spirv::StructType>(resultType)) {
287 Operation *op = indexSSA.getDefiningOp();
288 if (!op) {
289 emitError(baseLoc, "'spirv.AccessChain' op index must be an "
290 "integer spirv.Constant to access "
291 "element of spirv.struct");
292 return nullptr;
293 }
294
295 // TODO: this should be relaxed to allow
296 // integer literals of other bitwidths.
297 if (failed(spirv::extractValueFromConstOp(op, index))) {
298 emitError(
299 baseLoc,
300 "'spirv.AccessChain' index must be an integer spirv.Constant to "
301 "access element of spirv.struct, but provided ")
302 << op->getName();
303 return nullptr;
304 }
305 if (index < 0 || static_cast<uint64_t>(index) >= cType.getNumElements()) {
306 emitError(baseLoc, "'spirv.AccessChain' op index ")
307 << index << " out of bounds for " << resultType;
308 return nullptr;
309 }
310 }
311 resultType = cType.getElementType(index);
312 }
313 return spirv::PointerType::get(resultType, resultStorageClass);
314}
315
316void AccessChainOp::build(OpBuilder &builder, OperationState &state,
317 Value basePtr, ValueRange indices) {
318 auto type = getElementPtrType(basePtr.getType(), indices, state.location);
319 assert(type && "Unable to deduce return type based on basePtr and indices");
320 build(builder, state, type, basePtr, indices);
321}
322
323template <typename Op>
324static LogicalResult verifyAccessChain(Op accessChainOp, ValueRange indices) {
325 auto resultType = getElementPtrType(accessChainOp.getBasePtr().getType(),
326 indices, accessChainOp.getLoc());
327 if (!resultType)
328 return failure();
329
330 auto providedResultType =
331 dyn_cast<spirv::PointerType>(accessChainOp.getType());
332 if (!providedResultType)
333 return accessChainOp.emitOpError(
334 "result type must be a pointer, but provided")
335 << providedResultType;
336
337 if (resultType != providedResultType)
338 return accessChainOp.emitOpError("invalid result type: expected ")
339 << resultType << ", but provided " << providedResultType;
340
341 return success();
342}
343
344LogicalResult AccessChainOp::verify() {
345 return verifyAccessChain(*this, getIndices());
346}
347
348//===----------------------------------------------------------------------===//
349// spirv.InBoundsAccessChainOp
350//===----------------------------------------------------------------------===//
351
352void InBoundsAccessChainOp::build(OpBuilder &builder, OperationState &state,
353 Value basePtr, ValueRange indices) {
354 Type type = getElementPtrType(basePtr.getType(), indices, state.location);
355 assert(type && "Unable to deduce return type based on basePtr and indices");
356 build(builder, state, type, basePtr, indices);
357}
358
359LogicalResult InBoundsAccessChainOp::verify() {
360 return verifyAccessChain(*this, getIndices());
361}
362
363//===----------------------------------------------------------------------===//
364// spirv.LoadOp
365//===----------------------------------------------------------------------===//
366
367void LoadOp::build(OpBuilder &builder, OperationState &state, Value basePtr,
368 MemoryAccessAttr memoryAccess, IntegerAttr alignment) {
369 auto ptrType = cast<spirv::PointerType>(basePtr.getType());
370 build(builder, state, ptrType.getPointeeType(), basePtr, memoryAccess,
371 alignment);
372}
373
374ParseResult LoadOp::parse(OpAsmParser &parser, OperationState &result) {
375 OpAsmParser::UnresolvedOperand ptrInfo;
376 Type elementType;
377
378 // Untyped pointer form spells out the pointer type instead of the storage
379 // class.
380 OptionalParseResult untypedPtr = parser.parseOptionalOperand(ptrInfo);
381 if (untypedPtr.has_value()) {
382 spirv::UntypedPointerType ptrType;
383 if (failed(*untypedPtr) ||
385 parser.parseOptionalAttrDict(result.attributes) ||
386 parser.parseColonType(ptrType) || parser.parseArrow() ||
387 parser.parseType(elementType) ||
388 parser.resolveOperand(ptrInfo, ptrType, result.operands))
389 return failure();
390 result.addTypes(elementType);
391 return success();
392 }
393
394 // Parse the storage class specification
395 spirv::StorageClass storageClass;
396 if (parseEnumStrAttr(storageClass, parser) || parser.parseOperand(ptrInfo) ||
398 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
399 parser.parseType(elementType)) {
400 return failure();
401 }
402
403 auto ptrType = spirv::PointerType::get(elementType, storageClass);
404 if (parser.resolveOperand(ptrInfo, ptrType, result.operands)) {
405 return failure();
406 }
407
408 result.addTypes(elementType);
409 return success();
410}
411
412void LoadOp::print(OpAsmPrinter &printer) {
413 SmallVector<StringRef, 4> elidedAttrs;
414 auto ptrType = dyn_cast<spirv::PointerType>(getPtr().getType());
415 if (ptrType)
416 printer << " \"" << stringifyStorageClass(ptrType.getStorageClass())
417 << "\"";
418 printer << " " << getPtr();
419
420 printMemoryAccessAttribute(*this, printer, elidedAttrs);
421
422 printer.printOptionalAttrDict(
423 (*this)->getDiscardableAttrDictionary().getValue(), elidedAttrs);
424 printer << " : ";
425 if (!ptrType)
426 printer << getPtr().getType() << " -> ";
427 printer << getType();
428}
429
430LogicalResult LoadOp::verify() {
431 // SPIR-V spec : "Result Type is the type of the loaded object. It must be a
432 // type with fixed size; i.e., it cannot be, nor include, any
433 // OpTypeRuntimeArray types."
434 if (failed(verifyLoadStorePtrAndValTypes(*this, getPtr(), getValue()))) {
435 return failure();
436 }
437 return verifyMemoryAccessAttribute(*this, MemoryAccessKind::Read);
438}
439
440//===----------------------------------------------------------------------===//
441// spirv.StoreOp
442//===----------------------------------------------------------------------===//
443
444ParseResult StoreOp::parse(OpAsmParser &parser, OperationState &result) {
445 SmallVector<OpAsmParser::UnresolvedOperand, 2> operandInfo;
446 auto loc = parser.getCurrentLocation();
447 Type elementType;
448
449 // Untyped pointer form spells out the pointer type instead of the storage
450 // class.
451 OpAsmParser::UnresolvedOperand ptrInfo;
452 OptionalParseResult untypedPtr = parser.parseOptionalOperand(ptrInfo);
453 if (untypedPtr.has_value()) {
454 OpAsmParser::UnresolvedOperand valueInfo;
455 spirv::UntypedPointerType ptrType;
456 if (failed(*untypedPtr) || parser.parseComma() ||
457 parser.parseOperand(valueInfo) ||
459 parser.parseColonType(ptrType) || parser.parseComma() ||
460 parser.parseType(elementType) ||
461 parser.parseOptionalAttrDict(result.attributes) ||
462 parser.resolveOperands({ptrInfo, valueInfo}, {ptrType, elementType},
463 loc, result.operands))
464 return failure();
465 return success();
466 }
467
468 // Parse the storage class specification
469 spirv::StorageClass storageClass;
470 if (parseEnumStrAttr(storageClass, parser) ||
471 parser.parseOperandList(operandInfo, 2) ||
473 parser.parseColon() || parser.parseType(elementType)) {
474 return failure();
475 }
476
477 auto ptrType = spirv::PointerType::get(elementType, storageClass);
478 if (parser.resolveOperands(operandInfo, {ptrType, elementType}, loc,
479 result.operands)) {
480 return failure();
481 }
482 return success();
483}
484
485void StoreOp::print(OpAsmPrinter &printer) {
486 SmallVector<StringRef, 4> elidedAttrs;
487 auto ptrType = dyn_cast<spirv::PointerType>(getPtr().getType());
488 if (ptrType)
489 printer << " \"" << stringifyStorageClass(ptrType.getStorageClass())
490 << "\"";
491 printer << " " << getPtr() << ", " << getValue();
492
493 printMemoryAccessAttribute(*this, printer, elidedAttrs);
494
495 printer << " : ";
496 if (!ptrType)
497 printer << getPtr().getType() << ", ";
498 printer << getValue().getType();
499 printer.printOptionalAttrDict(
500 (*this)->getDiscardableAttrDictionary().getValue(), elidedAttrs);
501}
502
503LogicalResult StoreOp::verify() {
504 // SPIR-V spec : "Pointer is the pointer to store through. Its type must be a
505 // pointer type. If its type is OpTypePointer, the Type operand must be the
506 // same as the type of Object."
507 if (failed(verifyLoadStorePtrAndValTypes(*this, getPtr(), getValue())))
508 return failure();
509 return verifyMemoryAccessAttribute(*this, MemoryAccessKind::Write);
510}
511
512//===----------------------------------------------------------------------===//
513// spirv.CopyMemory
514//===----------------------------------------------------------------------===//
515
516void CopyMemoryOp::print(OpAsmPrinter &printer) {
517 printer << ' ';
518
519 StringRef targetStorageClass = stringifyStorageClass(
520 cast<spirv::PointerType>(getTarget().getType()).getStorageClass());
521 printer << " \"" << targetStorageClass << "\" " << getTarget() << ", ";
522
523 StringRef sourceStorageClass = stringifyStorageClass(
524 cast<spirv::PointerType>(getSource().getType()).getStorageClass());
525 printer << " \"" << sourceStorageClass << "\" " << getSource();
526
527 SmallVector<StringRef, 4> elidedAttrs;
528 printMemoryAccessAttribute(*this, printer, elidedAttrs);
529 printSourceMemoryAccessAttribute(*this, printer, elidedAttrs,
530 getSourceMemoryAccess(),
531 getSourceAlignment());
532
533 printer.printOptionalAttrDict(
534 (*this)->getDiscardableAttrDictionary().getValue(), elidedAttrs);
535
536 Type pointeeType =
537 cast<spirv::PointerType>(getTarget().getType()).getPointeeType();
538 printer << " : " << pointeeType;
539}
540
541ParseResult CopyMemoryOp::parse(OpAsmParser &parser, OperationState &result) {
542 spirv::StorageClass targetStorageClass;
543 OpAsmParser::UnresolvedOperand targetPtrInfo;
544
545 spirv::StorageClass sourceStorageClass;
546 OpAsmParser::UnresolvedOperand sourcePtrInfo;
547
548 Type elementType;
549
550 if (parseEnumStrAttr(targetStorageClass, parser) ||
551 parser.parseOperand(targetPtrInfo) || parser.parseComma() ||
552 parseEnumStrAttr(sourceStorageClass, parser) ||
553 parser.parseOperand(sourcePtrInfo) ||
555 return failure();
556 }
557
558 if (!parser.parseOptionalComma()) {
559 // Parse 2nd memory access attributes.
561 return failure();
562 }
563 }
564
565 if (parser.parseColon() || parser.parseType(elementType))
566 return failure();
567
568 if (parser.parseOptionalAttrDict(result.attributes))
569 return failure();
570
571 auto targetPtrType = spirv::PointerType::get(elementType, targetStorageClass);
572 auto sourcePtrType = spirv::PointerType::get(elementType, sourceStorageClass);
573
574 if (parser.resolveOperand(targetPtrInfo, targetPtrType, result.operands) ||
575 parser.resolveOperand(sourcePtrInfo, sourcePtrType, result.operands)) {
576 return failure();
577 }
578
579 return success();
580}
581
582LogicalResult CopyMemoryOp::verify() {
583 Type targetType =
584 cast<spirv::PointerType>(getTarget().getType()).getPointeeType();
585
586 Type sourceType =
587 cast<spirv::PointerType>(getSource().getType()).getPointeeType();
588
589 if (targetType != sourceType)
590 return emitOpError("both operands must be pointers to the same type");
591
592 // A lone mask applies to both operands. Only the first of two masks is
593 // Target-only.
594 MemoryAccessKind targetKind = getSourceMemoryAccess()
595 ? MemoryAccessKind::Write
596 : MemoryAccessKind::ReadWrite;
597 if (failed(verifyMemoryAccessAttribute(*this, targetKind)))
598 return failure();
599
601 getOperation(), getSourceMemoryAccessAttr(), getSourceAlignmentAttr(),
602 MemoryAccessKind::Read);
603}
604
605//===----------------------------------------------------------------------===//
606// spirv.InBoundsPtrAccessChainOp
607//===----------------------------------------------------------------------===//
608
609void InBoundsPtrAccessChainOp::build(OpBuilder &builder, OperationState &state,
610 Value basePtr, Value element,
612 auto type = getElementPtrType(basePtr.getType(), indices, state.location);
613 assert(type && "Unable to deduce return type based on basePtr and indices");
614 build(builder, state, type, basePtr, element, indices);
615}
616
617LogicalResult InBoundsPtrAccessChainOp::verify() {
618 return verifyAccessChain(*this, getIndices());
619}
620
621//===----------------------------------------------------------------------===//
622// spirv.PtrAccessChainOp
623//===----------------------------------------------------------------------===//
624
625void PtrAccessChainOp::build(OpBuilder &builder, OperationState &state,
626 Value basePtr, Value element, ValueRange indices) {
627 auto type = getElementPtrType(basePtr.getType(), indices, state.location);
628 assert(type && "Unable to deduce return type based on basePtr and indices");
629 build(builder, state, type, basePtr, element, indices);
630}
631
632LogicalResult PtrAccessChainOp::verify() {
633 return verifyAccessChain(*this, getIndices());
634}
635
636//===----------------------------------------------------------------------===//
637// spirv.Variable
638//===----------------------------------------------------------------------===//
639
640ParseResult VariableOp::parse(OpAsmParser &parser, OperationState &result) {
641 // Parse optional initializer
642 std::optional<OpAsmParser::UnresolvedOperand> initInfo;
643 if (succeeded(parser.parseOptionalKeyword("init"))) {
644 initInfo = OpAsmParser::UnresolvedOperand();
645 if (parser.parseLParen() || parser.parseOperand(*initInfo) ||
646 parser.parseRParen())
647 return failure();
648 }
649
650 if (parseVariableDecorations(parser, result)) {
651 return failure();
652 }
653
654 // Parse result pointer type
655 Type type;
656 if (parser.parseColon())
657 return failure();
658 auto loc = parser.getCurrentLocation();
659 if (parser.parseType(type))
660 return failure();
661
662 auto ptrType = dyn_cast<spirv::PointerType>(type);
663 if (!ptrType)
664 return parser.emitError(loc, "expected spirv.ptr type");
665 result.addTypes(ptrType);
666
667 // Resolve the initializer operand
668 if (initInfo) {
669 if (parser.resolveOperand(*initInfo, ptrType.getPointeeType(),
670 result.operands))
671 return failure();
672 }
673
674 auto attr = parser.getBuilder().getAttr<spirv::StorageClassAttr>(
675 ptrType.getStorageClass());
677
678 return success();
679}
680
681void VariableOp::print(OpAsmPrinter &printer) {
682 SmallVector<StringRef, 4> elidedAttrs{
684 // Print optional initializer
685 if (getNumOperands() != 0)
686 printer << " init(" << getInitializer() << ")";
687
688 printVariableDecorations(*this, printer, elidedAttrs);
689 printer << " : " << getType();
690}
691
692LogicalResult VariableOp::verify() {
693 // SPIR-V spec: "Storage Class is the Storage Class of the memory holding the
694 // object. It cannot be Generic. It must be the same as the Storage Class
695 // operand of the Result Type."
696 if (getStorageClass() != spirv::StorageClass::Function) {
697 return emitOpError(
698 "can only be used to model function-level variables. Use "
699 "spirv.GlobalVariable for module-level variables.");
700 }
701
702 auto pointerType = cast<spirv::PointerType>(getPointer().getType());
703 if (getStorageClass() != pointerType.getStorageClass())
704 return emitOpError(
705 "storage class must match result pointer's storage class");
706
707 if (getNumOperands() != 0) {
708 // SPIR-V spec: "Initializer must be an <id> from a constant instruction or
709 // a global (module scope) OpVariable instruction".
710 auto *initOp = getOperand(0).getDefiningOp();
711 if (!initOp || !isa<spirv::ConstantOp, // for normal constant
712 spirv::ReferenceOfOp, // for spec constant
713 spirv::AddressOfOp>(initOp))
714 return emitOpError("initializer must be the result of a "
715 "constant or spirv.GlobalVariable op");
716 }
717
718 auto getDecorationAttr = [op = getOperation()](spirv::Decoration decoration) {
719 return op->getDiscardableAttr(spirv::getDecorationString(decoration));
720 };
721
722 // TODO: generate these strings using ODS.
723 for (auto decoration :
724 {spirv::Decoration::DescriptorSet, spirv::Decoration::Binding,
725 spirv::Decoration::BuiltIn}) {
726 if (auto attr = getDecorationAttr(decoration))
727 return emitOpError("cannot have '")
728 << spirv::getDecorationString(decoration)
729 << "' attribute (only allowed in spirv.GlobalVariable)";
730 }
731
733 getPointeeType())))
734 return failure();
735
736 return success();
737}
738
739//===----------------------------------------------------------------------===//
740// spirv.ArrayLength
741//===----------------------------------------------------------------------===//
742
743LogicalResult ArrayLengthOp::verify() {
744 auto ptrType = cast<spirv::PointerType>(getStructure().getType());
745 auto structType = cast<spirv::StructType>(ptrType.getPointeeType());
746 size_t numElements = structType.getNumElements();
747 if (numElements == 0 ||
748 !isa<spirv::RuntimeArrayType>(structType.getElementType(numElements - 1)))
749 return emitOpError("expected struct whose last member is a runtime array");
750 if (getArrayMember() != numElements - 1)
751 return emitOpError("array member index must be the last struct member (")
752 << (numElements - 1) << "), got " << getArrayMember();
753 return success();
754}
755} // namespace mlir::spirv
static Value getPointer(Location loc, Value value, ConversionPatternRewriter &rewriter)
return success()
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
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.
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 parseRSquare()=0
Parse a ] token.
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.
virtual ParseResult parseArrow()=0
Parse a '->' token.
virtual ParseResult parseLParen()=0
Parse a ( token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseComma()=0
Parse a , token.
virtual ParseResult parseOptionalLSquare()=0
Parse a [ token if present.
virtual ParseResult parseAttribute(Attribute &result, Type type={})=0
Parse an arbitrary attribute of a given type and return it in result.
Attributes are known-constant values of operations.
Definition Attributes.h:25
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:75
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
Definition Builders.h:101
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
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 parseOptionalOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single operand if present.
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 printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
This class helps build Operations.
Definition Builders.h:210
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
Location getLoc()
The source location the operation was defined or derived from.
This provides public APIs that all operations should have.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
bool has_value() const
Returns true if we contain a valid ParseResult value.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
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
static PointerType get(Type pointeeType, StorageClass storageClass)
StorageClass getStorageClass() const
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
static ParseResult parseSourceMemoryAccessAttributes(OpAsmParser &parser, OperationState &state)
Definition MemoryOps.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.
static LogicalResult verifyMemoryAccessAttribute(Operation *op, spirv::MemoryAccessAttr memAccessAttr, Attribute alignmentAttr, MemoryAccessKind kind)
Verifies the memory operands mask memAccessAttr of op and its companion alignment attribute alignment...
static void printSourceMemoryAccessAttribute(MemoryOpTy memoryOp, OpAsmPrinter &printer, SmallVectorImpl< StringRef > &elidedAttrs, std::optional< spirv::MemoryAccess > memoryAccessAtrrValue=std::nullopt, std::optional< uint32_t > alignmentAttrValue=std::nullopt)
ParseResult parseMemoryAccessAttributes(OpAsmParser &parser, OperationState &state)
Parses optional memory access (a.k.a.
Definition MemoryOps.cpp:35
static Type getElementPtrType(Type type, ValueRange indices, Location baseLoc)
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
static LogicalResult verifyLoadStorePtrAndValTypes(LoadStoreOpTy op, Value ptr, Value val)
constexpr StringRef attributeName()
static void printMemoryAccessAttribute(MemoryOpTy memoryOp, OpAsmPrinter &printer, SmallVectorImpl< StringRef > &elidedAttrs, std::optional< spirv::MemoryAccess > memoryAccessAtrrValue=std::nullopt, std::optional< uint32_t > alignmentAttrValue=std::nullopt)
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)
static LogicalResult verifyAccessChain(Op accessChainOp, ValueRange indices)
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.
This represents an operation in an abstracted form, suitable for use with the builder APIs.