1 //===- LLVMDialect.cpp - LLVM IR Ops and Dialect registration -------------===// 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 types and operation details for the LLVM IR dialect in 10 // MLIR, and the LLVM IR dialect. It also registers the dialect. 11 // 12 //===----------------------------------------------------------------------===// 13 #include "mlir/Dialect/LLVMIR/LLVMDialect.h" 14 #include "TypeDetail.h" 15 #include "mlir/Dialect/LLVMIR/LLVMTypes.h" 16 #include "mlir/IR/Builders.h" 17 #include "mlir/IR/BuiltinOps.h" 18 #include "mlir/IR/BuiltinTypes.h" 19 #include "mlir/IR/DialectImplementation.h" 20 #include "mlir/IR/FunctionImplementation.h" 21 #include "mlir/IR/MLIRContext.h" 22 23 #include "llvm/ADT/StringSwitch.h" 24 #include "llvm/ADT/TypeSwitch.h" 25 #include "llvm/AsmParser/Parser.h" 26 #include "llvm/Bitcode/BitcodeReader.h" 27 #include "llvm/Bitcode/BitcodeWriter.h" 28 #include "llvm/IR/Attributes.h" 29 #include "llvm/IR/Function.h" 30 #include "llvm/IR/Type.h" 31 #include "llvm/Support/Mutex.h" 32 #include "llvm/Support/SourceMgr.h" 33 34 #include <iostream> 35 36 using namespace mlir; 37 using namespace mlir::LLVM; 38 39 static constexpr const char kVolatileAttrName[] = "volatile_"; 40 static constexpr const char kNonTemporalAttrName[] = "nontemporal"; 41 42 #include "mlir/Dialect/LLVMIR/LLVMOpsEnums.cpp.inc" 43 #include "mlir/Dialect/LLVMIR/LLVMOpsInterfaces.cpp.inc" 44 #define GET_ATTRDEF_CLASSES 45 #include "mlir/Dialect/LLVMIR/LLVMOpsAttrDefs.cpp.inc" 46 47 static auto processFMFAttr(ArrayRef<NamedAttribute> attrs) { 48 SmallVector<NamedAttribute, 8> filteredAttrs( 49 llvm::make_filter_range(attrs, [&](NamedAttribute attr) { 50 if (attr.first == "fastmathFlags") { 51 auto defAttr = FMFAttr::get(attr.second.getContext(), {}); 52 return defAttr != attr.second; 53 } 54 return true; 55 })); 56 return filteredAttrs; 57 } 58 59 static ParseResult parseLLVMOpAttrs(OpAsmParser &parser, 60 NamedAttrList &result) { 61 return parser.parseOptionalAttrDict(result); 62 } 63 64 static void printLLVMOpAttrs(OpAsmPrinter &printer, Operation *op, 65 DictionaryAttr attrs) { 66 printer.printOptionalAttrDict(processFMFAttr(attrs.getValue())); 67 } 68 69 //===----------------------------------------------------------------------===// 70 // Printing/parsing for LLVM::CmpOp. 71 //===----------------------------------------------------------------------===// 72 static void printICmpOp(OpAsmPrinter &p, ICmpOp &op) { 73 p << op.getOperationName() << " \"" << stringifyICmpPredicate(op.predicate()) 74 << "\" " << op.getOperand(0) << ", " << op.getOperand(1); 75 p.printOptionalAttrDict(op->getAttrs(), {"predicate"}); 76 p << " : " << op.lhs().getType(); 77 } 78 79 static void printFCmpOp(OpAsmPrinter &p, FCmpOp &op) { 80 p << op.getOperationName() << " \"" << stringifyFCmpPredicate(op.predicate()) 81 << "\" " << op.getOperand(0) << ", " << op.getOperand(1); 82 p.printOptionalAttrDict(processFMFAttr(op->getAttrs()), {"predicate"}); 83 p << " : " << op.lhs().getType(); 84 } 85 86 // <operation> ::= `llvm.icmp` string-literal ssa-use `,` ssa-use 87 // attribute-dict? `:` type 88 // <operation> ::= `llvm.fcmp` string-literal ssa-use `,` ssa-use 89 // attribute-dict? `:` type 90 template <typename CmpPredicateType> 91 static ParseResult parseCmpOp(OpAsmParser &parser, OperationState &result) { 92 Builder &builder = parser.getBuilder(); 93 94 StringAttr predicateAttr; 95 OpAsmParser::OperandType lhs, rhs; 96 Type type; 97 llvm::SMLoc predicateLoc, trailingTypeLoc; 98 if (parser.getCurrentLocation(&predicateLoc) || 99 parser.parseAttribute(predicateAttr, "predicate", result.attributes) || 100 parser.parseOperand(lhs) || parser.parseComma() || 101 parser.parseOperand(rhs) || 102 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() || 103 parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(type) || 104 parser.resolveOperand(lhs, type, result.operands) || 105 parser.resolveOperand(rhs, type, result.operands)) 106 return failure(); 107 108 // Replace the string attribute `predicate` with an integer attribute. 109 int64_t predicateValue = 0; 110 if (std::is_same<CmpPredicateType, ICmpPredicate>()) { 111 Optional<ICmpPredicate> predicate = 112 symbolizeICmpPredicate(predicateAttr.getValue()); 113 if (!predicate) 114 return parser.emitError(predicateLoc) 115 << "'" << predicateAttr.getValue() 116 << "' is an incorrect value of the 'predicate' attribute"; 117 predicateValue = static_cast<int64_t>(predicate.getValue()); 118 } else { 119 Optional<FCmpPredicate> predicate = 120 symbolizeFCmpPredicate(predicateAttr.getValue()); 121 if (!predicate) 122 return parser.emitError(predicateLoc) 123 << "'" << predicateAttr.getValue() 124 << "' is an incorrect value of the 'predicate' attribute"; 125 predicateValue = static_cast<int64_t>(predicate.getValue()); 126 } 127 128 result.attributes.set("predicate", 129 parser.getBuilder().getI64IntegerAttr(predicateValue)); 130 131 // The result type is either i1 or a vector type <? x i1> if the inputs are 132 // vectors. 133 Type resultType = IntegerType::get(builder.getContext(), 1); 134 if (!isCompatibleType(type)) 135 return parser.emitError(trailingTypeLoc, 136 "expected LLVM dialect-compatible type"); 137 if (LLVM::isCompatibleVectorType(type)) 138 resultType = LLVM::getFixedVectorType( 139 resultType, LLVM::getVectorNumElements(type).getFixedValue()); 140 assert(!type.isa<LLVM::LLVMScalableVectorType>() && 141 "unhandled scalable vector"); 142 143 result.addTypes({resultType}); 144 return success(); 145 } 146 147 //===----------------------------------------------------------------------===// 148 // Printing/parsing for LLVM::AllocaOp. 149 //===----------------------------------------------------------------------===// 150 151 static void printAllocaOp(OpAsmPrinter &p, AllocaOp &op) { 152 auto elemTy = op.getType().cast<LLVM::LLVMPointerType>().getElementType(); 153 154 auto funcTy = FunctionType::get(op.getContext(), {op.arraySize().getType()}, 155 {op.getType()}); 156 157 p << op.getOperationName() << ' ' << op.arraySize() << " x " << elemTy; 158 if (op.alignment().hasValue() && *op.alignment() != 0) 159 p.printOptionalAttrDict(op->getAttrs()); 160 else 161 p.printOptionalAttrDict(op->getAttrs(), {"alignment"}); 162 p << " : " << funcTy; 163 } 164 165 // <operation> ::= `llvm.alloca` ssa-use `x` type attribute-dict? 166 // `:` type `,` type 167 static ParseResult parseAllocaOp(OpAsmParser &parser, OperationState &result) { 168 OpAsmParser::OperandType arraySize; 169 Type type, elemType; 170 llvm::SMLoc trailingTypeLoc; 171 if (parser.parseOperand(arraySize) || parser.parseKeyword("x") || 172 parser.parseType(elemType) || 173 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() || 174 parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(type)) 175 return failure(); 176 177 Optional<NamedAttribute> alignmentAttr = 178 result.attributes.getNamed("alignment"); 179 if (alignmentAttr.hasValue()) { 180 auto alignmentInt = alignmentAttr.getValue().second.dyn_cast<IntegerAttr>(); 181 if (!alignmentInt) 182 return parser.emitError(parser.getNameLoc(), 183 "expected integer alignment"); 184 if (alignmentInt.getValue().isNullValue()) 185 result.attributes.erase("alignment"); 186 } 187 188 // Extract the result type from the trailing function type. 189 auto funcType = type.dyn_cast<FunctionType>(); 190 if (!funcType || funcType.getNumInputs() != 1 || 191 funcType.getNumResults() != 1) 192 return parser.emitError( 193 trailingTypeLoc, 194 "expected trailing function type with one argument and one result"); 195 196 if (parser.resolveOperand(arraySize, funcType.getInput(0), result.operands)) 197 return failure(); 198 199 result.addTypes({funcType.getResult(0)}); 200 return success(); 201 } 202 203 //===----------------------------------------------------------------------===// 204 // LLVM::BrOp 205 //===----------------------------------------------------------------------===// 206 207 Optional<MutableOperandRange> 208 BrOp::getMutableSuccessorOperands(unsigned index) { 209 assert(index == 0 && "invalid successor index"); 210 return destOperandsMutable(); 211 } 212 213 //===----------------------------------------------------------------------===// 214 // LLVM::CondBrOp 215 //===----------------------------------------------------------------------===// 216 217 Optional<MutableOperandRange> 218 CondBrOp::getMutableSuccessorOperands(unsigned index) { 219 assert(index < getNumSuccessors() && "invalid successor index"); 220 return index == 0 ? trueDestOperandsMutable() : falseDestOperandsMutable(); 221 } 222 223 //===----------------------------------------------------------------------===// 224 // LLVM::SwitchOp 225 //===----------------------------------------------------------------------===// 226 227 void SwitchOp::build(OpBuilder &builder, OperationState &result, Value value, 228 Block *defaultDestination, ValueRange defaultOperands, 229 ArrayRef<int32_t> caseValues, BlockRange caseDestinations, 230 ArrayRef<ValueRange> caseOperands, 231 ArrayRef<int32_t> branchWeights) { 232 SmallVector<Value> flattenedCaseOperands; 233 SmallVector<int32_t> caseOperandOffsets; 234 int32_t offset = 0; 235 for (ValueRange operands : caseOperands) { 236 flattenedCaseOperands.append(operands.begin(), operands.end()); 237 caseOperandOffsets.push_back(offset); 238 offset += operands.size(); 239 } 240 ElementsAttr caseValuesAttr; 241 if (!caseValues.empty()) 242 caseValuesAttr = builder.getI32VectorAttr(caseValues); 243 ElementsAttr caseOperandOffsetsAttr; 244 if (!caseOperandOffsets.empty()) 245 caseOperandOffsetsAttr = builder.getI32VectorAttr(caseOperandOffsets); 246 247 ElementsAttr weightsAttr; 248 if (!branchWeights.empty()) 249 weightsAttr = builder.getI32VectorAttr(llvm::to_vector<4>(branchWeights)); 250 251 build(builder, result, value, defaultOperands, flattenedCaseOperands, 252 caseValuesAttr, caseOperandOffsetsAttr, weightsAttr, defaultDestination, 253 caseDestinations); 254 } 255 256 /// <cases> ::= integer `:` bb-id (`(` ssa-use-and-type-list `)`)? 257 /// ( `,` integer `:` bb-id (`(` ssa-use-and-type-list `)`)? )? 258 static ParseResult 259 parseSwitchOpCases(OpAsmParser &parser, ElementsAttr &caseValues, 260 SmallVectorImpl<Block *> &caseDestinations, 261 SmallVectorImpl<OpAsmParser::OperandType> &caseOperands, 262 SmallVectorImpl<Type> &caseOperandTypes, 263 ElementsAttr &caseOperandOffsets) { 264 SmallVector<int32_t> values; 265 SmallVector<int32_t> offsets; 266 int32_t value, offset = 0; 267 do { 268 OptionalParseResult integerParseResult = parser.parseOptionalInteger(value); 269 if (values.empty() && !integerParseResult.hasValue()) 270 return success(); 271 272 if (!integerParseResult.hasValue() || integerParseResult.getValue()) 273 return failure(); 274 values.push_back(value); 275 276 Block *destination; 277 SmallVector<OpAsmParser::OperandType> operands; 278 if (parser.parseColon() || parser.parseSuccessor(destination)) 279 return failure(); 280 if (!parser.parseOptionalLParen()) { 281 if (parser.parseRegionArgumentList(operands) || 282 parser.parseColonTypeList(caseOperandTypes) || parser.parseRParen()) 283 return failure(); 284 } 285 caseDestinations.push_back(destination); 286 caseOperands.append(operands.begin(), operands.end()); 287 offsets.push_back(offset); 288 offset += operands.size(); 289 } while (!parser.parseOptionalComma()); 290 291 Builder &builder = parser.getBuilder(); 292 caseValues = builder.getI32VectorAttr(values); 293 caseOperandOffsets = builder.getI32VectorAttr(offsets); 294 295 return success(); 296 } 297 298 static void printSwitchOpCases(OpAsmPrinter &p, SwitchOp op, 299 ElementsAttr caseValues, 300 SuccessorRange caseDestinations, 301 OperandRange caseOperands, 302 TypeRange caseOperandTypes, 303 ElementsAttr caseOperandOffsets) { 304 if (!caseValues) 305 return; 306 307 size_t index = 0; 308 llvm::interleave( 309 llvm::zip(caseValues.cast<DenseIntElementsAttr>(), caseDestinations), 310 [&](auto i) { 311 p << " "; 312 p << std::get<0>(i).getLimitedValue(); 313 p << ": "; 314 p.printSuccessorAndUseList(std::get<1>(i), op.getCaseOperands(index++)); 315 }, 316 [&] { 317 p << ','; 318 p.printNewline(); 319 }); 320 p.printNewline(); 321 } 322 323 static LogicalResult verify(SwitchOp op) { 324 if ((!op.case_values() && !op.caseDestinations().empty()) || 325 (op.case_values() && 326 op.case_values()->size() != 327 static_cast<int64_t>(op.caseDestinations().size()))) 328 return op.emitOpError("expects number of case values to match number of " 329 "case destinations"); 330 if (op.branch_weights() && 331 op.branch_weights()->size() != op.getNumSuccessors()) 332 return op.emitError("expects number of branch weights to match number of " 333 "successors: ") 334 << op.branch_weights()->size() << " vs " << op.getNumSuccessors(); 335 return success(); 336 } 337 338 OperandRange SwitchOp::getCaseOperands(unsigned index) { 339 return getCaseOperandsMutable(index); 340 } 341 342 MutableOperandRange SwitchOp::getCaseOperandsMutable(unsigned index) { 343 MutableOperandRange caseOperands = caseOperandsMutable(); 344 if (!case_operand_offsets()) { 345 assert(caseOperands.size() == 0 && 346 "non-empty case operands must have offsets"); 347 return caseOperands; 348 } 349 350 ElementsAttr offsets = case_operand_offsets().getValue(); 351 assert(index < offsets.size() && "invalid case operand offset index"); 352 353 int64_t begin = offsets.getValue(index).cast<IntegerAttr>().getInt(); 354 int64_t end = index + 1 == offsets.size() 355 ? caseOperands.size() 356 : offsets.getValue(index + 1).cast<IntegerAttr>().getInt(); 357 return caseOperandsMutable().slice(begin, end - begin); 358 } 359 360 Optional<MutableOperandRange> 361 SwitchOp::getMutableSuccessorOperands(unsigned index) { 362 assert(index < getNumSuccessors() && "invalid successor index"); 363 return index == 0 ? defaultOperandsMutable() 364 : getCaseOperandsMutable(index - 1); 365 } 366 367 //===----------------------------------------------------------------------===// 368 // Builder, printer and parser for for LLVM::LoadOp. 369 //===----------------------------------------------------------------------===// 370 371 static LogicalResult verifyAccessGroups(Operation *op) { 372 if (Attribute attribute = 373 op->getAttr(LLVMDialect::getAccessGroupsAttrName())) { 374 // The attribute is already verified to be a symbol ref array attribute via 375 // a constraint in the operation definition. 376 for (SymbolRefAttr accessGroupRef : 377 attribute.cast<ArrayAttr>().getAsRange<SymbolRefAttr>()) { 378 StringRef metadataName = accessGroupRef.getRootReference(); 379 auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 380 op->getParentOp(), metadataName); 381 if (!metadataOp) 382 return op->emitOpError() << "expected '" << accessGroupRef 383 << "' to reference a metadata op"; 384 StringRef accessGroupName = accessGroupRef.getLeafReference(); 385 Operation *accessGroupOp = 386 SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName); 387 if (!accessGroupOp) 388 return op->emitOpError() << "expected '" << accessGroupRef 389 << "' to reference an access_group op"; 390 } 391 } 392 return success(); 393 } 394 395 static LogicalResult verify(LoadOp op) { 396 return verifyAccessGroups(op.getOperation()); 397 } 398 399 void LoadOp::build(OpBuilder &builder, OperationState &result, Type t, 400 Value addr, unsigned alignment, bool isVolatile, 401 bool isNonTemporal) { 402 result.addOperands(addr); 403 result.addTypes(t); 404 if (isVolatile) 405 result.addAttribute(kVolatileAttrName, builder.getUnitAttr()); 406 if (isNonTemporal) 407 result.addAttribute(kNonTemporalAttrName, builder.getUnitAttr()); 408 if (alignment != 0) 409 result.addAttribute("alignment", builder.getI64IntegerAttr(alignment)); 410 } 411 412 static void printLoadOp(OpAsmPrinter &p, LoadOp &op) { 413 p << op.getOperationName() << ' '; 414 if (op.volatile_()) 415 p << "volatile "; 416 p << op.addr(); 417 p.printOptionalAttrDict(op->getAttrs(), {kVolatileAttrName}); 418 p << " : " << op.addr().getType(); 419 } 420 421 // Extract the pointee type from the LLVM pointer type wrapped in MLIR. Return 422 // the resulting type wrapped in MLIR, or nullptr on error. 423 static Type getLoadStoreElementType(OpAsmParser &parser, Type type, 424 llvm::SMLoc trailingTypeLoc) { 425 auto llvmTy = type.dyn_cast<LLVM::LLVMPointerType>(); 426 if (!llvmTy) 427 return parser.emitError(trailingTypeLoc, "expected LLVM pointer type"), 428 nullptr; 429 return llvmTy.getElementType(); 430 } 431 432 // <operation> ::= `llvm.load` `volatile` ssa-use attribute-dict? `:` type 433 static ParseResult parseLoadOp(OpAsmParser &parser, OperationState &result) { 434 OpAsmParser::OperandType addr; 435 Type type; 436 llvm::SMLoc trailingTypeLoc; 437 438 if (succeeded(parser.parseOptionalKeyword("volatile"))) 439 result.addAttribute(kVolatileAttrName, parser.getBuilder().getUnitAttr()); 440 441 if (parser.parseOperand(addr) || 442 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() || 443 parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(type) || 444 parser.resolveOperand(addr, type, result.operands)) 445 return failure(); 446 447 Type elemTy = getLoadStoreElementType(parser, type, trailingTypeLoc); 448 449 result.addTypes(elemTy); 450 return success(); 451 } 452 453 //===----------------------------------------------------------------------===// 454 // Builder, printer and parser for LLVM::StoreOp. 455 //===----------------------------------------------------------------------===// 456 457 static LogicalResult verify(StoreOp op) { 458 return verifyAccessGroups(op.getOperation()); 459 } 460 461 void StoreOp::build(OpBuilder &builder, OperationState &result, Value value, 462 Value addr, unsigned alignment, bool isVolatile, 463 bool isNonTemporal) { 464 result.addOperands({value, addr}); 465 result.addTypes({}); 466 if (isVolatile) 467 result.addAttribute(kVolatileAttrName, builder.getUnitAttr()); 468 if (isNonTemporal) 469 result.addAttribute(kNonTemporalAttrName, builder.getUnitAttr()); 470 if (alignment != 0) 471 result.addAttribute("alignment", builder.getI64IntegerAttr(alignment)); 472 } 473 474 static void printStoreOp(OpAsmPrinter &p, StoreOp &op) { 475 p << op.getOperationName() << ' '; 476 if (op.volatile_()) 477 p << "volatile "; 478 p << op.value() << ", " << op.addr(); 479 p.printOptionalAttrDict(op->getAttrs(), {kVolatileAttrName}); 480 p << " : " << op.addr().getType(); 481 } 482 483 // <operation> ::= `llvm.store` `volatile` ssa-use `,` ssa-use 484 // attribute-dict? `:` type 485 static ParseResult parseStoreOp(OpAsmParser &parser, OperationState &result) { 486 OpAsmParser::OperandType addr, value; 487 Type type; 488 llvm::SMLoc trailingTypeLoc; 489 490 if (succeeded(parser.parseOptionalKeyword("volatile"))) 491 result.addAttribute(kVolatileAttrName, parser.getBuilder().getUnitAttr()); 492 493 if (parser.parseOperand(value) || parser.parseComma() || 494 parser.parseOperand(addr) || 495 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() || 496 parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(type)) 497 return failure(); 498 499 Type elemTy = getLoadStoreElementType(parser, type, trailingTypeLoc); 500 if (!elemTy) 501 return failure(); 502 503 if (parser.resolveOperand(value, elemTy, result.operands) || 504 parser.resolveOperand(addr, type, result.operands)) 505 return failure(); 506 507 return success(); 508 } 509 510 ///===---------------------------------------------------------------------===// 511 /// LLVM::InvokeOp 512 ///===---------------------------------------------------------------------===// 513 514 Optional<MutableOperandRange> 515 InvokeOp::getMutableSuccessorOperands(unsigned index) { 516 assert(index < getNumSuccessors() && "invalid successor index"); 517 return index == 0 ? normalDestOperandsMutable() : unwindDestOperandsMutable(); 518 } 519 520 static LogicalResult verify(InvokeOp op) { 521 if (op.getNumResults() > 1) 522 return op.emitOpError("must have 0 or 1 result"); 523 524 Block *unwindDest = op.unwindDest(); 525 if (unwindDest->empty()) 526 return op.emitError( 527 "must have at least one operation in unwind destination"); 528 529 // In unwind destination, first operation must be LandingpadOp 530 if (!isa<LandingpadOp>(unwindDest->front())) 531 return op.emitError("first operation in unwind destination should be a " 532 "llvm.landingpad operation"); 533 534 return success(); 535 } 536 537 static void printInvokeOp(OpAsmPrinter &p, InvokeOp op) { 538 auto callee = op.callee(); 539 bool isDirect = callee.hasValue(); 540 541 p << op.getOperationName() << ' '; 542 543 // Either function name or pointer 544 if (isDirect) 545 p.printSymbolName(callee.getValue()); 546 else 547 p << op.getOperand(0); 548 549 p << '(' << op.getOperands().drop_front(isDirect ? 0 : 1) << ')'; 550 p << " to "; 551 p.printSuccessorAndUseList(op.normalDest(), op.normalDestOperands()); 552 p << " unwind "; 553 p.printSuccessorAndUseList(op.unwindDest(), op.unwindDestOperands()); 554 555 p.printOptionalAttrDict(op->getAttrs(), 556 {InvokeOp::getOperandSegmentSizeAttr(), "callee"}); 557 p << " : "; 558 p.printFunctionalType( 559 llvm::drop_begin(op.getOperandTypes(), isDirect ? 0 : 1), 560 op.getResultTypes()); 561 } 562 563 /// <operation> ::= `llvm.invoke` (function-id | ssa-use) `(` ssa-use-list `)` 564 /// `to` bb-id (`[` ssa-use-and-type-list `]`)? 565 /// `unwind` bb-id (`[` ssa-use-and-type-list `]`)? 566 /// attribute-dict? `:` function-type 567 static ParseResult parseInvokeOp(OpAsmParser &parser, OperationState &result) { 568 SmallVector<OpAsmParser::OperandType, 8> operands; 569 FunctionType funcType; 570 SymbolRefAttr funcAttr; 571 llvm::SMLoc trailingTypeLoc; 572 Block *normalDest, *unwindDest; 573 SmallVector<Value, 4> normalOperands, unwindOperands; 574 Builder &builder = parser.getBuilder(); 575 576 // Parse an operand list that will, in practice, contain 0 or 1 operand. In 577 // case of an indirect call, there will be 1 operand before `(`. In case of a 578 // direct call, there will be no operands and the parser will stop at the 579 // function identifier without complaining. 580 if (parser.parseOperandList(operands)) 581 return failure(); 582 bool isDirect = operands.empty(); 583 584 // Optionally parse a function identifier. 585 if (isDirect && parser.parseAttribute(funcAttr, "callee", result.attributes)) 586 return failure(); 587 588 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::Paren) || 589 parser.parseKeyword("to") || 590 parser.parseSuccessorAndUseList(normalDest, normalOperands) || 591 parser.parseKeyword("unwind") || 592 parser.parseSuccessorAndUseList(unwindDest, unwindOperands) || 593 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() || 594 parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(funcType)) 595 return failure(); 596 597 if (isDirect) { 598 // Make sure types match. 599 if (parser.resolveOperands(operands, funcType.getInputs(), 600 parser.getNameLoc(), result.operands)) 601 return failure(); 602 result.addTypes(funcType.getResults()); 603 } else { 604 // Construct the LLVM IR Dialect function type that the first operand 605 // should match. 606 if (funcType.getNumResults() > 1) 607 return parser.emitError(trailingTypeLoc, 608 "expected function with 0 or 1 result"); 609 610 Type llvmResultType; 611 if (funcType.getNumResults() == 0) { 612 llvmResultType = LLVM::LLVMVoidType::get(builder.getContext()); 613 } else { 614 llvmResultType = funcType.getResult(0); 615 if (!isCompatibleType(llvmResultType)) 616 return parser.emitError(trailingTypeLoc, 617 "expected result to have LLVM type"); 618 } 619 620 SmallVector<Type, 8> argTypes; 621 argTypes.reserve(funcType.getNumInputs()); 622 for (Type ty : funcType.getInputs()) { 623 if (isCompatibleType(ty)) 624 argTypes.push_back(ty); 625 else 626 return parser.emitError(trailingTypeLoc, 627 "expected LLVM types as inputs"); 628 } 629 630 auto llvmFuncType = LLVM::LLVMFunctionType::get(llvmResultType, argTypes); 631 auto wrappedFuncType = LLVM::LLVMPointerType::get(llvmFuncType); 632 633 auto funcArguments = llvm::makeArrayRef(operands).drop_front(); 634 635 // Make sure that the first operand (indirect callee) matches the wrapped 636 // LLVM IR function type, and that the types of the other call operands 637 // match the types of the function arguments. 638 if (parser.resolveOperand(operands[0], wrappedFuncType, result.operands) || 639 parser.resolveOperands(funcArguments, funcType.getInputs(), 640 parser.getNameLoc(), result.operands)) 641 return failure(); 642 643 result.addTypes(llvmResultType); 644 } 645 result.addSuccessors({normalDest, unwindDest}); 646 result.addOperands(normalOperands); 647 result.addOperands(unwindOperands); 648 649 result.addAttribute( 650 InvokeOp::getOperandSegmentSizeAttr(), 651 builder.getI32VectorAttr({static_cast<int32_t>(operands.size()), 652 static_cast<int32_t>(normalOperands.size()), 653 static_cast<int32_t>(unwindOperands.size())})); 654 return success(); 655 } 656 657 ///===----------------------------------------------------------------------===// 658 /// Verifying/Printing/Parsing for LLVM::LandingpadOp. 659 ///===----------------------------------------------------------------------===// 660 661 static LogicalResult verify(LandingpadOp op) { 662 Value value; 663 if (LLVMFuncOp func = op->getParentOfType<LLVMFuncOp>()) { 664 if (!func.personality().hasValue()) 665 return op.emitError( 666 "llvm.landingpad needs to be in a function with a personality"); 667 } 668 669 if (!op.cleanup() && op.getOperands().empty()) 670 return op.emitError("landingpad instruction expects at least one clause or " 671 "cleanup attribute"); 672 673 for (unsigned idx = 0, ie = op.getNumOperands(); idx < ie; idx++) { 674 value = op.getOperand(idx); 675 bool isFilter = value.getType().isa<LLVMArrayType>(); 676 if (isFilter) { 677 // FIXME: Verify filter clauses when arrays are appropriately handled 678 } else { 679 // catch - global addresses only. 680 // Bitcast ops should have global addresses as their args. 681 if (auto bcOp = value.getDefiningOp<BitcastOp>()) { 682 if (auto addrOp = bcOp.arg().getDefiningOp<AddressOfOp>()) 683 continue; 684 return op.emitError("constant clauses expected") 685 .attachNote(bcOp.getLoc()) 686 << "global addresses expected as operand to " 687 "bitcast used in clauses for landingpad"; 688 } 689 // NullOp and AddressOfOp allowed 690 if (value.getDefiningOp<NullOp>()) 691 continue; 692 if (value.getDefiningOp<AddressOfOp>()) 693 continue; 694 return op.emitError("clause #") 695 << idx << " is not a known constant - null, addressof, bitcast"; 696 } 697 } 698 return success(); 699 } 700 701 static void printLandingpadOp(OpAsmPrinter &p, LandingpadOp &op) { 702 p << op.getOperationName() << (op.cleanup() ? " cleanup " : " "); 703 704 // Clauses 705 for (auto value : op.getOperands()) { 706 // Similar to llvm - if clause is an array type then it is filter 707 // clause else catch clause 708 bool isArrayTy = value.getType().isa<LLVMArrayType>(); 709 p << '(' << (isArrayTy ? "filter " : "catch ") << value << " : " 710 << value.getType() << ") "; 711 } 712 713 p.printOptionalAttrDict(op->getAttrs(), {"cleanup"}); 714 715 p << ": " << op.getType(); 716 } 717 718 /// <operation> ::= `llvm.landingpad` `cleanup`? 719 /// ((`catch` | `filter`) operand-type ssa-use)* attribute-dict? 720 static ParseResult parseLandingpadOp(OpAsmParser &parser, 721 OperationState &result) { 722 // Check for cleanup 723 if (succeeded(parser.parseOptionalKeyword("cleanup"))) 724 result.addAttribute("cleanup", parser.getBuilder().getUnitAttr()); 725 726 // Parse clauses with types 727 while (succeeded(parser.parseOptionalLParen()) && 728 (succeeded(parser.parseOptionalKeyword("filter")) || 729 succeeded(parser.parseOptionalKeyword("catch")))) { 730 OpAsmParser::OperandType operand; 731 Type ty; 732 if (parser.parseOperand(operand) || parser.parseColon() || 733 parser.parseType(ty) || 734 parser.resolveOperand(operand, ty, result.operands) || 735 parser.parseRParen()) 736 return failure(); 737 } 738 739 Type type; 740 if (parser.parseColon() || parser.parseType(type)) 741 return failure(); 742 743 result.addTypes(type); 744 return success(); 745 } 746 747 //===----------------------------------------------------------------------===// 748 // Verifying/Printing/parsing for LLVM::CallOp. 749 //===----------------------------------------------------------------------===// 750 751 static LogicalResult verify(CallOp &op) { 752 if (op.getNumResults() > 1) 753 return op.emitOpError("must have 0 or 1 result"); 754 755 // Type for the callee, we'll get it differently depending if it is a direct 756 // or indirect call. 757 Type fnType; 758 759 bool isIndirect = false; 760 761 // If this is an indirect call, the callee attribute is missing. 762 Optional<StringRef> calleeName = op.callee(); 763 if (!calleeName) { 764 isIndirect = true; 765 if (!op.getNumOperands()) 766 return op.emitOpError( 767 "must have either a `callee` attribute or at least an operand"); 768 auto ptrType = op.getOperand(0).getType().dyn_cast<LLVMPointerType>(); 769 if (!ptrType) 770 return op.emitOpError("indirect call expects a pointer as callee: ") 771 << ptrType; 772 fnType = ptrType.getElementType(); 773 } else { 774 Operation *callee = SymbolTable::lookupNearestSymbolFrom(op, *calleeName); 775 if (!callee) 776 return op.emitOpError() 777 << "'" << *calleeName 778 << "' does not reference a symbol in the current scope"; 779 auto fn = dyn_cast<LLVMFuncOp>(callee); 780 if (!fn) 781 return op.emitOpError() << "'" << *calleeName 782 << "' does not reference a valid LLVM function"; 783 784 fnType = fn.getType(); 785 } 786 787 LLVMFunctionType funcType = fnType.dyn_cast<LLVMFunctionType>(); 788 if (!funcType) 789 return op.emitOpError("callee does not have a functional type: ") << fnType; 790 791 // Verify that the operand and result types match the callee. 792 793 if (!funcType.isVarArg() && 794 funcType.getNumParams() != (op.getNumOperands() - isIndirect)) 795 return op.emitOpError() 796 << "incorrect number of operands (" 797 << (op.getNumOperands() - isIndirect) 798 << ") for callee (expecting: " << funcType.getNumParams() << ")"; 799 800 if (funcType.getNumParams() > (op.getNumOperands() - isIndirect)) 801 return op.emitOpError() << "incorrect number of operands (" 802 << (op.getNumOperands() - isIndirect) 803 << ") for varargs callee (expecting at least: " 804 << funcType.getNumParams() << ")"; 805 806 for (unsigned i = 0, e = funcType.getNumParams(); i != e; ++i) 807 if (op.getOperand(i + isIndirect).getType() != funcType.getParamType(i)) 808 return op.emitOpError() << "operand type mismatch for operand " << i 809 << ": " << op.getOperand(i + isIndirect).getType() 810 << " != " << funcType.getParamType(i); 811 812 if (op.getNumResults() && 813 op.getResult(0).getType() != funcType.getReturnType()) 814 return op.emitOpError() 815 << "result type mismatch: " << op.getResult(0).getType() 816 << " != " << funcType.getReturnType(); 817 818 return success(); 819 } 820 821 static void printCallOp(OpAsmPrinter &p, CallOp &op) { 822 auto callee = op.callee(); 823 bool isDirect = callee.hasValue(); 824 825 // Print the direct callee if present as a function attribute, or an indirect 826 // callee (first operand) otherwise. 827 p << op.getOperationName() << ' '; 828 if (isDirect) 829 p.printSymbolName(callee.getValue()); 830 else 831 p << op.getOperand(0); 832 833 auto args = op.getOperands().drop_front(isDirect ? 0 : 1); 834 p << '(' << args << ')'; 835 p.printOptionalAttrDict(processFMFAttr(op->getAttrs()), {"callee"}); 836 837 // Reconstruct the function MLIR function type from operand and result types. 838 p << " : " 839 << FunctionType::get(op.getContext(), args.getTypes(), op.getResultTypes()); 840 } 841 842 // <operation> ::= `llvm.call` (function-id | ssa-use) `(` ssa-use-list `)` 843 // attribute-dict? `:` function-type 844 static ParseResult parseCallOp(OpAsmParser &parser, OperationState &result) { 845 SmallVector<OpAsmParser::OperandType, 8> operands; 846 Type type; 847 SymbolRefAttr funcAttr; 848 llvm::SMLoc trailingTypeLoc; 849 850 // Parse an operand list that will, in practice, contain 0 or 1 operand. In 851 // case of an indirect call, there will be 1 operand before `(`. In case of a 852 // direct call, there will be no operands and the parser will stop at the 853 // function identifier without complaining. 854 if (parser.parseOperandList(operands)) 855 return failure(); 856 bool isDirect = operands.empty(); 857 858 // Optionally parse a function identifier. 859 if (isDirect) 860 if (parser.parseAttribute(funcAttr, "callee", result.attributes)) 861 return failure(); 862 863 if (parser.parseOperandList(operands, OpAsmParser::Delimiter::Paren) || 864 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() || 865 parser.getCurrentLocation(&trailingTypeLoc) || parser.parseType(type)) 866 return failure(); 867 868 auto funcType = type.dyn_cast<FunctionType>(); 869 if (!funcType) 870 return parser.emitError(trailingTypeLoc, "expected function type"); 871 if (isDirect) { 872 // Make sure types match. 873 if (parser.resolveOperands(operands, funcType.getInputs(), 874 parser.getNameLoc(), result.operands)) 875 return failure(); 876 result.addTypes(funcType.getResults()); 877 } else { 878 // Construct the LLVM IR Dialect function type that the first operand 879 // should match. 880 if (funcType.getNumResults() > 1) 881 return parser.emitError(trailingTypeLoc, 882 "expected function with 0 or 1 result"); 883 884 Builder &builder = parser.getBuilder(); 885 Type llvmResultType; 886 if (funcType.getNumResults() == 0) { 887 llvmResultType = LLVM::LLVMVoidType::get(builder.getContext()); 888 } else { 889 llvmResultType = funcType.getResult(0); 890 if (!isCompatibleType(llvmResultType)) 891 return parser.emitError(trailingTypeLoc, 892 "expected result to have LLVM type"); 893 } 894 895 SmallVector<Type, 8> argTypes; 896 argTypes.reserve(funcType.getNumInputs()); 897 for (int i = 0, e = funcType.getNumInputs(); i < e; ++i) { 898 auto argType = funcType.getInput(i); 899 if (!isCompatibleType(argType)) 900 return parser.emitError(trailingTypeLoc, 901 "expected LLVM types as inputs"); 902 argTypes.push_back(argType); 903 } 904 auto llvmFuncType = LLVM::LLVMFunctionType::get(llvmResultType, argTypes); 905 auto wrappedFuncType = LLVM::LLVMPointerType::get(llvmFuncType); 906 907 auto funcArguments = 908 ArrayRef<OpAsmParser::OperandType>(operands).drop_front(); 909 910 // Make sure that the first operand (indirect callee) matches the wrapped 911 // LLVM IR function type, and that the types of the other call operands 912 // match the types of the function arguments. 913 if (parser.resolveOperand(operands[0], wrappedFuncType, result.operands) || 914 parser.resolveOperands(funcArguments, funcType.getInputs(), 915 parser.getNameLoc(), result.operands)) 916 return failure(); 917 918 result.addTypes(llvmResultType); 919 } 920 921 return success(); 922 } 923 924 //===----------------------------------------------------------------------===// 925 // Printing/parsing for LLVM::ExtractElementOp. 926 //===----------------------------------------------------------------------===// 927 // Expects vector to be of wrapped LLVM vector type and position to be of 928 // wrapped LLVM i32 type. 929 void LLVM::ExtractElementOp::build(OpBuilder &b, OperationState &result, 930 Value vector, Value position, 931 ArrayRef<NamedAttribute> attrs) { 932 auto vectorType = vector.getType(); 933 auto llvmType = LLVM::getVectorElementType(vectorType); 934 build(b, result, llvmType, vector, position); 935 result.addAttributes(attrs); 936 } 937 938 static void printExtractElementOp(OpAsmPrinter &p, ExtractElementOp &op) { 939 p << op.getOperationName() << ' ' << op.vector() << "[" << op.position() 940 << " : " << op.position().getType() << "]"; 941 p.printOptionalAttrDict(op->getAttrs()); 942 p << " : " << op.vector().getType(); 943 } 944 945 // <operation> ::= `llvm.extractelement` ssa-use `, ` ssa-use 946 // attribute-dict? `:` type 947 static ParseResult parseExtractElementOp(OpAsmParser &parser, 948 OperationState &result) { 949 llvm::SMLoc loc; 950 OpAsmParser::OperandType vector, position; 951 Type type, positionType; 952 if (parser.getCurrentLocation(&loc) || parser.parseOperand(vector) || 953 parser.parseLSquare() || parser.parseOperand(position) || 954 parser.parseColonType(positionType) || parser.parseRSquare() || 955 parser.parseOptionalAttrDict(result.attributes) || 956 parser.parseColonType(type) || 957 parser.resolveOperand(vector, type, result.operands) || 958 parser.resolveOperand(position, positionType, result.operands)) 959 return failure(); 960 if (!LLVM::isCompatibleVectorType(type)) 961 return parser.emitError( 962 loc, "expected LLVM dialect-compatible vector type for operand #1"); 963 result.addTypes(LLVM::getVectorElementType(type)); 964 return success(); 965 } 966 967 //===----------------------------------------------------------------------===// 968 // Printing/parsing for LLVM::ExtractValueOp. 969 //===----------------------------------------------------------------------===// 970 971 static void printExtractValueOp(OpAsmPrinter &p, ExtractValueOp &op) { 972 p << op.getOperationName() << ' ' << op.container() << op.position(); 973 p.printOptionalAttrDict(op->getAttrs(), {"position"}); 974 p << " : " << op.container().getType(); 975 } 976 977 // Extract the type at `position` in the wrapped LLVM IR aggregate type 978 // `containerType`. Position is an integer array attribute where each value 979 // is a zero-based position of the element in the aggregate type. Return the 980 // resulting type wrapped in MLIR, or nullptr on error. 981 static Type getInsertExtractValueElementType(OpAsmParser &parser, 982 Type containerType, 983 ArrayAttr positionAttr, 984 llvm::SMLoc attributeLoc, 985 llvm::SMLoc typeLoc) { 986 Type llvmType = containerType; 987 if (!isCompatibleType(containerType)) 988 return parser.emitError(typeLoc, "expected LLVM IR Dialect type"), nullptr; 989 990 // Infer the element type from the structure type: iteratively step inside the 991 // type by taking the element type, indexed by the position attribute for 992 // structures. Check the position index before accessing, it is supposed to 993 // be in bounds. 994 for (Attribute subAttr : positionAttr) { 995 auto positionElementAttr = subAttr.dyn_cast<IntegerAttr>(); 996 if (!positionElementAttr) 997 return parser.emitError(attributeLoc, 998 "expected an array of integer literals"), 999 nullptr; 1000 int position = positionElementAttr.getInt(); 1001 if (auto arrayType = llvmType.dyn_cast<LLVMArrayType>()) { 1002 if (position < 0 || 1003 static_cast<unsigned>(position) >= arrayType.getNumElements()) 1004 return parser.emitError(attributeLoc, "position out of bounds"), 1005 nullptr; 1006 llvmType = arrayType.getElementType(); 1007 } else if (auto structType = llvmType.dyn_cast<LLVMStructType>()) { 1008 if (position < 0 || 1009 static_cast<unsigned>(position) >= structType.getBody().size()) 1010 return parser.emitError(attributeLoc, "position out of bounds"), 1011 nullptr; 1012 llvmType = structType.getBody()[position]; 1013 } else { 1014 return parser.emitError(typeLoc, "expected LLVM IR structure/array type"), 1015 nullptr; 1016 } 1017 } 1018 return llvmType; 1019 } 1020 1021 // <operation> ::= `llvm.extractvalue` ssa-use 1022 // `[` integer-literal (`,` integer-literal)* `]` 1023 // attribute-dict? `:` type 1024 static ParseResult parseExtractValueOp(OpAsmParser &parser, 1025 OperationState &result) { 1026 OpAsmParser::OperandType container; 1027 Type containerType; 1028 ArrayAttr positionAttr; 1029 llvm::SMLoc attributeLoc, trailingTypeLoc; 1030 1031 if (parser.parseOperand(container) || 1032 parser.getCurrentLocation(&attributeLoc) || 1033 parser.parseAttribute(positionAttr, "position", result.attributes) || 1034 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() || 1035 parser.getCurrentLocation(&trailingTypeLoc) || 1036 parser.parseType(containerType) || 1037 parser.resolveOperand(container, containerType, result.operands)) 1038 return failure(); 1039 1040 auto elementType = getInsertExtractValueElementType( 1041 parser, containerType, positionAttr, attributeLoc, trailingTypeLoc); 1042 if (!elementType) 1043 return failure(); 1044 1045 result.addTypes(elementType); 1046 return success(); 1047 } 1048 1049 //===----------------------------------------------------------------------===// 1050 // Printing/parsing for LLVM::InsertElementOp. 1051 //===----------------------------------------------------------------------===// 1052 1053 static void printInsertElementOp(OpAsmPrinter &p, InsertElementOp &op) { 1054 p << op.getOperationName() << ' ' << op.value() << ", " << op.vector() << "[" 1055 << op.position() << " : " << op.position().getType() << "]"; 1056 p.printOptionalAttrDict(op->getAttrs()); 1057 p << " : " << op.vector().getType(); 1058 } 1059 1060 // <operation> ::= `llvm.insertelement` ssa-use `,` ssa-use `,` ssa-use 1061 // attribute-dict? `:` type 1062 static ParseResult parseInsertElementOp(OpAsmParser &parser, 1063 OperationState &result) { 1064 llvm::SMLoc loc; 1065 OpAsmParser::OperandType vector, value, position; 1066 Type vectorType, positionType; 1067 if (parser.getCurrentLocation(&loc) || parser.parseOperand(value) || 1068 parser.parseComma() || parser.parseOperand(vector) || 1069 parser.parseLSquare() || parser.parseOperand(position) || 1070 parser.parseColonType(positionType) || parser.parseRSquare() || 1071 parser.parseOptionalAttrDict(result.attributes) || 1072 parser.parseColonType(vectorType)) 1073 return failure(); 1074 1075 if (!LLVM::isCompatibleVectorType(vectorType)) 1076 return parser.emitError( 1077 loc, "expected LLVM dialect-compatible vector type for operand #1"); 1078 Type valueType = LLVM::getVectorElementType(vectorType); 1079 if (!valueType) 1080 return failure(); 1081 1082 if (parser.resolveOperand(vector, vectorType, result.operands) || 1083 parser.resolveOperand(value, valueType, result.operands) || 1084 parser.resolveOperand(position, positionType, result.operands)) 1085 return failure(); 1086 1087 result.addTypes(vectorType); 1088 return success(); 1089 } 1090 1091 //===----------------------------------------------------------------------===// 1092 // Printing/parsing for LLVM::InsertValueOp. 1093 //===----------------------------------------------------------------------===// 1094 1095 static void printInsertValueOp(OpAsmPrinter &p, InsertValueOp &op) { 1096 p << op.getOperationName() << ' ' << op.value() << ", " << op.container() 1097 << op.position(); 1098 p.printOptionalAttrDict(op->getAttrs(), {"position"}); 1099 p << " : " << op.container().getType(); 1100 } 1101 1102 // <operation> ::= `llvm.insertvaluevalue` ssa-use `,` ssa-use 1103 // `[` integer-literal (`,` integer-literal)* `]` 1104 // attribute-dict? `:` type 1105 static ParseResult parseInsertValueOp(OpAsmParser &parser, 1106 OperationState &result) { 1107 OpAsmParser::OperandType container, value; 1108 Type containerType; 1109 ArrayAttr positionAttr; 1110 llvm::SMLoc attributeLoc, trailingTypeLoc; 1111 1112 if (parser.parseOperand(value) || parser.parseComma() || 1113 parser.parseOperand(container) || 1114 parser.getCurrentLocation(&attributeLoc) || 1115 parser.parseAttribute(positionAttr, "position", result.attributes) || 1116 parser.parseOptionalAttrDict(result.attributes) || parser.parseColon() || 1117 parser.getCurrentLocation(&trailingTypeLoc) || 1118 parser.parseType(containerType)) 1119 return failure(); 1120 1121 auto valueType = getInsertExtractValueElementType( 1122 parser, containerType, positionAttr, attributeLoc, trailingTypeLoc); 1123 if (!valueType) 1124 return failure(); 1125 1126 if (parser.resolveOperand(container, containerType, result.operands) || 1127 parser.resolveOperand(value, valueType, result.operands)) 1128 return failure(); 1129 1130 result.addTypes(containerType); 1131 return success(); 1132 } 1133 1134 //===----------------------------------------------------------------------===// 1135 // Printing, parsing and verification for LLVM::ReturnOp. 1136 //===----------------------------------------------------------------------===// 1137 1138 static void printReturnOp(OpAsmPrinter &p, ReturnOp op) { 1139 p << op.getOperationName(); 1140 p.printOptionalAttrDict(op->getAttrs()); 1141 assert(op.getNumOperands() <= 1); 1142 1143 if (op.getNumOperands() == 0) 1144 return; 1145 1146 p << ' ' << op.getOperand(0) << " : " << op.getOperand(0).getType(); 1147 } 1148 1149 // <operation> ::= `llvm.return` ssa-use-list attribute-dict? `:` 1150 // type-list-no-parens 1151 static ParseResult parseReturnOp(OpAsmParser &parser, OperationState &result) { 1152 SmallVector<OpAsmParser::OperandType, 1> operands; 1153 Type type; 1154 1155 if (parser.parseOperandList(operands) || 1156 parser.parseOptionalAttrDict(result.attributes)) 1157 return failure(); 1158 if (operands.empty()) 1159 return success(); 1160 1161 if (parser.parseColonType(type) || 1162 parser.resolveOperand(operands[0], type, result.operands)) 1163 return failure(); 1164 return success(); 1165 } 1166 1167 static LogicalResult verify(ReturnOp op) { 1168 if (op->getNumOperands() > 1) 1169 return op->emitOpError("expected at most 1 operand"); 1170 1171 if (auto parent = op->getParentOfType<LLVMFuncOp>()) { 1172 Type expectedType = parent.getType().getReturnType(); 1173 if (expectedType.isa<LLVMVoidType>()) { 1174 if (op->getNumOperands() == 0) 1175 return success(); 1176 InFlightDiagnostic diag = op->emitOpError("expected no operands"); 1177 diag.attachNote(parent->getLoc()) << "when returning from function"; 1178 return diag; 1179 } 1180 if (op->getNumOperands() == 0) { 1181 if (expectedType.isa<LLVMVoidType>()) 1182 return success(); 1183 InFlightDiagnostic diag = op->emitOpError("expected 1 operand"); 1184 diag.attachNote(parent->getLoc()) << "when returning from function"; 1185 return diag; 1186 } 1187 if (expectedType != op->getOperand(0).getType()) { 1188 InFlightDiagnostic diag = op->emitOpError("mismatching result types"); 1189 diag.attachNote(parent->getLoc()) << "when returning from function"; 1190 return diag; 1191 } 1192 } 1193 return success(); 1194 } 1195 1196 //===----------------------------------------------------------------------===// 1197 // Verifier for LLVM::AddressOfOp. 1198 //===----------------------------------------------------------------------===// 1199 1200 template <typename OpTy> 1201 static OpTy lookupSymbolInModule(Operation *parent, StringRef name) { 1202 Operation *module = parent; 1203 while (module && !satisfiesLLVMModule(module)) 1204 module = module->getParentOp(); 1205 assert(module && "unexpected operation outside of a module"); 1206 return dyn_cast_or_null<OpTy>( 1207 mlir::SymbolTable::lookupSymbolIn(module, name)); 1208 } 1209 1210 GlobalOp AddressOfOp::getGlobal() { 1211 return lookupSymbolInModule<LLVM::GlobalOp>((*this)->getParentOp(), 1212 global_name()); 1213 } 1214 1215 LLVMFuncOp AddressOfOp::getFunction() { 1216 return lookupSymbolInModule<LLVM::LLVMFuncOp>((*this)->getParentOp(), 1217 global_name()); 1218 } 1219 1220 static LogicalResult verify(AddressOfOp op) { 1221 auto global = op.getGlobal(); 1222 auto function = op.getFunction(); 1223 if (!global && !function) 1224 return op.emitOpError( 1225 "must reference a global defined by 'llvm.mlir.global' or 'llvm.func'"); 1226 1227 if (global && 1228 LLVM::LLVMPointerType::get(global.getType(), global.addr_space()) != 1229 op.getResult().getType()) 1230 return op.emitOpError( 1231 "the type must be a pointer to the type of the referenced global"); 1232 1233 if (function && LLVM::LLVMPointerType::get(function.getType()) != 1234 op.getResult().getType()) 1235 return op.emitOpError( 1236 "the type must be a pointer to the type of the referenced function"); 1237 1238 return success(); 1239 } 1240 1241 //===----------------------------------------------------------------------===// 1242 // Builder, printer and verifier for LLVM::GlobalOp. 1243 //===----------------------------------------------------------------------===// 1244 1245 /// Returns the name used for the linkage attribute. This *must* correspond to 1246 /// the name of the attribute in ODS. 1247 static StringRef getLinkageAttrName() { return "linkage"; } 1248 1249 /// Returns the name used for the unnamed_addr attribute. This *must* correspond 1250 /// to the name of the attribute in ODS. 1251 static StringRef getUnnamedAddrAttrName() { return "unnamed_addr"; } 1252 1253 void GlobalOp::build(OpBuilder &builder, OperationState &result, Type type, 1254 bool isConstant, Linkage linkage, StringRef name, 1255 Attribute value, uint64_t alignment, unsigned addrSpace, 1256 ArrayRef<NamedAttribute> attrs) { 1257 result.addAttribute(SymbolTable::getSymbolAttrName(), 1258 builder.getStringAttr(name)); 1259 result.addAttribute("type", TypeAttr::get(type)); 1260 if (isConstant) 1261 result.addAttribute("constant", builder.getUnitAttr()); 1262 if (value) 1263 result.addAttribute("value", value); 1264 1265 // Only add an alignment attribute if the "alignment" input 1266 // is different from 0. The value must also be a power of two, but 1267 // this is tested in GlobalOp::verify, not here. 1268 if (alignment != 0) 1269 result.addAttribute("alignment", builder.getI64IntegerAttr(alignment)); 1270 1271 result.addAttribute(getLinkageAttrName(), 1272 builder.getI64IntegerAttr(static_cast<int64_t>(linkage))); 1273 if (addrSpace != 0) 1274 result.addAttribute("addr_space", builder.getI32IntegerAttr(addrSpace)); 1275 result.attributes.append(attrs.begin(), attrs.end()); 1276 result.addRegion(); 1277 } 1278 1279 static void printGlobalOp(OpAsmPrinter &p, GlobalOp op) { 1280 p << op.getOperationName() << ' ' << stringifyLinkage(op.linkage()) << ' '; 1281 if (op.unnamed_addr()) 1282 p << stringifyUnnamedAddr(*op.unnamed_addr()) << ' '; 1283 if (op.constant()) 1284 p << "constant "; 1285 p.printSymbolName(op.sym_name()); 1286 p << '('; 1287 if (auto value = op.getValueOrNull()) 1288 p.printAttribute(value); 1289 p << ')'; 1290 // Note that the alignment attribute is printed using the 1291 // default syntax here, even though it is an inherent attribute 1292 // (as defined in https://mlir.llvm.org/docs/LangRef/#attributes) 1293 p.printOptionalAttrDict(op->getAttrs(), 1294 {SymbolTable::getSymbolAttrName(), "type", "constant", 1295 "value", getLinkageAttrName(), 1296 getUnnamedAddrAttrName()}); 1297 1298 // Print the trailing type unless it's a string global. 1299 if (op.getValueOrNull().dyn_cast_or_null<StringAttr>()) 1300 return; 1301 p << " : " << op.type(); 1302 1303 Region &initializer = op.getInitializerRegion(); 1304 if (!initializer.empty()) 1305 p.printRegion(initializer, /*printEntryBlockArgs=*/false); 1306 } 1307 1308 //===----------------------------------------------------------------------===// 1309 // Verifier for LLVM::DialectCastOp. 1310 //===----------------------------------------------------------------------===// 1311 1312 /// Checks if `llvmType` is dialect cast-compatible with `index` type. Does not 1313 /// report the error, the user is expected to produce an appropriate message. 1314 // TODO: make the size depend on data layout rather than on the conversion 1315 // pass option, and pull that information here. 1316 static LogicalResult verifyCastWithIndex(Type llvmType) { 1317 return success(llvmType.isa<IntegerType>()); 1318 } 1319 1320 /// Checks if `llvmType` is dialect cast-compatible with built-in `type` and 1321 /// reports errors to the location of `op`. `isElement` indicates whether the 1322 /// verification is performed for types that are element types inside a 1323 /// container; we don't want casts from X to X at the top level, but c1<X> to 1324 /// c2<X> may be fine. 1325 static LogicalResult verifyCast(DialectCastOp op, Type llvmType, Type type, 1326 bool isElement = false) { 1327 // Equal element types are directly compatible. 1328 if (isElement && llvmType == type) 1329 return success(); 1330 1331 // Index is compatible with any integer. 1332 if (type.isIndex()) { 1333 if (succeeded(verifyCastWithIndex(llvmType))) 1334 return success(); 1335 1336 return op.emitOpError("invalid cast between index and non-integer type"); 1337 } 1338 1339 if (type.isa<IntegerType>()) { 1340 auto llvmIntegerType = llvmType.dyn_cast<IntegerType>(); 1341 if (!llvmIntegerType) 1342 return op->emitOpError("invalid cast between integer and non-integer"); 1343 if (llvmIntegerType.getWidth() != type.getIntOrFloatBitWidth()) 1344 return op.emitOpError("invalid cast changing integer width"); 1345 return success(); 1346 } 1347 1348 // Vectors are compatible if they are 1D non-scalable, and their element types 1349 // are compatible. nD vectors are compatible with (n-1)D arrays containing 1D 1350 // vector. 1351 if (auto vectorType = type.dyn_cast<VectorType>()) { 1352 if (vectorType == llvmType && !isElement) 1353 return op.emitOpError("vector types should not be casted"); 1354 1355 if (vectorType.getRank() == 1) { 1356 auto llvmVectorType = llvmType.dyn_cast<VectorType>(); 1357 if (!llvmVectorType || llvmVectorType.getRank() != 1) 1358 return op.emitOpError("invalid cast for vector types"); 1359 1360 return verifyCast(op, llvmVectorType.getElementType(), 1361 vectorType.getElementType(), /*isElement=*/true); 1362 } 1363 1364 auto arrayType = llvmType.dyn_cast<LLVM::LLVMArrayType>(); 1365 if (!arrayType || 1366 arrayType.getNumElements() != vectorType.getShape().front()) 1367 return op.emitOpError("invalid cast for vector, expected array"); 1368 return verifyCast(op, arrayType.getElementType(), 1369 VectorType::get(vectorType.getShape().drop_front(), 1370 vectorType.getElementType()), 1371 /*isElement=*/true); 1372 } 1373 1374 if (auto memrefType = type.dyn_cast<MemRefType>()) { 1375 // Bare pointer convention: statically-shaped memref is compatible with an 1376 // LLVM pointer to the element type. 1377 if (auto ptrType = llvmType.dyn_cast<LLVMPointerType>()) { 1378 if (!memrefType.hasStaticShape()) 1379 return op->emitOpError( 1380 "unexpected bare pointer for dynamically shaped memref"); 1381 if (memrefType.getMemorySpaceAsInt() != ptrType.getAddressSpace()) 1382 return op->emitError("invalid conversion between memref and pointer in " 1383 "different memory spaces"); 1384 1385 return verifyCast(op, ptrType.getElementType(), 1386 memrefType.getElementType(), /*isElement=*/true); 1387 } 1388 1389 // Otherwise, memrefs are convertible to a descriptor, which is a structure 1390 // type. 1391 auto structType = llvmType.dyn_cast<LLVMStructType>(); 1392 if (!structType) 1393 return op->emitOpError("invalid cast between a memref and a type other " 1394 "than pointer or memref descriptor"); 1395 1396 unsigned expectedNumElements = memrefType.getRank() == 0 ? 3 : 5; 1397 if (structType.getBody().size() != expectedNumElements) { 1398 return op->emitOpError() << "expected memref descriptor with " 1399 << expectedNumElements << " elements"; 1400 } 1401 1402 // The first two elements are pointers to the element type. 1403 auto allocatedPtr = structType.getBody()[0].dyn_cast<LLVMPointerType>(); 1404 if (!allocatedPtr || 1405 allocatedPtr.getAddressSpace() != memrefType.getMemorySpaceAsInt()) 1406 return op->emitOpError("expected first element of a memref descriptor to " 1407 "be a pointer in the address space of the memref"); 1408 if (failed(verifyCast(op, allocatedPtr.getElementType(), 1409 memrefType.getElementType(), /*isElement=*/true))) 1410 return failure(); 1411 1412 auto alignedPtr = structType.getBody()[1].dyn_cast<LLVMPointerType>(); 1413 if (!alignedPtr || 1414 alignedPtr.getAddressSpace() != memrefType.getMemorySpaceAsInt()) 1415 return op->emitOpError( 1416 "expected second element of a memref descriptor to " 1417 "be a pointer in the address space of the memref"); 1418 if (failed(verifyCast(op, alignedPtr.getElementType(), 1419 memrefType.getElementType(), /*isElement=*/true))) 1420 return failure(); 1421 1422 // The second element (offset) is an equivalent of index. 1423 if (failed(verifyCastWithIndex(structType.getBody()[2]))) 1424 return op->emitOpError("expected third element of a memref descriptor to " 1425 "be index-compatible integers"); 1426 1427 // 0D memrefs don't have sizes/strides. 1428 if (memrefType.getRank() == 0) 1429 return success(); 1430 1431 // Sizes and strides are rank-sized arrays of `index` equivalents. 1432 auto sizes = structType.getBody()[3].dyn_cast<LLVMArrayType>(); 1433 if (!sizes || failed(verifyCastWithIndex(sizes.getElementType())) || 1434 sizes.getNumElements() != memrefType.getRank()) 1435 return op->emitOpError( 1436 "expected fourth element of a memref descriptor " 1437 "to be an array of <rank> index-compatible integers"); 1438 1439 auto strides = structType.getBody()[4].dyn_cast<LLVMArrayType>(); 1440 if (!strides || failed(verifyCastWithIndex(strides.getElementType())) || 1441 strides.getNumElements() != memrefType.getRank()) 1442 return op->emitOpError( 1443 "expected fifth element of a memref descriptor " 1444 "to be an array of <rank> index-compatible integers"); 1445 1446 return success(); 1447 } 1448 1449 // Unranked memrefs are compatible with their descriptors. 1450 if (auto unrankedMemrefType = type.dyn_cast<UnrankedMemRefType>()) { 1451 auto structType = llvmType.dyn_cast<LLVMStructType>(); 1452 if (!structType || structType.getBody().size() != 2) 1453 return op->emitOpError( 1454 "expected descriptor to be a struct with two elements"); 1455 1456 if (failed(verifyCastWithIndex(structType.getBody()[0]))) 1457 return op->emitOpError("expected first element of a memref descriptor to " 1458 "be an index-compatible integer"); 1459 1460 auto ptrType = structType.getBody()[1].dyn_cast<LLVMPointerType>(); 1461 auto ptrElementType = 1462 ptrType ? ptrType.getElementType().dyn_cast<IntegerType>() : nullptr; 1463 if (!ptrElementType || ptrElementType.getWidth() != 8) 1464 return op->emitOpError("expected second element of a memref descriptor " 1465 "to be an !llvm.ptr<i8>"); 1466 1467 return success(); 1468 } 1469 1470 // Complex types are compatible with the two-element structs. 1471 if (auto complexType = type.dyn_cast<ComplexType>()) { 1472 auto structType = llvmType.dyn_cast<LLVMStructType>(); 1473 if (!structType || structType.getBody().size() != 2 || 1474 structType.getBody()[0] != structType.getBody()[1] || 1475 structType.getBody()[0] != complexType.getElementType()) 1476 return op->emitOpError("expected 'complex' to map to two-element struct " 1477 "with identical element types"); 1478 return success(); 1479 } 1480 1481 // Everything else is not supported. 1482 return op->emitError("unsupported cast"); 1483 } 1484 1485 static LogicalResult verify(DialectCastOp op) { 1486 if (isCompatibleType(op.getType())) 1487 return verifyCast(op, op.getType(), op.in().getType()); 1488 1489 if (!isCompatibleType(op.in().getType())) 1490 return op->emitOpError("expected one LLVM type and one built-in type"); 1491 1492 return verifyCast(op, op.in().getType(), op.getType()); 1493 } 1494 1495 // Parses one of the keywords provided in the list `keywords` and returns the 1496 // position of the parsed keyword in the list. If none of the keywords from the 1497 // list is parsed, returns -1. 1498 static int parseOptionalKeywordAlternative(OpAsmParser &parser, 1499 ArrayRef<StringRef> keywords) { 1500 for (auto en : llvm::enumerate(keywords)) { 1501 if (succeeded(parser.parseOptionalKeyword(en.value()))) 1502 return en.index(); 1503 } 1504 return -1; 1505 } 1506 1507 namespace { 1508 template <typename Ty> 1509 struct EnumTraits {}; 1510 1511 #define REGISTER_ENUM_TYPE(Ty) \ 1512 template <> \ 1513 struct EnumTraits<Ty> { \ 1514 static StringRef stringify(Ty value) { return stringify##Ty(value); } \ 1515 static unsigned getMaxEnumVal() { return getMaxEnumValFor##Ty(); } \ 1516 } 1517 1518 REGISTER_ENUM_TYPE(Linkage); 1519 REGISTER_ENUM_TYPE(UnnamedAddr); 1520 } // end namespace 1521 1522 template <typename EnumTy> 1523 static ParseResult parseOptionalLLVMKeyword(OpAsmParser &parser, 1524 OperationState &result, 1525 StringRef name) { 1526 SmallVector<StringRef, 10> names; 1527 for (unsigned i = 0, e = getMaxEnumValForLinkage(); i <= e; ++i) 1528 names.push_back(EnumTraits<EnumTy>::stringify(static_cast<EnumTy>(i))); 1529 1530 int index = parseOptionalKeywordAlternative(parser, names); 1531 if (index == -1) 1532 return failure(); 1533 result.addAttribute(name, parser.getBuilder().getI64IntegerAttr(index)); 1534 return success(); 1535 } 1536 1537 // operation ::= `llvm.mlir.global` linkage? `constant`? `@` identifier 1538 // `(` attribute? `)` align? attribute-list? (`:` type)? region? 1539 // align ::= `align` `=` UINT64 1540 // 1541 // The type can be omitted for string attributes, in which case it will be 1542 // inferred from the value of the string as [strlen(value) x i8]. 1543 static ParseResult parseGlobalOp(OpAsmParser &parser, OperationState &result) { 1544 if (failed(parseOptionalLLVMKeyword<Linkage>(parser, result, 1545 getLinkageAttrName()))) 1546 result.addAttribute(getLinkageAttrName(), 1547 parser.getBuilder().getI64IntegerAttr( 1548 static_cast<int64_t>(LLVM::Linkage::External))); 1549 1550 if (failed(parseOptionalLLVMKeyword<UnnamedAddr>(parser, result, 1551 getUnnamedAddrAttrName()))) 1552 result.addAttribute(getUnnamedAddrAttrName(), 1553 parser.getBuilder().getI64IntegerAttr( 1554 static_cast<int64_t>(LLVM::UnnamedAddr::None))); 1555 1556 if (succeeded(parser.parseOptionalKeyword("constant"))) 1557 result.addAttribute("constant", parser.getBuilder().getUnitAttr()); 1558 1559 StringAttr name; 1560 if (parser.parseSymbolName(name, SymbolTable::getSymbolAttrName(), 1561 result.attributes) || 1562 parser.parseLParen()) 1563 return failure(); 1564 1565 Attribute value; 1566 if (parser.parseOptionalRParen()) { 1567 if (parser.parseAttribute(value, "value", result.attributes) || 1568 parser.parseRParen()) 1569 return failure(); 1570 } 1571 1572 SmallVector<Type, 1> types; 1573 if (parser.parseOptionalAttrDict(result.attributes) || 1574 parser.parseOptionalColonTypeList(types)) 1575 return failure(); 1576 1577 if (types.size() > 1) 1578 return parser.emitError(parser.getNameLoc(), "expected zero or one type"); 1579 1580 Region &initRegion = *result.addRegion(); 1581 if (types.empty()) { 1582 if (auto strAttr = value.dyn_cast_or_null<StringAttr>()) { 1583 MLIRContext *context = parser.getBuilder().getContext(); 1584 auto arrayType = LLVM::LLVMArrayType::get(IntegerType::get(context, 8), 1585 strAttr.getValue().size()); 1586 types.push_back(arrayType); 1587 } else { 1588 return parser.emitError(parser.getNameLoc(), 1589 "type can only be omitted for string globals"); 1590 } 1591 } else { 1592 OptionalParseResult parseResult = 1593 parser.parseOptionalRegion(initRegion, /*arguments=*/{}, 1594 /*argTypes=*/{}); 1595 if (parseResult.hasValue() && failed(*parseResult)) 1596 return failure(); 1597 } 1598 1599 result.addAttribute("type", TypeAttr::get(types[0])); 1600 return success(); 1601 } 1602 1603 static bool isZeroAttribute(Attribute value) { 1604 if (auto intValue = value.dyn_cast<IntegerAttr>()) 1605 return intValue.getValue().isNullValue(); 1606 if (auto fpValue = value.dyn_cast<FloatAttr>()) 1607 return fpValue.getValue().isZero(); 1608 if (auto splatValue = value.dyn_cast<SplatElementsAttr>()) 1609 return isZeroAttribute(splatValue.getSplatValue()); 1610 if (auto elementsValue = value.dyn_cast<ElementsAttr>()) 1611 return llvm::all_of(elementsValue.getValues<Attribute>(), isZeroAttribute); 1612 if (auto arrayValue = value.dyn_cast<ArrayAttr>()) 1613 return llvm::all_of(arrayValue.getValue(), isZeroAttribute); 1614 return false; 1615 } 1616 1617 static LogicalResult verify(GlobalOp op) { 1618 if (!LLVMPointerType::isValidElementType(op.getType())) 1619 return op.emitOpError( 1620 "expects type to be a valid element type for an LLVM pointer"); 1621 if (op->getParentOp() && !satisfiesLLVMModule(op->getParentOp())) 1622 return op.emitOpError("must appear at the module level"); 1623 1624 if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) { 1625 auto type = op.getType().dyn_cast<LLVMArrayType>(); 1626 IntegerType elementType = 1627 type ? type.getElementType().dyn_cast<IntegerType>() : nullptr; 1628 if (!elementType || elementType.getWidth() != 8 || 1629 type.getNumElements() != strAttr.getValue().size()) 1630 return op.emitOpError( 1631 "requires an i8 array type of the length equal to that of the string " 1632 "attribute"); 1633 } 1634 1635 if (Block *b = op.getInitializerBlock()) { 1636 ReturnOp ret = cast<ReturnOp>(b->getTerminator()); 1637 if (ret.operand_type_begin() == ret.operand_type_end()) 1638 return op.emitOpError("initializer region cannot return void"); 1639 if (*ret.operand_type_begin() != op.getType()) 1640 return op.emitOpError("initializer region type ") 1641 << *ret.operand_type_begin() << " does not match global type " 1642 << op.getType(); 1643 1644 if (op.getValueOrNull()) 1645 return op.emitOpError("cannot have both initializer value and region"); 1646 } 1647 1648 if (op.linkage() == Linkage::Common) { 1649 if (Attribute value = op.getValueOrNull()) { 1650 if (!isZeroAttribute(value)) { 1651 return op.emitOpError() 1652 << "expected zero value for '" 1653 << stringifyLinkage(Linkage::Common) << "' linkage"; 1654 } 1655 } 1656 } 1657 1658 if (op.linkage() == Linkage::Appending) { 1659 if (!op.getType().isa<LLVMArrayType>()) { 1660 return op.emitOpError() 1661 << "expected array type for '" 1662 << stringifyLinkage(Linkage::Appending) << "' linkage"; 1663 } 1664 } 1665 1666 Optional<uint64_t> alignAttr = op.alignment(); 1667 if (alignAttr.hasValue()) { 1668 uint64_t value = alignAttr.getValue(); 1669 if (!llvm::isPowerOf2_64(value)) 1670 return op->emitError() << "alignment attribute is not a power of 2"; 1671 } 1672 1673 return success(); 1674 } 1675 1676 //===----------------------------------------------------------------------===// 1677 // Printing/parsing for LLVM::ShuffleVectorOp. 1678 //===----------------------------------------------------------------------===// 1679 // Expects vector to be of wrapped LLVM vector type and position to be of 1680 // wrapped LLVM i32 type. 1681 void LLVM::ShuffleVectorOp::build(OpBuilder &b, OperationState &result, 1682 Value v1, Value v2, ArrayAttr mask, 1683 ArrayRef<NamedAttribute> attrs) { 1684 auto containerType = v1.getType(); 1685 auto vType = LLVM::getFixedVectorType( 1686 LLVM::getVectorElementType(containerType), mask.size()); 1687 build(b, result, vType, v1, v2, mask); 1688 result.addAttributes(attrs); 1689 } 1690 1691 static void printShuffleVectorOp(OpAsmPrinter &p, ShuffleVectorOp &op) { 1692 p << op.getOperationName() << ' ' << op.v1() << ", " << op.v2() << " " 1693 << op.mask(); 1694 p.printOptionalAttrDict(op->getAttrs(), {"mask"}); 1695 p << " : " << op.v1().getType() << ", " << op.v2().getType(); 1696 } 1697 1698 // <operation> ::= `llvm.shufflevector` ssa-use `, ` ssa-use 1699 // `[` integer-literal (`,` integer-literal)* `]` 1700 // attribute-dict? `:` type 1701 static ParseResult parseShuffleVectorOp(OpAsmParser &parser, 1702 OperationState &result) { 1703 llvm::SMLoc loc; 1704 OpAsmParser::OperandType v1, v2; 1705 ArrayAttr maskAttr; 1706 Type typeV1, typeV2; 1707 if (parser.getCurrentLocation(&loc) || parser.parseOperand(v1) || 1708 parser.parseComma() || parser.parseOperand(v2) || 1709 parser.parseAttribute(maskAttr, "mask", result.attributes) || 1710 parser.parseOptionalAttrDict(result.attributes) || 1711 parser.parseColonType(typeV1) || parser.parseComma() || 1712 parser.parseType(typeV2) || 1713 parser.resolveOperand(v1, typeV1, result.operands) || 1714 parser.resolveOperand(v2, typeV2, result.operands)) 1715 return failure(); 1716 if (!LLVM::isCompatibleVectorType(typeV1)) 1717 return parser.emitError( 1718 loc, "expected LLVM IR dialect vector type for operand #1"); 1719 auto vType = LLVM::getFixedVectorType(LLVM::getVectorElementType(typeV1), 1720 maskAttr.size()); 1721 result.addTypes(vType); 1722 return success(); 1723 } 1724 1725 //===----------------------------------------------------------------------===// 1726 // Implementations for LLVM::LLVMFuncOp. 1727 //===----------------------------------------------------------------------===// 1728 1729 // Add the entry block to the function. 1730 Block *LLVMFuncOp::addEntryBlock() { 1731 assert(empty() && "function already has an entry block"); 1732 assert(!isVarArg() && "unimplemented: non-external variadic functions"); 1733 1734 auto *entry = new Block; 1735 push_back(entry); 1736 1737 LLVMFunctionType type = getType(); 1738 for (unsigned i = 0, e = type.getNumParams(); i < e; ++i) 1739 entry->addArgument(type.getParamType(i)); 1740 return entry; 1741 } 1742 1743 void LLVMFuncOp::build(OpBuilder &builder, OperationState &result, 1744 StringRef name, Type type, LLVM::Linkage linkage, 1745 ArrayRef<NamedAttribute> attrs, 1746 ArrayRef<DictionaryAttr> argAttrs) { 1747 result.addRegion(); 1748 result.addAttribute(SymbolTable::getSymbolAttrName(), 1749 builder.getStringAttr(name)); 1750 result.addAttribute("type", TypeAttr::get(type)); 1751 result.addAttribute(getLinkageAttrName(), 1752 builder.getI64IntegerAttr(static_cast<int64_t>(linkage))); 1753 result.attributes.append(attrs.begin(), attrs.end()); 1754 if (argAttrs.empty()) 1755 return; 1756 1757 assert(type.cast<LLVMFunctionType>().getNumParams() == argAttrs.size() && 1758 "expected as many argument attribute lists as arguments"); 1759 function_like_impl::addArgAndResultAttrs(builder, result, argAttrs, 1760 /*resultAttrs=*/llvm::None); 1761 } 1762 1763 // Builds an LLVM function type from the given lists of input and output types. 1764 // Returns a null type if any of the types provided are non-LLVM types, or if 1765 // there is more than one output type. 1766 static Type 1767 buildLLVMFunctionType(OpAsmParser &parser, llvm::SMLoc loc, 1768 ArrayRef<Type> inputs, ArrayRef<Type> outputs, 1769 function_like_impl::VariadicFlag variadicFlag) { 1770 Builder &b = parser.getBuilder(); 1771 if (outputs.size() > 1) { 1772 parser.emitError(loc, "failed to construct function type: expected zero or " 1773 "one function result"); 1774 return {}; 1775 } 1776 1777 // Convert inputs to LLVM types, exit early on error. 1778 SmallVector<Type, 4> llvmInputs; 1779 for (auto t : inputs) { 1780 if (!isCompatibleType(t)) { 1781 parser.emitError(loc, "failed to construct function type: expected LLVM " 1782 "type for function arguments"); 1783 return {}; 1784 } 1785 llvmInputs.push_back(t); 1786 } 1787 1788 // No output is denoted as "void" in LLVM type system. 1789 Type llvmOutput = 1790 outputs.empty() ? LLVMVoidType::get(b.getContext()) : outputs.front(); 1791 if (!isCompatibleType(llvmOutput)) { 1792 parser.emitError(loc, "failed to construct function type: expected LLVM " 1793 "type for function results") 1794 << llvmOutput; 1795 return {}; 1796 } 1797 return LLVMFunctionType::get(llvmOutput, llvmInputs, 1798 variadicFlag.isVariadic()); 1799 } 1800 1801 // Parses an LLVM function. 1802 // 1803 // operation ::= `llvm.func` linkage? function-signature function-attributes? 1804 // function-body 1805 // 1806 static ParseResult parseLLVMFuncOp(OpAsmParser &parser, 1807 OperationState &result) { 1808 // Default to external linkage if no keyword is provided. 1809 if (failed(parseOptionalLLVMKeyword<Linkage>(parser, result, 1810 getLinkageAttrName()))) 1811 result.addAttribute(getLinkageAttrName(), 1812 parser.getBuilder().getI64IntegerAttr( 1813 static_cast<int64_t>(LLVM::Linkage::External))); 1814 1815 StringAttr nameAttr; 1816 SmallVector<OpAsmParser::OperandType, 8> entryArgs; 1817 SmallVector<NamedAttrList, 1> argAttrs; 1818 SmallVector<NamedAttrList, 1> resultAttrs; 1819 SmallVector<Type, 8> argTypes; 1820 SmallVector<Type, 4> resultTypes; 1821 bool isVariadic; 1822 1823 auto signatureLocation = parser.getCurrentLocation(); 1824 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(), 1825 result.attributes) || 1826 function_like_impl::parseFunctionSignature( 1827 parser, /*allowVariadic=*/true, entryArgs, argTypes, argAttrs, 1828 isVariadic, resultTypes, resultAttrs)) 1829 return failure(); 1830 1831 auto type = 1832 buildLLVMFunctionType(parser, signatureLocation, argTypes, resultTypes, 1833 function_like_impl::VariadicFlag(isVariadic)); 1834 if (!type) 1835 return failure(); 1836 result.addAttribute(function_like_impl::getTypeAttrName(), 1837 TypeAttr::get(type)); 1838 1839 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes))) 1840 return failure(); 1841 function_like_impl::addArgAndResultAttrs(parser.getBuilder(), result, 1842 argAttrs, resultAttrs); 1843 1844 auto *body = result.addRegion(); 1845 OptionalParseResult parseResult = parser.parseOptionalRegion( 1846 *body, entryArgs, entryArgs.empty() ? ArrayRef<Type>() : argTypes); 1847 return failure(parseResult.hasValue() && failed(*parseResult)); 1848 } 1849 1850 // Print the LLVMFuncOp. Collects argument and result types and passes them to 1851 // helper functions. Drops "void" result since it cannot be parsed back. Skips 1852 // the external linkage since it is the default value. 1853 static void printLLVMFuncOp(OpAsmPrinter &p, LLVMFuncOp op) { 1854 p << op.getOperationName() << ' '; 1855 if (op.linkage() != LLVM::Linkage::External) 1856 p << stringifyLinkage(op.linkage()) << ' '; 1857 p.printSymbolName(op.getName()); 1858 1859 LLVMFunctionType fnType = op.getType(); 1860 SmallVector<Type, 8> argTypes; 1861 SmallVector<Type, 1> resTypes; 1862 argTypes.reserve(fnType.getNumParams()); 1863 for (unsigned i = 0, e = fnType.getNumParams(); i < e; ++i) 1864 argTypes.push_back(fnType.getParamType(i)); 1865 1866 Type returnType = fnType.getReturnType(); 1867 if (!returnType.isa<LLVMVoidType>()) 1868 resTypes.push_back(returnType); 1869 1870 function_like_impl::printFunctionSignature(p, op, argTypes, op.isVarArg(), 1871 resTypes); 1872 function_like_impl::printFunctionAttributes( 1873 p, op, argTypes.size(), resTypes.size(), {getLinkageAttrName()}); 1874 1875 // Print the body if this is not an external function. 1876 Region &body = op.body(); 1877 if (!body.empty()) 1878 p.printRegion(body, /*printEntryBlockArgs=*/false, 1879 /*printBlockTerminators=*/true); 1880 } 1881 1882 // Hook for OpTrait::FunctionLike, called after verifying that the 'type' 1883 // attribute is present. This can check for preconditions of the 1884 // getNumArguments hook not failing. 1885 LogicalResult LLVMFuncOp::verifyType() { 1886 auto llvmType = getTypeAttr().getValue().dyn_cast_or_null<LLVMFunctionType>(); 1887 if (!llvmType) 1888 return emitOpError("requires '" + getTypeAttrName() + 1889 "' attribute of wrapped LLVM function type"); 1890 1891 return success(); 1892 } 1893 1894 // Hook for OpTrait::FunctionLike, returns the number of function arguments. 1895 // Depends on the type attribute being correct as checked by verifyType 1896 unsigned LLVMFuncOp::getNumFuncArguments() { return getType().getNumParams(); } 1897 1898 // Hook for OpTrait::FunctionLike, returns the number of function results. 1899 // Depends on the type attribute being correct as checked by verifyType 1900 unsigned LLVMFuncOp::getNumFuncResults() { 1901 // We model LLVM functions that return void as having zero results, 1902 // and all others as having one result. 1903 // If we modeled a void return as one result, then it would be possible to 1904 // attach an MLIR result attribute to it, and it isn't clear what semantics we 1905 // would assign to that. 1906 if (getType().getReturnType().isa<LLVMVoidType>()) 1907 return 0; 1908 return 1; 1909 } 1910 1911 // Verifies LLVM- and implementation-specific properties of the LLVM func Op: 1912 // - functions don't have 'common' linkage 1913 // - external functions have 'external' or 'extern_weak' linkage; 1914 // - vararg is (currently) only supported for external functions; 1915 // - entry block arguments are of LLVM types and match the function signature. 1916 static LogicalResult verify(LLVMFuncOp op) { 1917 if (op.linkage() == LLVM::Linkage::Common) 1918 return op.emitOpError() 1919 << "functions cannot have '" 1920 << stringifyLinkage(LLVM::Linkage::Common) << "' linkage"; 1921 1922 if (op.isExternal()) { 1923 if (op.linkage() != LLVM::Linkage::External && 1924 op.linkage() != LLVM::Linkage::ExternWeak) 1925 return op.emitOpError() 1926 << "external functions must have '" 1927 << stringifyLinkage(LLVM::Linkage::External) << "' or '" 1928 << stringifyLinkage(LLVM::Linkage::ExternWeak) << "' linkage"; 1929 return success(); 1930 } 1931 1932 if (op.isVarArg()) 1933 return op.emitOpError("only external functions can be variadic"); 1934 1935 unsigned numArguments = op.getType().getNumParams(); 1936 Block &entryBlock = op.front(); 1937 for (unsigned i = 0; i < numArguments; ++i) { 1938 Type argType = entryBlock.getArgument(i).getType(); 1939 if (!isCompatibleType(argType)) 1940 return op.emitOpError("entry block argument #") 1941 << i << " is not of LLVM type"; 1942 if (op.getType().getParamType(i) != argType) 1943 return op.emitOpError("the type of entry block argument #") 1944 << i << " does not match the function signature"; 1945 } 1946 1947 return success(); 1948 } 1949 1950 //===----------------------------------------------------------------------===// 1951 // Verification for LLVM::ConstantOp. 1952 //===----------------------------------------------------------------------===// 1953 1954 static LogicalResult verify(LLVM::ConstantOp op) { 1955 if (StringAttr sAttr = op.value().dyn_cast<StringAttr>()) { 1956 auto arrayType = op.getType().dyn_cast<LLVMArrayType>(); 1957 if (!arrayType || arrayType.getNumElements() != sAttr.getValue().size() || 1958 !arrayType.getElementType().isInteger(8)) { 1959 return op->emitOpError() 1960 << "expected array type of " << sAttr.getValue().size() 1961 << " i8 elements for the string constant"; 1962 } 1963 return success(); 1964 } 1965 if (auto structType = op.getType().dyn_cast<LLVMStructType>()) { 1966 if (structType.getBody().size() != 2 || 1967 structType.getBody()[0] != structType.getBody()[1]) { 1968 return op.emitError() << "expected struct type with two elements of the " 1969 "same type, the type of a complex constant"; 1970 } 1971 1972 auto arrayAttr = op.value().dyn_cast<ArrayAttr>(); 1973 if (!arrayAttr || arrayAttr.size() != 2 || 1974 arrayAttr[0].getType() != arrayAttr[1].getType()) { 1975 return op.emitOpError() << "expected array attribute with two elements, " 1976 "representing a complex constant"; 1977 } 1978 1979 Type elementType = structType.getBody()[0]; 1980 if (!elementType 1981 .isa<IntegerType, Float16Type, Float32Type, Float64Type>()) { 1982 return op.emitError() 1983 << "expected struct element types to be floating point type or " 1984 "integer type"; 1985 } 1986 return success(); 1987 } 1988 if (!op.value().isa<IntegerAttr, ArrayAttr, FloatAttr, ElementsAttr>()) 1989 return op.emitOpError() 1990 << "only supports integer, float, string or elements attributes"; 1991 return success(); 1992 } 1993 1994 //===----------------------------------------------------------------------===// 1995 // Utility functions for parsing atomic ops 1996 //===----------------------------------------------------------------------===// 1997 1998 // Helper function to parse a keyword into the specified attribute named by 1999 // `attrName`. The keyword must match one of the string values defined by the 2000 // AtomicBinOp enum. The resulting I64 attribute is added to the `result` 2001 // state. 2002 static ParseResult parseAtomicBinOp(OpAsmParser &parser, OperationState &result, 2003 StringRef attrName) { 2004 llvm::SMLoc loc; 2005 StringRef keyword; 2006 if (parser.getCurrentLocation(&loc) || parser.parseKeyword(&keyword)) 2007 return failure(); 2008 2009 // Replace the keyword `keyword` with an integer attribute. 2010 auto kind = symbolizeAtomicBinOp(keyword); 2011 if (!kind) { 2012 return parser.emitError(loc) 2013 << "'" << keyword << "' is an incorrect value of the '" << attrName 2014 << "' attribute"; 2015 } 2016 2017 auto value = static_cast<int64_t>(kind.getValue()); 2018 auto attr = parser.getBuilder().getI64IntegerAttr(value); 2019 result.addAttribute(attrName, attr); 2020 2021 return success(); 2022 } 2023 2024 // Helper function to parse a keyword into the specified attribute named by 2025 // `attrName`. The keyword must match one of the string values defined by the 2026 // AtomicOrdering enum. The resulting I64 attribute is added to the `result` 2027 // state. 2028 static ParseResult parseAtomicOrdering(OpAsmParser &parser, 2029 OperationState &result, 2030 StringRef attrName) { 2031 llvm::SMLoc loc; 2032 StringRef ordering; 2033 if (parser.getCurrentLocation(&loc) || parser.parseKeyword(&ordering)) 2034 return failure(); 2035 2036 // Replace the keyword `ordering` with an integer attribute. 2037 auto kind = symbolizeAtomicOrdering(ordering); 2038 if (!kind) { 2039 return parser.emitError(loc) 2040 << "'" << ordering << "' is an incorrect value of the '" << attrName 2041 << "' attribute"; 2042 } 2043 2044 auto value = static_cast<int64_t>(kind.getValue()); 2045 auto attr = parser.getBuilder().getI64IntegerAttr(value); 2046 result.addAttribute(attrName, attr); 2047 2048 return success(); 2049 } 2050 2051 //===----------------------------------------------------------------------===// 2052 // Printer, parser and verifier for LLVM::AtomicRMWOp. 2053 //===----------------------------------------------------------------------===// 2054 2055 static void printAtomicRMWOp(OpAsmPrinter &p, AtomicRMWOp &op) { 2056 p << op.getOperationName() << ' ' << stringifyAtomicBinOp(op.bin_op()) << ' ' 2057 << op.ptr() << ", " << op.val() << ' ' 2058 << stringifyAtomicOrdering(op.ordering()) << ' '; 2059 p.printOptionalAttrDict(op->getAttrs(), {"bin_op", "ordering"}); 2060 p << " : " << op.res().getType(); 2061 } 2062 2063 // <operation> ::= `llvm.atomicrmw` keyword ssa-use `,` ssa-use keyword 2064 // attribute-dict? `:` type 2065 static ParseResult parseAtomicRMWOp(OpAsmParser &parser, 2066 OperationState &result) { 2067 Type type; 2068 OpAsmParser::OperandType ptr, val; 2069 if (parseAtomicBinOp(parser, result, "bin_op") || parser.parseOperand(ptr) || 2070 parser.parseComma() || parser.parseOperand(val) || 2071 parseAtomicOrdering(parser, result, "ordering") || 2072 parser.parseOptionalAttrDict(result.attributes) || 2073 parser.parseColonType(type) || 2074 parser.resolveOperand(ptr, LLVM::LLVMPointerType::get(type), 2075 result.operands) || 2076 parser.resolveOperand(val, type, result.operands)) 2077 return failure(); 2078 2079 result.addTypes(type); 2080 return success(); 2081 } 2082 2083 static LogicalResult verify(AtomicRMWOp op) { 2084 auto ptrType = op.ptr().getType().cast<LLVM::LLVMPointerType>(); 2085 auto valType = op.val().getType(); 2086 if (valType != ptrType.getElementType()) 2087 return op.emitOpError("expected LLVM IR element type for operand #0 to " 2088 "match type for operand #1"); 2089 auto resType = op.res().getType(); 2090 if (resType != valType) 2091 return op.emitOpError( 2092 "expected LLVM IR result type to match type for operand #1"); 2093 if (op.bin_op() == AtomicBinOp::fadd || op.bin_op() == AtomicBinOp::fsub) { 2094 if (!mlir::LLVM::isCompatibleFloatingPointType(valType)) 2095 return op.emitOpError("expected LLVM IR floating point type"); 2096 } else if (op.bin_op() == AtomicBinOp::xchg) { 2097 auto intType = valType.dyn_cast<IntegerType>(); 2098 unsigned intBitWidth = intType ? intType.getWidth() : 0; 2099 if (intBitWidth != 8 && intBitWidth != 16 && intBitWidth != 32 && 2100 intBitWidth != 64 && !valType.isa<BFloat16Type>() && 2101 !valType.isa<Float16Type>() && !valType.isa<Float32Type>() && 2102 !valType.isa<Float64Type>()) 2103 return op.emitOpError("unexpected LLVM IR type for 'xchg' bin_op"); 2104 } else { 2105 auto intType = valType.dyn_cast<IntegerType>(); 2106 unsigned intBitWidth = intType ? intType.getWidth() : 0; 2107 if (intBitWidth != 8 && intBitWidth != 16 && intBitWidth != 32 && 2108 intBitWidth != 64) 2109 return op.emitOpError("expected LLVM IR integer type"); 2110 } 2111 2112 if (static_cast<unsigned>(op.ordering()) < 2113 static_cast<unsigned>(AtomicOrdering::monotonic)) 2114 return op.emitOpError() 2115 << "expected at least '" 2116 << stringifyAtomicOrdering(AtomicOrdering::monotonic) 2117 << "' ordering"; 2118 2119 return success(); 2120 } 2121 2122 //===----------------------------------------------------------------------===// 2123 // Printer, parser and verifier for LLVM::AtomicCmpXchgOp. 2124 //===----------------------------------------------------------------------===// 2125 2126 static void printAtomicCmpXchgOp(OpAsmPrinter &p, AtomicCmpXchgOp &op) { 2127 p << op.getOperationName() << ' ' << op.ptr() << ", " << op.cmp() << ", " 2128 << op.val() << ' ' << stringifyAtomicOrdering(op.success_ordering()) << ' ' 2129 << stringifyAtomicOrdering(op.failure_ordering()); 2130 p.printOptionalAttrDict(op->getAttrs(), 2131 {"success_ordering", "failure_ordering"}); 2132 p << " : " << op.val().getType(); 2133 } 2134 2135 // <operation> ::= `llvm.cmpxchg` ssa-use `,` ssa-use `,` ssa-use 2136 // keyword keyword attribute-dict? `:` type 2137 static ParseResult parseAtomicCmpXchgOp(OpAsmParser &parser, 2138 OperationState &result) { 2139 auto &builder = parser.getBuilder(); 2140 Type type; 2141 OpAsmParser::OperandType ptr, cmp, val; 2142 if (parser.parseOperand(ptr) || parser.parseComma() || 2143 parser.parseOperand(cmp) || parser.parseComma() || 2144 parser.parseOperand(val) || 2145 parseAtomicOrdering(parser, result, "success_ordering") || 2146 parseAtomicOrdering(parser, result, "failure_ordering") || 2147 parser.parseOptionalAttrDict(result.attributes) || 2148 parser.parseColonType(type) || 2149 parser.resolveOperand(ptr, LLVM::LLVMPointerType::get(type), 2150 result.operands) || 2151 parser.resolveOperand(cmp, type, result.operands) || 2152 parser.resolveOperand(val, type, result.operands)) 2153 return failure(); 2154 2155 auto boolType = IntegerType::get(builder.getContext(), 1); 2156 auto resultType = 2157 LLVMStructType::getLiteral(builder.getContext(), {type, boolType}); 2158 result.addTypes(resultType); 2159 2160 return success(); 2161 } 2162 2163 static LogicalResult verify(AtomicCmpXchgOp op) { 2164 auto ptrType = op.ptr().getType().cast<LLVM::LLVMPointerType>(); 2165 if (!ptrType) 2166 return op.emitOpError("expected LLVM IR pointer type for operand #0"); 2167 auto cmpType = op.cmp().getType(); 2168 auto valType = op.val().getType(); 2169 if (cmpType != ptrType.getElementType() || cmpType != valType) 2170 return op.emitOpError("expected LLVM IR element type for operand #0 to " 2171 "match type for all other operands"); 2172 auto intType = valType.dyn_cast<IntegerType>(); 2173 unsigned intBitWidth = intType ? intType.getWidth() : 0; 2174 if (!valType.isa<LLVMPointerType>() && intBitWidth != 8 && 2175 intBitWidth != 16 && intBitWidth != 32 && intBitWidth != 64 && 2176 !valType.isa<BFloat16Type>() && !valType.isa<Float16Type>() && 2177 !valType.isa<Float32Type>() && !valType.isa<Float64Type>()) 2178 return op.emitOpError("unexpected LLVM IR type"); 2179 if (op.success_ordering() < AtomicOrdering::monotonic || 2180 op.failure_ordering() < AtomicOrdering::monotonic) 2181 return op.emitOpError("ordering must be at least 'monotonic'"); 2182 if (op.failure_ordering() == AtomicOrdering::release || 2183 op.failure_ordering() == AtomicOrdering::acq_rel) 2184 return op.emitOpError("failure ordering cannot be 'release' or 'acq_rel'"); 2185 return success(); 2186 } 2187 2188 //===----------------------------------------------------------------------===// 2189 // Printer, parser and verifier for LLVM::FenceOp. 2190 //===----------------------------------------------------------------------===// 2191 2192 // <operation> ::= `llvm.fence` (`syncscope(`strAttr`)`)? keyword 2193 // attribute-dict? 2194 static ParseResult parseFenceOp(OpAsmParser &parser, OperationState &result) { 2195 StringAttr sScope; 2196 StringRef syncscopeKeyword = "syncscope"; 2197 if (!failed(parser.parseOptionalKeyword(syncscopeKeyword))) { 2198 if (parser.parseLParen() || 2199 parser.parseAttribute(sScope, syncscopeKeyword, result.attributes) || 2200 parser.parseRParen()) 2201 return failure(); 2202 } else { 2203 result.addAttribute(syncscopeKeyword, 2204 parser.getBuilder().getStringAttr("")); 2205 } 2206 if (parseAtomicOrdering(parser, result, "ordering") || 2207 parser.parseOptionalAttrDict(result.attributes)) 2208 return failure(); 2209 return success(); 2210 } 2211 2212 static void printFenceOp(OpAsmPrinter &p, FenceOp &op) { 2213 StringRef syncscopeKeyword = "syncscope"; 2214 p << op.getOperationName() << ' '; 2215 if (!op->getAttr(syncscopeKeyword).cast<StringAttr>().getValue().empty()) 2216 p << "syncscope(" << op->getAttr(syncscopeKeyword) << ") "; 2217 p << stringifyAtomicOrdering(op.ordering()); 2218 } 2219 2220 static LogicalResult verify(FenceOp &op) { 2221 if (op.ordering() == AtomicOrdering::not_atomic || 2222 op.ordering() == AtomicOrdering::unordered || 2223 op.ordering() == AtomicOrdering::monotonic) 2224 return op.emitOpError("can be given only acquire, release, acq_rel, " 2225 "and seq_cst orderings"); 2226 return success(); 2227 } 2228 2229 //===----------------------------------------------------------------------===// 2230 // LLVMDialect initialization, type parsing, and registration. 2231 //===----------------------------------------------------------------------===// 2232 2233 void LLVMDialect::initialize() { 2234 addAttributes<FMFAttr, LoopOptionsAttr>(); 2235 2236 // clang-format off 2237 addTypes<LLVMVoidType, 2238 LLVMPPCFP128Type, 2239 LLVMX86MMXType, 2240 LLVMTokenType, 2241 LLVMLabelType, 2242 LLVMMetadataType, 2243 LLVMFunctionType, 2244 LLVMPointerType, 2245 LLVMFixedVectorType, 2246 LLVMScalableVectorType, 2247 LLVMArrayType, 2248 LLVMStructType>(); 2249 // clang-format on 2250 addOperations< 2251 #define GET_OP_LIST 2252 #include "mlir/Dialect/LLVMIR/LLVMOps.cpp.inc" 2253 >(); 2254 2255 // Support unknown operations because not all LLVM operations are registered. 2256 allowUnknownOperations(); 2257 } 2258 2259 #define GET_OP_CLASSES 2260 #include "mlir/Dialect/LLVMIR/LLVMOps.cpp.inc" 2261 2262 /// Parse a type registered to this dialect. 2263 Type LLVMDialect::parseType(DialectAsmParser &parser) const { 2264 return detail::parseType(parser); 2265 } 2266 2267 /// Print a type registered to this dialect. 2268 void LLVMDialect::printType(Type type, DialectAsmPrinter &os) const { 2269 return detail::printType(type, os); 2270 } 2271 2272 LogicalResult LLVMDialect::verifyDataLayoutString( 2273 StringRef descr, llvm::function_ref<void(const Twine &)> reportError) { 2274 llvm::Expected<llvm::DataLayout> maybeDataLayout = 2275 llvm::DataLayout::parse(descr); 2276 if (maybeDataLayout) 2277 return success(); 2278 2279 std::string message; 2280 llvm::raw_string_ostream messageStream(message); 2281 llvm::logAllUnhandledErrors(maybeDataLayout.takeError(), messageStream); 2282 reportError("invalid data layout descriptor: " + messageStream.str()); 2283 return failure(); 2284 } 2285 2286 /// Verify LLVM dialect attributes. 2287 LogicalResult LLVMDialect::verifyOperationAttribute(Operation *op, 2288 NamedAttribute attr) { 2289 // If the `llvm.loop` attribute is present, enforce the following structure, 2290 // which the module translation can assume. 2291 if (attr.first.strref() == LLVMDialect::getLoopAttrName()) { 2292 auto loopAttr = attr.second.dyn_cast<DictionaryAttr>(); 2293 if (!loopAttr) 2294 return op->emitOpError() << "expected '" << LLVMDialect::getLoopAttrName() 2295 << "' to be a dictionary attribute"; 2296 Optional<NamedAttribute> parallelAccessGroup = 2297 loopAttr.getNamed(LLVMDialect::getParallelAccessAttrName()); 2298 if (parallelAccessGroup.hasValue()) { 2299 auto accessGroups = parallelAccessGroup->second.dyn_cast<ArrayAttr>(); 2300 if (!accessGroups) 2301 return op->emitOpError() 2302 << "expected '" << LLVMDialect::getParallelAccessAttrName() 2303 << "' to be an array attribute"; 2304 for (Attribute attr : accessGroups) { 2305 auto accessGroupRef = attr.dyn_cast<SymbolRefAttr>(); 2306 if (!accessGroupRef) 2307 return op->emitOpError() 2308 << "expected '" << attr << "' to be a symbol reference"; 2309 StringRef metadataName = accessGroupRef.getRootReference(); 2310 auto metadataOp = 2311 SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>( 2312 op->getParentOp(), metadataName); 2313 if (!metadataOp) 2314 return op->emitOpError() 2315 << "expected '" << attr << "' to reference a metadata op"; 2316 StringRef accessGroupName = accessGroupRef.getLeafReference(); 2317 Operation *accessGroupOp = 2318 SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName); 2319 if (!accessGroupOp) 2320 return op->emitOpError() 2321 << "expected '" << attr << "' to reference an access_group op"; 2322 } 2323 } 2324 2325 Optional<NamedAttribute> loopOptions = 2326 loopAttr.getNamed(LLVMDialect::getLoopOptionsAttrName()); 2327 if (loopOptions.hasValue() && !loopOptions->second.isa<LoopOptionsAttr>()) 2328 return op->emitOpError() 2329 << "expected '" << LLVMDialect::getLoopOptionsAttrName() 2330 << "' to be a `loopopts` attribute"; 2331 } 2332 2333 // If the data layout attribute is present, it must use the LLVM data layout 2334 // syntax. Try parsing it and report errors in case of failure. Users of this 2335 // attribute may assume it is well-formed and can pass it to the (asserting) 2336 // llvm::DataLayout constructor. 2337 if (attr.first.strref() != LLVM::LLVMDialect::getDataLayoutAttrName()) 2338 return success(); 2339 if (auto stringAttr = attr.second.dyn_cast<StringAttr>()) 2340 return verifyDataLayoutString( 2341 stringAttr.getValue(), 2342 [op](const Twine &message) { op->emitOpError() << message.str(); }); 2343 2344 return op->emitOpError() << "expected '" 2345 << LLVM::LLVMDialect::getDataLayoutAttrName() 2346 << "' to be a string attribute"; 2347 } 2348 2349 /// Verify LLVMIR function argument attributes. 2350 LogicalResult LLVMDialect::verifyRegionArgAttribute(Operation *op, 2351 unsigned regionIdx, 2352 unsigned argIdx, 2353 NamedAttribute argAttr) { 2354 // Check that llvm.noalias is a unit attribute. 2355 if (argAttr.first == LLVMDialect::getNoAliasAttrName() && 2356 !argAttr.second.isa<UnitAttr>()) 2357 return op->emitError() 2358 << "expected llvm.noalias argument attribute to be a unit attribute"; 2359 // Check that llvm.align is an integer attribute. 2360 if (argAttr.first == LLVMDialect::getAlignAttrName() && 2361 !argAttr.second.isa<IntegerAttr>()) 2362 return op->emitError() 2363 << "llvm.align argument attribute of non integer type"; 2364 return success(); 2365 } 2366 2367 //===----------------------------------------------------------------------===// 2368 // Utility functions. 2369 //===----------------------------------------------------------------------===// 2370 2371 Value mlir::LLVM::createGlobalString(Location loc, OpBuilder &builder, 2372 StringRef name, StringRef value, 2373 LLVM::Linkage linkage) { 2374 assert(builder.getInsertionBlock() && 2375 builder.getInsertionBlock()->getParentOp() && 2376 "expected builder to point to a block constrained in an op"); 2377 auto module = 2378 builder.getInsertionBlock()->getParentOp()->getParentOfType<ModuleOp>(); 2379 assert(module && "builder points to an op outside of a module"); 2380 2381 // Create the global at the entry of the module. 2382 OpBuilder moduleBuilder(module.getBodyRegion(), builder.getListener()); 2383 MLIRContext *ctx = builder.getContext(); 2384 auto type = LLVM::LLVMArrayType::get(IntegerType::get(ctx, 8), value.size()); 2385 auto global = moduleBuilder.create<LLVM::GlobalOp>( 2386 loc, type, /*isConstant=*/true, linkage, name, 2387 builder.getStringAttr(value), /*alignment=*/0); 2388 2389 // Get the pointer to the first character in the global string. 2390 Value globalPtr = builder.create<LLVM::AddressOfOp>(loc, global); 2391 Value cst0 = builder.create<LLVM::ConstantOp>( 2392 loc, IntegerType::get(ctx, 64), 2393 builder.getIntegerAttr(builder.getIndexType(), 0)); 2394 return builder.create<LLVM::GEPOp>( 2395 loc, LLVM::LLVMPointerType::get(IntegerType::get(ctx, 8)), globalPtr, 2396 ValueRange{cst0, cst0}); 2397 } 2398 2399 bool mlir::LLVM::satisfiesLLVMModule(Operation *op) { 2400 return op->hasTrait<OpTrait::SymbolTable>() && 2401 op->hasTrait<OpTrait::IsIsolatedFromAbove>(); 2402 } 2403 2404 static constexpr const FastmathFlags FastmathFlagsList[] = { 2405 // clang-format off 2406 FastmathFlags::nnan, 2407 FastmathFlags::ninf, 2408 FastmathFlags::nsz, 2409 FastmathFlags::arcp, 2410 FastmathFlags::contract, 2411 FastmathFlags::afn, 2412 FastmathFlags::reassoc, 2413 FastmathFlags::fast, 2414 // clang-format on 2415 }; 2416 2417 void FMFAttr::print(DialectAsmPrinter &printer) const { 2418 printer << "fastmath<"; 2419 auto flags = llvm::make_filter_range(FastmathFlagsList, [&](auto flag) { 2420 return bitEnumContains(this->getFlags(), flag); 2421 }); 2422 llvm::interleaveComma(flags, printer, 2423 [&](auto flag) { printer << stringifyEnum(flag); }); 2424 printer << ">"; 2425 } 2426 2427 Attribute FMFAttr::parse(MLIRContext *context, DialectAsmParser &parser, 2428 Type type) { 2429 if (failed(parser.parseLess())) 2430 return {}; 2431 2432 FastmathFlags flags = {}; 2433 if (failed(parser.parseOptionalGreater())) { 2434 do { 2435 StringRef elemName; 2436 if (failed(parser.parseKeyword(&elemName))) 2437 return {}; 2438 2439 auto elem = symbolizeFastmathFlags(elemName); 2440 if (!elem) { 2441 parser.emitError(parser.getNameLoc(), "Unknown fastmath flag: ") 2442 << elemName; 2443 return {}; 2444 } 2445 2446 flags = flags | *elem; 2447 } while (succeeded(parser.parseOptionalComma())); 2448 2449 if (failed(parser.parseGreater())) 2450 return {}; 2451 } 2452 2453 return FMFAttr::get(parser.getBuilder().getContext(), flags); 2454 } 2455 2456 LoopOptionsAttrBuilder::LoopOptionsAttrBuilder(LoopOptionsAttr attr) 2457 : options(attr.getOptions().begin(), attr.getOptions().end()) {} 2458 2459 template <typename T> 2460 LoopOptionsAttrBuilder &LoopOptionsAttrBuilder::setOption(LoopOptionCase tag, 2461 Optional<T> value) { 2462 auto option = llvm::find_if( 2463 options, [tag](auto option) { return option.first == tag; }); 2464 if (option != options.end()) { 2465 if (value.hasValue()) 2466 option->second = *value; 2467 else 2468 options.erase(option); 2469 } else { 2470 options.push_back(LoopOptionsAttr::OptionValuePair(tag, *value)); 2471 } 2472 return *this; 2473 } 2474 2475 LoopOptionsAttrBuilder & 2476 LoopOptionsAttrBuilder::setDisableLICM(Optional<bool> value) { 2477 return setOption(LoopOptionCase::disable_licm, value); 2478 } 2479 2480 /// Set the `interleave_count` option to the provided value. If no value 2481 /// is provided the option is deleted. 2482 LoopOptionsAttrBuilder & 2483 LoopOptionsAttrBuilder::setInterleaveCount(Optional<uint64_t> count) { 2484 return setOption(LoopOptionCase::interleave_count, count); 2485 } 2486 2487 /// Set the `disable_unroll` option to the provided value. If no value 2488 /// is provided the option is deleted. 2489 LoopOptionsAttrBuilder & 2490 LoopOptionsAttrBuilder::setDisableUnroll(Optional<bool> value) { 2491 return setOption(LoopOptionCase::disable_unroll, value); 2492 } 2493 2494 /// Set the `disable_pipeline` option to the provided value. If no value 2495 /// is provided the option is deleted. 2496 LoopOptionsAttrBuilder & 2497 LoopOptionsAttrBuilder::setDisablePipeline(Optional<bool> value) { 2498 return setOption(LoopOptionCase::disable_pipeline, value); 2499 } 2500 2501 /// Set the `pipeline_initiation_interval` option to the provided value. 2502 /// If no value is provided the option is deleted. 2503 LoopOptionsAttrBuilder &LoopOptionsAttrBuilder::setPipelineInitiationInterval( 2504 Optional<uint64_t> count) { 2505 return setOption(LoopOptionCase::pipeline_initiation_interval, count); 2506 } 2507 2508 template <typename T> 2509 static Optional<T> 2510 getOption(ArrayRef<std::pair<LoopOptionCase, int64_t>> options, 2511 LoopOptionCase option) { 2512 auto it = 2513 lower_bound(options, option, [](auto optionPair, LoopOptionCase option) { 2514 return optionPair.first < option; 2515 }); 2516 if (it == options.end()) 2517 return {}; 2518 return static_cast<T>(it->second); 2519 } 2520 2521 Optional<bool> LoopOptionsAttr::disableUnroll() { 2522 return getOption<bool>(getOptions(), LoopOptionCase::disable_unroll); 2523 } 2524 2525 Optional<bool> LoopOptionsAttr::disableLICM() { 2526 return getOption<bool>(getOptions(), LoopOptionCase::disable_licm); 2527 } 2528 2529 Optional<int64_t> LoopOptionsAttr::interleaveCount() { 2530 return getOption<int64_t>(getOptions(), LoopOptionCase::interleave_count); 2531 } 2532 2533 /// Build the LoopOptions Attribute from a sorted array of individual options. 2534 LoopOptionsAttr LoopOptionsAttr::get( 2535 MLIRContext *context, 2536 ArrayRef<std::pair<LoopOptionCase, int64_t>> sortedOptions) { 2537 assert(llvm::is_sorted(sortedOptions, llvm::less_first()) && 2538 "LoopOptionsAttr ctor expects a sorted options array"); 2539 return Base::get(context, sortedOptions); 2540 } 2541 2542 /// Build the LoopOptions Attribute from a sorted array of individual options. 2543 LoopOptionsAttr LoopOptionsAttr::get(MLIRContext *context, 2544 LoopOptionsAttrBuilder &optionBuilders) { 2545 llvm::sort(optionBuilders.options, llvm::less_first()); 2546 return Base::get(context, optionBuilders.options); 2547 } 2548 2549 void LoopOptionsAttr::print(DialectAsmPrinter &printer) const { 2550 printer << getMnemonic() << "<"; 2551 llvm::interleaveComma(getOptions(), printer, [&](auto option) { 2552 printer << stringifyEnum(option.first) << " = "; 2553 switch (option.first) { 2554 case LoopOptionCase::disable_licm: 2555 case LoopOptionCase::disable_unroll: 2556 case LoopOptionCase::disable_pipeline: 2557 printer << (option.second ? "true" : "false"); 2558 break; 2559 case LoopOptionCase::interleave_count: 2560 case LoopOptionCase::pipeline_initiation_interval: 2561 printer << option.second; 2562 break; 2563 } 2564 }); 2565 printer << ">"; 2566 } 2567 2568 Attribute LoopOptionsAttr::parse(MLIRContext *context, DialectAsmParser &parser, 2569 Type type) { 2570 if (failed(parser.parseLess())) 2571 return {}; 2572 2573 SmallVector<std::pair<LoopOptionCase, int64_t>> options; 2574 llvm::SmallDenseSet<LoopOptionCase> seenOptions; 2575 do { 2576 StringRef optionName; 2577 if (parser.parseKeyword(&optionName)) 2578 return {}; 2579 2580 auto option = symbolizeLoopOptionCase(optionName); 2581 if (!option) { 2582 parser.emitError(parser.getNameLoc(), "unknown loop option: ") 2583 << optionName; 2584 return {}; 2585 } 2586 if (!seenOptions.insert(*option).second) { 2587 parser.emitError(parser.getNameLoc(), "loop option present twice"); 2588 return {}; 2589 } 2590 if (failed(parser.parseEqual())) 2591 return {}; 2592 2593 int64_t value; 2594 switch (*option) { 2595 case LoopOptionCase::disable_licm: 2596 case LoopOptionCase::disable_unroll: 2597 case LoopOptionCase::disable_pipeline: 2598 if (succeeded(parser.parseOptionalKeyword("true"))) 2599 value = 1; 2600 else if (succeeded(parser.parseOptionalKeyword("false"))) 2601 value = 0; 2602 else { 2603 parser.emitError(parser.getNameLoc(), 2604 "expected boolean value 'true' or 'false'"); 2605 return {}; 2606 } 2607 break; 2608 case LoopOptionCase::interleave_count: 2609 case LoopOptionCase::pipeline_initiation_interval: 2610 if (failed(parser.parseInteger(value))) { 2611 parser.emitError(parser.getNameLoc(), "expected integer value"); 2612 return {}; 2613 } 2614 break; 2615 } 2616 options.push_back(std::make_pair(*option, value)); 2617 } while (succeeded(parser.parseOptionalComma())); 2618 if (failed(parser.parseGreater())) 2619 return {}; 2620 2621 llvm::sort(options, llvm::less_first()); 2622 return get(parser.getBuilder().getContext(), options); 2623 } 2624 2625 Attribute LLVMDialect::parseAttribute(DialectAsmParser &parser, 2626 Type type) const { 2627 if (type) { 2628 parser.emitError(parser.getNameLoc(), "unexpected type"); 2629 return {}; 2630 } 2631 StringRef attrKind; 2632 if (parser.parseKeyword(&attrKind)) 2633 return {}; 2634 { 2635 Attribute attr; 2636 auto parseResult = 2637 generatedAttributeParser(getContext(), parser, attrKind, type, attr); 2638 if (parseResult.hasValue()) 2639 return attr; 2640 } 2641 parser.emitError(parser.getNameLoc(), "unknown attribute type: ") << attrKind; 2642 return {}; 2643 } 2644 2645 void LLVMDialect::printAttribute(Attribute attr, DialectAsmPrinter &os) const { 2646 if (succeeded(generatedAttributePrinter(attr, os))) 2647 return; 2648 llvm_unreachable("Unknown attribute type"); 2649 } 2650