1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
|
//===- MemoryOps.cpp - MLIR SPIR-V Memory Ops ----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Defines the memory operations in the SPIR-V dialect.
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/SPIRV/IR/SPIRVOps.h"
#include "SPIRVOpUtils.h"
#include "SPIRVParsingUtils.h"
#include "llvm/ADT/StringExtras.h"
using namespace mlir::spirv::AttrNames;
namespace mlir::spirv {
// TODO Make sure to merge this and the previous function into one template
// parameterized by memory access attribute name and alignment. Doing so now
// results in VS2017 in producing an internal error (at the call site) that's
// not detailed enough to understand what is happening.
static ParseResult parseSourceMemoryAccessAttributes(OpAsmParser &parser,
OperationState &state) {
// Parse an optional list of attributes staring with '['
if (parser.parseOptionalLSquare()) {
// Nothing to do
return success();
}
spirv::MemoryAccess memoryAccessAttr;
if (spirv::parseEnumStrAttr<spirv::MemoryAccessAttr>(
memoryAccessAttr, parser, state, kSourceMemoryAccessAttrName))
return failure();
if (spirv::bitEnumContainsAll(memoryAccessAttr,
spirv::MemoryAccess::Aligned)) {
// Parse integer attribute for alignment.
Attribute alignmentAttr;
Type i32Type = parser.getBuilder().getIntegerType(32);
if (parser.parseComma() ||
parser.parseAttribute(alignmentAttr, i32Type, kSourceAlignmentAttrName,
state.attributes)) {
return failure();
}
}
return parser.parseRSquare();
}
// TODO Make sure to merge this and the previous function into one template
// parameterized by memory access attribute name and alignment. Doing so now
// results in VS2017 in producing an internal error (at the call site) that's
// not detailed enough to understand what is happening.
template <typename MemoryOpTy>
static void printSourceMemoryAccessAttribute(
MemoryOpTy memoryOp, OpAsmPrinter &printer,
SmallVectorImpl<StringRef> &elidedAttrs,
std::optional<spirv::MemoryAccess> memoryAccessAtrrValue = std::nullopt,
std::optional<uint32_t> alignmentAttrValue = std::nullopt) {
printer << ", ";
// Print optional memory access attribute.
if (auto memAccess = (memoryAccessAtrrValue ? memoryAccessAtrrValue
: memoryOp.getMemoryAccess())) {
elidedAttrs.push_back(kSourceMemoryAccessAttrName);
printer << " [\"" << stringifyMemoryAccess(*memAccess) << "\"";
if (spirv::bitEnumContainsAll(*memAccess, spirv::MemoryAccess::Aligned)) {
// Print integer alignment attribute.
if (auto alignment = (alignmentAttrValue ? alignmentAttrValue
: memoryOp.getAlignment())) {
elidedAttrs.push_back(kSourceAlignmentAttrName);
printer << ", " << *alignment;
}
}
printer << "]";
}
elidedAttrs.push_back(spirv::attributeName<spirv::StorageClass>());
}
template <typename MemoryOpTy>
static void printMemoryAccessAttribute(
MemoryOpTy memoryOp, OpAsmPrinter &printer,
SmallVectorImpl<StringRef> &elidedAttrs,
std::optional<spirv::MemoryAccess> memoryAccessAtrrValue = std::nullopt,
std::optional<uint32_t> alignmentAttrValue = std::nullopt) {
// Print optional memory access attribute.
if (auto memAccess = (memoryAccessAtrrValue ? memoryAccessAtrrValue
: memoryOp.getMemoryAccess())) {
elidedAttrs.push_back(kMemoryAccessAttrName);
printer << " [\"" << stringifyMemoryAccess(*memAccess) << "\"";
if (spirv::bitEnumContainsAll(*memAccess, spirv::MemoryAccess::Aligned)) {
// Print integer alignment attribute.
if (auto alignment = (alignmentAttrValue ? alignmentAttrValue
: memoryOp.getAlignment())) {
elidedAttrs.push_back(kAlignmentAttrName);
printer << ", " << *alignment;
}
}
printer << "]";
}
elidedAttrs.push_back(spirv::attributeName<spirv::StorageClass>());
}
template <typename LoadStoreOpTy>
static LogicalResult verifyLoadStorePtrAndValTypes(LoadStoreOpTy op, Value ptr,
Value val) {
// ODS already checks ptr is spirv::PointerType. Just check that the pointee
// type of the pointer and the type of the value are the same
//
// TODO: Check that the value type satisfies restrictions of
// SPIR-V OpLoad/OpStore operations
if (val.getType() !=
llvm::cast<spirv::PointerType>(ptr.getType()).getPointeeType()) {
return op.emitOpError("mismatch in result type and pointer type");
}
return success();
}
template <typename MemoryOpTy>
static LogicalResult verifyMemoryAccessAttribute(MemoryOpTy memoryOp) {
// ODS checks for attributes values. Just need to verify that if the
// memory-access attribute is Aligned, then the alignment attribute must be
// present.
auto *op = memoryOp.getOperation();
auto memAccessAttr = op->getAttr(kMemoryAccessAttrName);
if (!memAccessAttr) {
// Alignment attribute shouldn't be present if memory access attribute is
// not present.
if (op->getAttr(kAlignmentAttrName)) {
return memoryOp.emitOpError(
"invalid alignment specification without aligned memory access "
"specification");
}
return success();
}
auto memAccess = llvm::cast<spirv::MemoryAccessAttr>(memAccessAttr);
if (!memAccess) {
return memoryOp.emitOpError("invalid memory access specifier: ")
<< memAccessAttr;
}
if (spirv::bitEnumContainsAll(memAccess.getValue(),
spirv::MemoryAccess::Aligned)) {
if (!op->getAttr(kAlignmentAttrName)) {
return memoryOp.emitOpError("missing alignment value");
}
} else {
if (op->getAttr(kAlignmentAttrName)) {
return memoryOp.emitOpError(
"invalid alignment specification with non-aligned memory access "
"specification");
}
}
return success();
}
// TODO Make sure to merge this and the previous function into one template
// parameterized by memory access attribute name and alignment. Doing so now
// results in VS2017 in producing an internal error (at the call site) that's
// not detailed enough to understand what is happening.
template <typename MemoryOpTy>
static LogicalResult verifySourceMemoryAccessAttribute(MemoryOpTy memoryOp) {
// ODS checks for attributes values. Just need to verify that if the
// memory-access attribute is Aligned, then the alignment attribute must be
// present.
auto *op = memoryOp.getOperation();
auto memAccessAttr = op->getAttr(kSourceMemoryAccessAttrName);
if (!memAccessAttr) {
// Alignment attribute shouldn't be present if memory access attribute is
// not present.
if (op->getAttr(kSourceAlignmentAttrName)) {
return memoryOp.emitOpError(
"invalid alignment specification without aligned memory access "
"specification");
}
return success();
}
auto memAccess = llvm::cast<spirv::MemoryAccessAttr>(memAccessAttr);
if (!memAccess) {
return memoryOp.emitOpError("invalid memory access specifier: ")
<< memAccess;
}
if (spirv::bitEnumContainsAll(memAccess.getValue(),
spirv::MemoryAccess::Aligned)) {
if (!op->getAttr(kSourceAlignmentAttrName)) {
return memoryOp.emitOpError("missing alignment value");
}
} else {
if (op->getAttr(kSourceAlignmentAttrName)) {
return memoryOp.emitOpError(
"invalid alignment specification with non-aligned memory access "
"specification");
}
}
return success();
}
//===----------------------------------------------------------------------===//
// spirv.AccessChainOp
//===----------------------------------------------------------------------===//
static Type getElementPtrType(Type type, ValueRange indices, Location baseLoc) {
auto ptrType = llvm::dyn_cast<spirv::PointerType>(type);
if (!ptrType) {
emitError(baseLoc, "'spirv.AccessChain' op expected a pointer "
"to composite type, but provided ")
<< type;
return nullptr;
}
auto resultType = ptrType.getPointeeType();
auto resultStorageClass = ptrType.getStorageClass();
int32_t index = 0;
for (auto indexSSA : indices) {
auto cType = llvm::dyn_cast<spirv::CompositeType>(resultType);
if (!cType) {
emitError(
baseLoc,
"'spirv.AccessChain' op cannot extract from non-composite type ")
<< resultType << " with index " << index;
return nullptr;
}
index = 0;
if (llvm::isa<spirv::StructType>(resultType)) {
Operation *op = indexSSA.getDefiningOp();
if (!op) {
emitError(baseLoc, "'spirv.AccessChain' op index must be an "
"integer spirv.Constant to access "
"element of spirv.struct");
return nullptr;
}
// TODO: this should be relaxed to allow
// integer literals of other bitwidths.
if (failed(spirv::extractValueFromConstOp(op, index))) {
emitError(
baseLoc,
"'spirv.AccessChain' index must be an integer spirv.Constant to "
"access element of spirv.struct, but provided ")
<< op->getName();
return nullptr;
}
if (index < 0 || static_cast<uint64_t>(index) >= cType.getNumElements()) {
emitError(baseLoc, "'spirv.AccessChain' op index ")
<< index << " out of bounds for " << resultType;
return nullptr;
}
}
resultType = cType.getElementType(index);
}
return spirv::PointerType::get(resultType, resultStorageClass);
}
void AccessChainOp::build(OpBuilder &builder, OperationState &state,
Value basePtr, ValueRange indices) {
auto type = getElementPtrType(basePtr.getType(), indices, state.location);
assert(type && "Unable to deduce return type based on basePtr and indices");
build(builder, state, type, basePtr, indices);
}
ParseResult AccessChainOp::parse(OpAsmParser &parser, OperationState &result) {
OpAsmParser::UnresolvedOperand ptrInfo;
SmallVector<OpAsmParser::UnresolvedOperand, 4> indicesInfo;
Type type;
auto loc = parser.getCurrentLocation();
SmallVector<Type, 4> indicesTypes;
if (parser.parseOperand(ptrInfo) ||
parser.parseOperandList(indicesInfo, OpAsmParser::Delimiter::Square) ||
parser.parseColonType(type) ||
parser.resolveOperand(ptrInfo, type, result.operands)) {
return failure();
}
// Check that the provided indices list is not empty before parsing their
// type list.
if (indicesInfo.empty()) {
return mlir::emitError(result.location,
"'spirv.AccessChain' op expected at "
"least one index ");
}
if (parser.parseComma() || parser.parseTypeList(indicesTypes))
return failure();
// Check that the indices types list is not empty and that it has a one-to-one
// mapping to the provided indices.
if (indicesTypes.size() != indicesInfo.size()) {
return mlir::emitError(
result.location, "'spirv.AccessChain' op indices types' count must be "
"equal to indices info count");
}
if (parser.resolveOperands(indicesInfo, indicesTypes, loc, result.operands))
return failure();
auto resultType = getElementPtrType(
type, llvm::ArrayRef(result.operands).drop_front(), result.location);
if (!resultType) {
return failure();
}
result.addTypes(resultType);
return success();
}
template <typename Op>
static void printAccessChain(Op op, ValueRange indices, OpAsmPrinter &printer) {
printer << ' ' << op.getBasePtr() << '[' << indices
<< "] : " << op.getBasePtr().getType() << ", " << indices.getTypes();
}
void spirv::AccessChainOp::print(OpAsmPrinter &printer) {
printAccessChain(*this, getIndices(), printer);
}
template <typename Op>
static LogicalResult verifyAccessChain(Op accessChainOp, ValueRange indices) {
auto resultType = getElementPtrType(accessChainOp.getBasePtr().getType(),
indices, accessChainOp.getLoc());
if (!resultType)
return failure();
auto providedResultType =
llvm::dyn_cast<spirv::PointerType>(accessChainOp.getType());
if (!providedResultType)
return accessChainOp.emitOpError(
"result type must be a pointer, but provided")
<< providedResultType;
if (resultType != providedResultType)
return accessChainOp.emitOpError("invalid result type: expected ")
<< resultType << ", but provided " << providedResultType;
return success();
}
LogicalResult AccessChainOp::verify() {
return verifyAccessChain(*this, getIndices());
}
//===----------------------------------------------------------------------===//
// spirv.LoadOp
//===----------------------------------------------------------------------===//
void LoadOp::build(OpBuilder &builder, OperationState &state, Value basePtr,
MemoryAccessAttr memoryAccess, IntegerAttr alignment) {
auto ptrType = llvm::cast<spirv::PointerType>(basePtr.getType());
build(builder, state, ptrType.getPointeeType(), basePtr, memoryAccess,
alignment);
}
ParseResult LoadOp::parse(OpAsmParser &parser, OperationState &result) {
// Parse the storage class specification
spirv::StorageClass storageClass;
OpAsmParser::UnresolvedOperand ptrInfo;
Type elementType;
if (parseEnumStrAttr(storageClass, parser) || parser.parseOperand(ptrInfo) ||
parseMemoryAccessAttributes(parser, result) ||
parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() ||
parser.parseType(elementType)) {
return failure();
}
auto ptrType = spirv::PointerType::get(elementType, storageClass);
if (parser.resolveOperand(ptrInfo, ptrType, result.operands)) {
return failure();
}
result.addTypes(elementType);
return success();
}
void LoadOp::print(OpAsmPrinter &printer) {
SmallVector<StringRef, 4> elidedAttrs;
StringRef sc = stringifyStorageClass(
llvm::cast<spirv::PointerType>(getPtr().getType()).getStorageClass());
printer << " \"" << sc << "\" " << getPtr();
printMemoryAccessAttribute(*this, printer, elidedAttrs);
printer.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs);
printer << " : " << getType();
}
LogicalResult LoadOp::verify() {
// SPIR-V spec : "Result Type is the type of the loaded object. It must be a
// type with fixed size; i.e., it cannot be, nor include, any
// OpTypeRuntimeArray types."
if (failed(verifyLoadStorePtrAndValTypes(*this, getPtr(), getValue()))) {
return failure();
}
return verifyMemoryAccessAttribute(*this);
}
//===----------------------------------------------------------------------===//
// spirv.StoreOp
//===----------------------------------------------------------------------===//
ParseResult StoreOp::parse(OpAsmParser &parser, OperationState &result) {
// Parse the storage class specification
spirv::StorageClass storageClass;
SmallVector<OpAsmParser::UnresolvedOperand, 2> operandInfo;
auto loc = parser.getCurrentLocation();
Type elementType;
if (parseEnumStrAttr(storageClass, parser) ||
parser.parseOperandList(operandInfo, 2) ||
parseMemoryAccessAttributes(parser, result) || parser.parseColon() ||
parser.parseType(elementType)) {
return failure();
}
auto ptrType = spirv::PointerType::get(elementType, storageClass);
if (parser.resolveOperands(operandInfo, {ptrType, elementType}, loc,
result.operands)) {
return failure();
}
return success();
}
void StoreOp::print(OpAsmPrinter &printer) {
SmallVector<StringRef, 4> elidedAttrs;
StringRef sc = stringifyStorageClass(
llvm::cast<spirv::PointerType>(getPtr().getType()).getStorageClass());
printer << " \"" << sc << "\" " << getPtr() << ", " << getValue();
printMemoryAccessAttribute(*this, printer, elidedAttrs);
printer << " : " << getValue().getType();
printer.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs);
}
LogicalResult StoreOp::verify() {
// SPIR-V spec : "Pointer is the pointer to store through. Its type must be an
// OpTypePointer whose Type operand is the same as the type of Object."
if (failed(verifyLoadStorePtrAndValTypes(*this, getPtr(), getValue())))
return failure();
return verifyMemoryAccessAttribute(*this);
}
//===----------------------------------------------------------------------===//
// spirv.CopyMemory
//===----------------------------------------------------------------------===//
void CopyMemoryOp::print(OpAsmPrinter &printer) {
printer << ' ';
StringRef targetStorageClass = stringifyStorageClass(
llvm::cast<spirv::PointerType>(getTarget().getType()).getStorageClass());
printer << " \"" << targetStorageClass << "\" " << getTarget() << ", ";
StringRef sourceStorageClass = stringifyStorageClass(
llvm::cast<spirv::PointerType>(getSource().getType()).getStorageClass());
printer << " \"" << sourceStorageClass << "\" " << getSource();
SmallVector<StringRef, 4> elidedAttrs;
printMemoryAccessAttribute(*this, printer, elidedAttrs);
printSourceMemoryAccessAttribute(*this, printer, elidedAttrs,
getSourceMemoryAccess(),
getSourceAlignment());
printer.printOptionalAttrDict((*this)->getAttrs(), elidedAttrs);
Type pointeeType =
llvm::cast<spirv::PointerType>(getTarget().getType()).getPointeeType();
printer << " : " << pointeeType;
}
ParseResult CopyMemoryOp::parse(OpAsmParser &parser, OperationState &result) {
spirv::StorageClass targetStorageClass;
OpAsmParser::UnresolvedOperand targetPtrInfo;
spirv::StorageClass sourceStorageClass;
OpAsmParser::UnresolvedOperand sourcePtrInfo;
Type elementType;
if (parseEnumStrAttr(targetStorageClass, parser) ||
parser.parseOperand(targetPtrInfo) || parser.parseComma() ||
parseEnumStrAttr(sourceStorageClass, parser) ||
parser.parseOperand(sourcePtrInfo) ||
parseMemoryAccessAttributes(parser, result)) {
return failure();
}
if (!parser.parseOptionalComma()) {
// Parse 2nd memory access attributes.
if (parseSourceMemoryAccessAttributes(parser, result)) {
return failure();
}
}
if (parser.parseColon() || parser.parseType(elementType))
return failure();
if (parser.parseOptionalAttrDict(result.attributes))
return failure();
auto targetPtrType = spirv::PointerType::get(elementType, targetStorageClass);
auto sourcePtrType = spirv::PointerType::get(elementType, sourceStorageClass);
if (parser.resolveOperand(targetPtrInfo, targetPtrType, result.operands) ||
parser.resolveOperand(sourcePtrInfo, sourcePtrType, result.operands)) {
return failure();
}
return success();
}
LogicalResult CopyMemoryOp::verify() {
Type targetType =
llvm::cast<spirv::PointerType>(getTarget().getType()).getPointeeType();
Type sourceType =
llvm::cast<spirv::PointerType>(getSource().getType()).getPointeeType();
if (targetType != sourceType)
return emitOpError("both operands must be pointers to the same type");
if (failed(verifyMemoryAccessAttribute(*this)))
return failure();
// TODO - According to the spec:
//
// If two masks are present, the first applies to Target and cannot include
// MakePointerVisible, and the second applies to Source and cannot include
// MakePointerAvailable.
//
// Add such verification here.
return verifySourceMemoryAccessAttribute(*this);
}
static ParseResult parsePtrAccessChainOpImpl(StringRef opName,
OpAsmParser &parser,
OperationState &state) {
OpAsmParser::UnresolvedOperand ptrInfo;
SmallVector<OpAsmParser::UnresolvedOperand, 4> indicesInfo;
Type type;
auto loc = parser.getCurrentLocation();
SmallVector<Type, 4> indicesTypes;
if (parser.parseOperand(ptrInfo) ||
parser.parseOperandList(indicesInfo, OpAsmParser::Delimiter::Square) ||
parser.parseColonType(type) ||
parser.resolveOperand(ptrInfo, type, state.operands))
return failure();
// Check that the provided indices list is not empty before parsing their
// type list.
if (indicesInfo.empty())
return emitError(state.location) << opName << " expected element";
if (parser.parseComma() || parser.parseTypeList(indicesTypes))
return failure();
// Check that the indices types list is not empty and that it has a one-to-one
// mapping to the provided indices.
if (indicesTypes.size() != indicesInfo.size())
return emitError(state.location)
<< opName
<< " indices types' count must be equal to indices info count";
if (parser.resolveOperands(indicesInfo, indicesTypes, loc, state.operands))
return failure();
auto resultType = getElementPtrType(
type, llvm::ArrayRef(state.operands).drop_front(2), state.location);
if (!resultType)
return failure();
state.addTypes(resultType);
return success();
}
template <typename Op>
static auto concatElemAndIndices(Op op) {
SmallVector<Value> ret(op.getIndices().size() + 1);
ret[0] = op.getElement();
llvm::copy(op.getIndices(), ret.begin() + 1);
return ret;
}
//===----------------------------------------------------------------------===//
// spirv.InBoundsPtrAccessChainOp
//===----------------------------------------------------------------------===//
void InBoundsPtrAccessChainOp::build(OpBuilder &builder, OperationState &state,
Value basePtr, Value element,
ValueRange indices) {
auto type = getElementPtrType(basePtr.getType(), indices, state.location);
assert(type && "Unable to deduce return type based on basePtr and indices");
build(builder, state, type, basePtr, element, indices);
}
ParseResult InBoundsPtrAccessChainOp::parse(OpAsmParser &parser,
OperationState &result) {
return parsePtrAccessChainOpImpl(
spirv::InBoundsPtrAccessChainOp::getOperationName(), parser, result);
}
void InBoundsPtrAccessChainOp::print(OpAsmPrinter &printer) {
printAccessChain(*this, concatElemAndIndices(*this), printer);
}
LogicalResult InBoundsPtrAccessChainOp::verify() {
return verifyAccessChain(*this, getIndices());
}
//===----------------------------------------------------------------------===//
// spirv.PtrAccessChainOp
//===----------------------------------------------------------------------===//
void PtrAccessChainOp::build(OpBuilder &builder, OperationState &state,
Value basePtr, Value element, ValueRange indices) {
auto type = getElementPtrType(basePtr.getType(), indices, state.location);
assert(type && "Unable to deduce return type based on basePtr and indices");
build(builder, state, type, basePtr, element, indices);
}
ParseResult PtrAccessChainOp::parse(OpAsmParser &parser,
OperationState &result) {
return parsePtrAccessChainOpImpl(spirv::PtrAccessChainOp::getOperationName(),
parser, result);
}
void PtrAccessChainOp::print(OpAsmPrinter &printer) {
printAccessChain(*this, concatElemAndIndices(*this), printer);
}
LogicalResult PtrAccessChainOp::verify() {
return verifyAccessChain(*this, getIndices());
}
//===----------------------------------------------------------------------===//
// spirv.Variable
//===----------------------------------------------------------------------===//
ParseResult VariableOp::parse(OpAsmParser &parser, OperationState &result) {
// Parse optional initializer
std::optional<OpAsmParser::UnresolvedOperand> initInfo;
if (succeeded(parser.parseOptionalKeyword("init"))) {
initInfo = OpAsmParser::UnresolvedOperand();
if (parser.parseLParen() || parser.parseOperand(*initInfo) ||
parser.parseRParen())
return failure();
}
if (parseVariableDecorations(parser, result)) {
return failure();
}
// Parse result pointer type
Type type;
if (parser.parseColon())
return failure();
auto loc = parser.getCurrentLocation();
if (parser.parseType(type))
return failure();
auto ptrType = llvm::dyn_cast<spirv::PointerType>(type);
if (!ptrType)
return parser.emitError(loc, "expected spirv.ptr type");
result.addTypes(ptrType);
// Resolve the initializer operand
if (initInfo) {
if (parser.resolveOperand(*initInfo, ptrType.getPointeeType(),
result.operands))
return failure();
}
auto attr = parser.getBuilder().getAttr<spirv::StorageClassAttr>(
ptrType.getStorageClass());
result.addAttribute(spirv::attributeName<spirv::StorageClass>(), attr);
return success();
}
void VariableOp::print(OpAsmPrinter &printer) {
SmallVector<StringRef, 4> elidedAttrs{
spirv::attributeName<spirv::StorageClass>()};
// Print optional initializer
if (getNumOperands() != 0)
printer << " init(" << getInitializer() << ")";
printVariableDecorations(*this, printer, elidedAttrs);
printer << " : " << getType();
}
LogicalResult VariableOp::verify() {
// SPIR-V spec: "Storage Class is the Storage Class of the memory holding the
// object. It cannot be Generic. It must be the same as the Storage Class
// operand of the Result Type."
if (getStorageClass() != spirv::StorageClass::Function) {
return emitOpError(
"can only be used to model function-level variables. Use "
"spirv.GlobalVariable for module-level variables.");
}
auto pointerType = llvm::cast<spirv::PointerType>(getPointer().getType());
if (getStorageClass() != pointerType.getStorageClass())
return emitOpError(
"storage class must match result pointer's storage class");
if (getNumOperands() != 0) {
// SPIR-V spec: "Initializer must be an <id> from a constant instruction or
// a global (module scope) OpVariable instruction".
auto *initOp = getOperand(0).getDefiningOp();
if (!initOp || !isa<spirv::ConstantOp, // for normal constant
spirv::ReferenceOfOp, // for spec constant
spirv::AddressOfOp>(initOp))
return emitOpError("initializer must be the result of a "
"constant or spirv.GlobalVariable op");
}
// TODO: generate these strings using ODS.
auto *op = getOperation();
auto descriptorSetName = llvm::convertToSnakeFromCamelCase(
stringifyDecoration(spirv::Decoration::DescriptorSet));
auto bindingName = llvm::convertToSnakeFromCamelCase(
stringifyDecoration(spirv::Decoration::Binding));
auto builtInName = llvm::convertToSnakeFromCamelCase(
stringifyDecoration(spirv::Decoration::BuiltIn));
for (const auto &attr : {descriptorSetName, bindingName, builtInName}) {
if (op->getAttr(attr))
return emitOpError("cannot have '")
<< attr << "' attribute (only allowed in spirv.GlobalVariable)";
}
return success();
}
} // namespace mlir::spirv
|