1 //===-- FIROps.cpp --------------------------------------------------------===// 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 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/ 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "flang/Optimizer/Dialect/FIROps.h" 14 #include "flang/Optimizer/Dialect/FIRAttr.h" 15 #include "flang/Optimizer/Dialect/FIROpsSupport.h" 16 #include "flang/Optimizer/Dialect/FIRType.h" 17 #include "mlir/Dialect/CommonFolders.h" 18 #include "mlir/Dialect/StandardOps/IR/Ops.h" 19 #include "mlir/IR/BuiltinOps.h" 20 #include "mlir/IR/Diagnostics.h" 21 #include "mlir/IR/Matchers.h" 22 #include "mlir/IR/PatternMatch.h" 23 #include "llvm/ADT/StringSwitch.h" 24 #include "llvm/ADT/TypeSwitch.h" 25 26 using namespace fir; 27 28 /// Return true if a sequence type is of some incomplete size or a record type 29 /// is malformed or contains an incomplete sequence type. An incomplete sequence 30 /// type is one with more unknown extents in the type than have been provided 31 /// via `dynamicExtents`. Sequence types with an unknown rank are incomplete by 32 /// definition. 33 static bool verifyInType(mlir::Type inType, 34 llvm::SmallVectorImpl<llvm::StringRef> &visited, 35 unsigned dynamicExtents = 0) { 36 if (auto st = inType.dyn_cast<fir::SequenceType>()) { 37 auto shape = st.getShape(); 38 if (shape.size() == 0) 39 return true; 40 for (std::size_t i = 0, end{shape.size()}; i < end; ++i) { 41 if (shape[i] != fir::SequenceType::getUnknownExtent()) 42 continue; 43 if (dynamicExtents-- == 0) 44 return true; 45 } 46 } else if (auto rt = inType.dyn_cast<fir::RecordType>()) { 47 // don't recurse if we're already visiting this one 48 if (llvm::is_contained(visited, rt.getName())) 49 return false; 50 // keep track of record types currently being visited 51 visited.push_back(rt.getName()); 52 for (auto &field : rt.getTypeList()) 53 if (verifyInType(field.second, visited)) 54 return true; 55 visited.pop_back(); 56 } else if (auto rt = inType.dyn_cast<fir::PointerType>()) { 57 return verifyInType(rt.getEleTy(), visited); 58 } 59 return false; 60 } 61 62 static bool verifyRecordLenParams(mlir::Type inType, unsigned numLenParams) { 63 if (numLenParams > 0) { 64 if (auto rt = inType.dyn_cast<fir::RecordType>()) 65 return numLenParams != rt.getNumLenParams(); 66 return true; 67 } 68 return false; 69 } 70 71 //===----------------------------------------------------------------------===// 72 // AllocaOp 73 //===----------------------------------------------------------------------===// 74 75 mlir::Type fir::AllocaOp::getAllocatedType() { 76 return getType().cast<ReferenceType>().getEleTy(); 77 } 78 79 /// Create a legal memory reference as return type 80 mlir::Type fir::AllocaOp::wrapResultType(mlir::Type intype) { 81 // FIR semantics: memory references to memory references are disallowed 82 if (intype.isa<ReferenceType>()) 83 return {}; 84 return ReferenceType::get(intype); 85 } 86 87 mlir::Type fir::AllocaOp::getRefTy(mlir::Type ty) { 88 return ReferenceType::get(ty); 89 } 90 91 //===----------------------------------------------------------------------===// 92 // AllocMemOp 93 //===----------------------------------------------------------------------===// 94 95 mlir::Type fir::AllocMemOp::getAllocatedType() { 96 return getType().cast<HeapType>().getEleTy(); 97 } 98 99 mlir::Type fir::AllocMemOp::getRefTy(mlir::Type ty) { 100 return HeapType::get(ty); 101 } 102 103 /// Create a legal heap reference as return type 104 mlir::Type fir::AllocMemOp::wrapResultType(mlir::Type intype) { 105 // Fortran semantics: C852 an entity cannot be both ALLOCATABLE and POINTER 106 // 8.5.3 note 1 prohibits ALLOCATABLE procedures as well 107 // FIR semantics: one may not allocate a memory reference value 108 if (intype.isa<ReferenceType>() || intype.isa<HeapType>() || 109 intype.isa<PointerType>() || intype.isa<FunctionType>()) 110 return {}; 111 return HeapType::get(intype); 112 } 113 114 //===----------------------------------------------------------------------===// 115 // ArrayCoorOp 116 //===----------------------------------------------------------------------===// 117 118 static mlir::LogicalResult verify(fir::ArrayCoorOp op) { 119 auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(op.memref().getType()); 120 auto arrTy = eleTy.dyn_cast<fir::SequenceType>(); 121 if (!arrTy) 122 return op.emitOpError("must be a reference to an array"); 123 auto arrDim = arrTy.getDimension(); 124 125 if (auto shapeOp = op.shape()) { 126 auto shapeTy = shapeOp.getType(); 127 unsigned shapeTyRank = 0; 128 if (auto s = shapeTy.dyn_cast<fir::ShapeType>()) { 129 shapeTyRank = s.getRank(); 130 } else if (auto ss = shapeTy.dyn_cast<fir::ShapeShiftType>()) { 131 shapeTyRank = ss.getRank(); 132 } else { 133 auto s = shapeTy.cast<fir::ShiftType>(); 134 shapeTyRank = s.getRank(); 135 if (!op.memref().getType().isa<fir::BoxType>()) 136 return op.emitOpError("shift can only be provided with fir.box memref"); 137 } 138 if (arrDim && arrDim != shapeTyRank) 139 return op.emitOpError("rank of dimension mismatched"); 140 if (shapeTyRank != op.indices().size()) 141 return op.emitOpError("number of indices do not match dim rank"); 142 } 143 144 if (auto sliceOp = op.slice()) 145 if (auto sliceTy = sliceOp.getType().dyn_cast<fir::SliceType>()) 146 if (sliceTy.getRank() != arrDim) 147 return op.emitOpError("rank of dimension in slice mismatched"); 148 149 return mlir::success(); 150 } 151 152 //===----------------------------------------------------------------------===// 153 // ArrayLoadOp 154 //===----------------------------------------------------------------------===// 155 156 std::vector<mlir::Value> fir::ArrayLoadOp::getExtents() { 157 if (auto sh = shape()) 158 if (auto *op = sh.getDefiningOp()) { 159 if (auto shOp = dyn_cast<fir::ShapeOp>(op)) 160 return shOp.getExtents(); 161 return cast<fir::ShapeShiftOp>(op).getExtents(); 162 } 163 return {}; 164 } 165 166 static mlir::LogicalResult verify(fir::ArrayLoadOp op) { 167 auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(op.memref().getType()); 168 auto arrTy = eleTy.dyn_cast<fir::SequenceType>(); 169 if (!arrTy) 170 return op.emitOpError("must be a reference to an array"); 171 auto arrDim = arrTy.getDimension(); 172 173 if (auto shapeOp = op.shape()) { 174 auto shapeTy = shapeOp.getType(); 175 unsigned shapeTyRank = 0; 176 if (auto s = shapeTy.dyn_cast<fir::ShapeType>()) { 177 shapeTyRank = s.getRank(); 178 } else if (auto ss = shapeTy.dyn_cast<fir::ShapeShiftType>()) { 179 shapeTyRank = ss.getRank(); 180 } else { 181 auto s = shapeTy.cast<fir::ShiftType>(); 182 shapeTyRank = s.getRank(); 183 if (!op.memref().getType().isa<fir::BoxType>()) 184 return op.emitOpError("shift can only be provided with fir.box memref"); 185 } 186 if (arrDim && arrDim != shapeTyRank) 187 return op.emitOpError("rank of dimension mismatched"); 188 } 189 190 if (auto sliceOp = op.slice()) 191 if (auto sliceTy = sliceOp.getType().dyn_cast<fir::SliceType>()) 192 if (sliceTy.getRank() != arrDim) 193 return op.emitOpError("rank of dimension in slice mismatched"); 194 195 return mlir::success(); 196 } 197 198 //===----------------------------------------------------------------------===// 199 // BoxAddrOp 200 //===----------------------------------------------------------------------===// 201 202 mlir::OpFoldResult fir::BoxAddrOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) { 203 if (auto v = val().getDefiningOp()) { 204 if (auto box = dyn_cast<fir::EmboxOp>(v)) 205 return box.memref(); 206 if (auto box = dyn_cast<fir::EmboxCharOp>(v)) 207 return box.memref(); 208 } 209 return {}; 210 } 211 212 //===----------------------------------------------------------------------===// 213 // BoxCharLenOp 214 //===----------------------------------------------------------------------===// 215 216 mlir::OpFoldResult 217 fir::BoxCharLenOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) { 218 if (auto v = val().getDefiningOp()) { 219 if (auto box = dyn_cast<fir::EmboxCharOp>(v)) 220 return box.len(); 221 } 222 return {}; 223 } 224 225 //===----------------------------------------------------------------------===// 226 // BoxDimsOp 227 //===----------------------------------------------------------------------===// 228 229 /// Get the result types packed in a tuple tuple 230 mlir::Type fir::BoxDimsOp::getTupleType() { 231 // note: triple, but 4 is nearest power of 2 232 llvm::SmallVector<mlir::Type, 4> triple{ 233 getResult(0).getType(), getResult(1).getType(), getResult(2).getType()}; 234 return mlir::TupleType::get(getContext(), triple); 235 } 236 237 //===----------------------------------------------------------------------===// 238 // CallOp 239 //===----------------------------------------------------------------------===// 240 241 mlir::FunctionType fir::CallOp::getFunctionType() { 242 return mlir::FunctionType::get(getContext(), getOperandTypes(), 243 getResultTypes()); 244 } 245 246 static void printCallOp(mlir::OpAsmPrinter &p, fir::CallOp &op) { 247 auto callee = op.callee(); 248 bool isDirect = callee.hasValue(); 249 p << op.getOperationName() << ' '; 250 if (isDirect) 251 p << callee.getValue(); 252 else 253 p << op.getOperand(0); 254 p << '(' << op->getOperands().drop_front(isDirect ? 0 : 1) << ')'; 255 p.printOptionalAttrDict(op->getAttrs(), {fir::CallOp::calleeAttrName()}); 256 auto resultTypes{op.getResultTypes()}; 257 llvm::SmallVector<Type, 8> argTypes( 258 llvm::drop_begin(op.getOperandTypes(), isDirect ? 0 : 1)); 259 p << " : " << FunctionType::get(op.getContext(), argTypes, resultTypes); 260 } 261 262 static mlir::ParseResult parseCallOp(mlir::OpAsmParser &parser, 263 mlir::OperationState &result) { 264 llvm::SmallVector<mlir::OpAsmParser::OperandType, 8> operands; 265 if (parser.parseOperandList(operands)) 266 return mlir::failure(); 267 268 mlir::NamedAttrList attrs; 269 mlir::SymbolRefAttr funcAttr; 270 bool isDirect = operands.empty(); 271 if (isDirect) 272 if (parser.parseAttribute(funcAttr, fir::CallOp::calleeAttrName(), attrs)) 273 return mlir::failure(); 274 275 Type type; 276 if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::Paren) || 277 parser.parseOptionalAttrDict(attrs) || parser.parseColon() || 278 parser.parseType(type)) 279 return mlir::failure(); 280 281 auto funcType = type.dyn_cast<mlir::FunctionType>(); 282 if (!funcType) 283 return parser.emitError(parser.getNameLoc(), "expected function type"); 284 if (isDirect) { 285 if (parser.resolveOperands(operands, funcType.getInputs(), 286 parser.getNameLoc(), result.operands)) 287 return mlir::failure(); 288 } else { 289 auto funcArgs = 290 llvm::ArrayRef<mlir::OpAsmParser::OperandType>(operands).drop_front(); 291 if (parser.resolveOperand(operands[0], funcType, result.operands) || 292 parser.resolveOperands(funcArgs, funcType.getInputs(), 293 parser.getNameLoc(), result.operands)) 294 return mlir::failure(); 295 } 296 result.addTypes(funcType.getResults()); 297 result.attributes = attrs; 298 return mlir::success(); 299 } 300 301 //===----------------------------------------------------------------------===// 302 // CmpfOp 303 //===----------------------------------------------------------------------===// 304 305 // Note: getCmpFPredicateNames() is inline static in StandardOps/IR/Ops.cpp 306 mlir::CmpFPredicate fir::CmpfOp::getPredicateByName(llvm::StringRef name) { 307 auto pred = mlir::symbolizeCmpFPredicate(name); 308 assert(pred.hasValue() && "invalid predicate name"); 309 return pred.getValue(); 310 } 311 312 void fir::buildCmpFOp(OpBuilder &builder, OperationState &result, 313 CmpFPredicate predicate, Value lhs, Value rhs) { 314 result.addOperands({lhs, rhs}); 315 result.types.push_back(builder.getI1Type()); 316 result.addAttribute( 317 CmpfOp::getPredicateAttrName(), 318 builder.getI64IntegerAttr(static_cast<int64_t>(predicate))); 319 } 320 321 template <typename OPTY> 322 static void printCmpOp(OpAsmPrinter &p, OPTY op) { 323 p << op.getOperationName() << ' '; 324 auto predSym = mlir::symbolizeCmpFPredicate( 325 op->template getAttrOfType<mlir::IntegerAttr>( 326 OPTY::getPredicateAttrName()) 327 .getInt()); 328 assert(predSym.hasValue() && "invalid symbol value for predicate"); 329 p << '"' << mlir::stringifyCmpFPredicate(predSym.getValue()) << '"' << ", "; 330 p.printOperand(op.lhs()); 331 p << ", "; 332 p.printOperand(op.rhs()); 333 p.printOptionalAttrDict(op->getAttrs(), 334 /*elidedAttrs=*/{OPTY::getPredicateAttrName()}); 335 p << " : " << op.lhs().getType(); 336 } 337 338 static void printCmpfOp(OpAsmPrinter &p, CmpfOp op) { printCmpOp(p, op); } 339 340 template <typename OPTY> 341 static mlir::ParseResult parseCmpOp(mlir::OpAsmParser &parser, 342 mlir::OperationState &result) { 343 llvm::SmallVector<mlir::OpAsmParser::OperandType, 2> ops; 344 mlir::NamedAttrList attrs; 345 mlir::Attribute predicateNameAttr; 346 mlir::Type type; 347 if (parser.parseAttribute(predicateNameAttr, OPTY::getPredicateAttrName(), 348 attrs) || 349 parser.parseComma() || parser.parseOperandList(ops, 2) || 350 parser.parseOptionalAttrDict(attrs) || parser.parseColonType(type) || 351 parser.resolveOperands(ops, type, result.operands)) 352 return failure(); 353 354 if (!predicateNameAttr.isa<mlir::StringAttr>()) 355 return parser.emitError(parser.getNameLoc(), 356 "expected string comparison predicate attribute"); 357 358 // Rewrite string attribute to an enum value. 359 llvm::StringRef predicateName = 360 predicateNameAttr.cast<mlir::StringAttr>().getValue(); 361 auto predicate = fir::CmpfOp::getPredicateByName(predicateName); 362 auto builder = parser.getBuilder(); 363 mlir::Type i1Type = builder.getI1Type(); 364 attrs.set(OPTY::getPredicateAttrName(), 365 builder.getI64IntegerAttr(static_cast<int64_t>(predicate))); 366 result.attributes = attrs; 367 result.addTypes({i1Type}); 368 return success(); 369 } 370 371 mlir::ParseResult fir::parseCmpfOp(mlir::OpAsmParser &parser, 372 mlir::OperationState &result) { 373 return parseCmpOp<fir::CmpfOp>(parser, result); 374 } 375 376 //===----------------------------------------------------------------------===// 377 // CmpcOp 378 //===----------------------------------------------------------------------===// 379 380 void fir::buildCmpCOp(OpBuilder &builder, OperationState &result, 381 CmpFPredicate predicate, Value lhs, Value rhs) { 382 result.addOperands({lhs, rhs}); 383 result.types.push_back(builder.getI1Type()); 384 result.addAttribute( 385 fir::CmpcOp::getPredicateAttrName(), 386 builder.getI64IntegerAttr(static_cast<int64_t>(predicate))); 387 } 388 389 static void printCmpcOp(OpAsmPrinter &p, fir::CmpcOp op) { printCmpOp(p, op); } 390 391 mlir::ParseResult fir::parseCmpcOp(mlir::OpAsmParser &parser, 392 mlir::OperationState &result) { 393 return parseCmpOp<fir::CmpcOp>(parser, result); 394 } 395 396 //===----------------------------------------------------------------------===// 397 // ConvertOp 398 //===----------------------------------------------------------------------===// 399 400 void fir::ConvertOp::getCanonicalizationPatterns( 401 OwningRewritePatternList &results, MLIRContext *context) { 402 } 403 404 mlir::OpFoldResult fir::ConvertOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) { 405 if (value().getType() == getType()) 406 return value(); 407 if (matchPattern(value(), m_Op<fir::ConvertOp>())) { 408 auto inner = cast<fir::ConvertOp>(value().getDefiningOp()); 409 // (convert (convert 'a : logical -> i1) : i1 -> logical) ==> forward 'a 410 if (auto toTy = getType().dyn_cast<fir::LogicalType>()) 411 if (auto fromTy = inner.value().getType().dyn_cast<fir::LogicalType>()) 412 if (inner.getType().isa<mlir::IntegerType>() && (toTy == fromTy)) 413 return inner.value(); 414 // (convert (convert 'a : i1 -> logical) : logical -> i1) ==> forward 'a 415 if (auto toTy = getType().dyn_cast<mlir::IntegerType>()) 416 if (auto fromTy = inner.value().getType().dyn_cast<mlir::IntegerType>()) 417 if (inner.getType().isa<fir::LogicalType>() && (toTy == fromTy) && 418 (fromTy.getWidth() == 1)) 419 return inner.value(); 420 } 421 return {}; 422 } 423 424 bool fir::ConvertOp::isIntegerCompatible(mlir::Type ty) { 425 return ty.isa<mlir::IntegerType>() || ty.isa<mlir::IndexType>() || 426 ty.isa<fir::IntegerType>() || ty.isa<fir::LogicalType>(); 427 } 428 429 bool fir::ConvertOp::isFloatCompatible(mlir::Type ty) { 430 return ty.isa<mlir::FloatType>() || ty.isa<fir::RealType>(); 431 } 432 433 bool fir::ConvertOp::isPointerCompatible(mlir::Type ty) { 434 return ty.isa<fir::ReferenceType>() || ty.isa<fir::PointerType>() || 435 ty.isa<fir::HeapType>() || ty.isa<mlir::MemRefType>() || 436 ty.isa<mlir::FunctionType>() || ty.isa<fir::TypeDescType>(); 437 } 438 439 //===----------------------------------------------------------------------===// 440 // CoordinateOp 441 //===----------------------------------------------------------------------===// 442 443 static void print(mlir::OpAsmPrinter &p, fir::CoordinateOp op) { 444 p << op.getOperationName() << ' ' << op.ref() << ", " << op.coor(); 445 p.printOptionalAttrDict(op->getAttrs(), /*elideAttrs=*/{"baseType"}); 446 p << " : "; 447 p.printFunctionalType(op.getOperandTypes(), op->getResultTypes()); 448 } 449 450 static mlir::ParseResult parseCoordinateCustom(mlir::OpAsmParser &parser, 451 mlir::OperationState &result) { 452 mlir::OpAsmParser::OperandType memref; 453 if (parser.parseOperand(memref) || parser.parseComma()) 454 return mlir::failure(); 455 llvm::SmallVector<mlir::OpAsmParser::OperandType, 8> coorOperands; 456 if (parser.parseOperandList(coorOperands)) 457 return mlir::failure(); 458 llvm::SmallVector<mlir::OpAsmParser::OperandType, 16> allOperands; 459 allOperands.push_back(memref); 460 allOperands.append(coorOperands.begin(), coorOperands.end()); 461 mlir::FunctionType funcTy; 462 auto loc = parser.getCurrentLocation(); 463 if (parser.parseOptionalAttrDict(result.attributes) || 464 parser.parseColonType(funcTy) || 465 parser.resolveOperands(allOperands, funcTy.getInputs(), loc, 466 result.operands)) 467 return failure(); 468 parser.addTypesToList(funcTy.getResults(), result.types); 469 result.addAttribute("baseType", mlir::TypeAttr::get(funcTy.getInput(0))); 470 return mlir::success(); 471 } 472 473 static mlir::LogicalResult verify(fir::CoordinateOp op) { 474 auto refTy = op.ref().getType(); 475 if (fir::isa_ref_type(refTy)) { 476 auto eleTy = fir::dyn_cast_ptrEleTy(refTy); 477 if (auto arrTy = eleTy.dyn_cast<fir::SequenceType>()) { 478 if (arrTy.hasUnknownShape()) 479 return op.emitOpError("cannot find coordinate in unknown shape"); 480 if (arrTy.getConstantRows() < arrTy.getDimension() - 1) 481 return op.emitOpError("cannot find coordinate with unknown extents"); 482 } 483 if (!(fir::isa_aggregate(eleTy) || fir::isa_complex(eleTy) || 484 fir::isa_char_string(eleTy))) 485 return op.emitOpError("cannot apply coordinate_of to this type"); 486 } 487 // Recovering a LEN type parameter only makes sense from a boxed value. For a 488 // bare reference, the LEN type parameters must be passed as additional 489 // arguments to `op`. 490 for (auto co : op.coor()) 491 if (dyn_cast_or_null<fir::LenParamIndexOp>(co.getDefiningOp())) { 492 if (op.getNumOperands() != 2) 493 return op.emitOpError("len_param_index must be last argument"); 494 if (!op.ref().getType().isa<BoxType>()) 495 return op.emitOpError("len_param_index must be used on box type"); 496 } 497 return mlir::success(); 498 } 499 500 //===----------------------------------------------------------------------===// 501 // DispatchOp 502 //===----------------------------------------------------------------------===// 503 504 mlir::FunctionType fir::DispatchOp::getFunctionType() { 505 return mlir::FunctionType::get(getContext(), getOperandTypes(), 506 getResultTypes()); 507 } 508 509 //===----------------------------------------------------------------------===// 510 // DispatchTableOp 511 //===----------------------------------------------------------------------===// 512 513 void fir::DispatchTableOp::appendTableEntry(mlir::Operation *op) { 514 assert(mlir::isa<fir::DTEntryOp>(*op) && "operation must be a DTEntryOp"); 515 auto &block = getBlock(); 516 block.getOperations().insert(block.end(), op); 517 } 518 519 //===----------------------------------------------------------------------===// 520 // EmboxOp 521 //===----------------------------------------------------------------------===// 522 523 static mlir::LogicalResult verify(fir::EmboxOp op) { 524 auto eleTy = fir::dyn_cast_ptrEleTy(op.memref().getType()); 525 bool isArray = false; 526 if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) { 527 eleTy = seqTy.getEleTy(); 528 isArray = true; 529 } 530 if (op.hasLenParams()) { 531 auto lenPs = op.numLenParams(); 532 if (auto rt = eleTy.dyn_cast<fir::RecordType>()) { 533 if (lenPs != rt.getNumLenParams()) 534 return op.emitOpError("number of LEN params does not correspond" 535 " to the !fir.type type"); 536 } else if (auto strTy = eleTy.dyn_cast<fir::CharacterType>()) { 537 if (strTy.getLen() != fir::CharacterType::unknownLen()) 538 return op.emitOpError("CHARACTER already has static LEN"); 539 } else { 540 return op.emitOpError("LEN parameters require CHARACTER or derived type"); 541 } 542 for (auto lp : op.lenParams()) 543 if (!fir::isa_integer(lp.getType())) 544 return op.emitOpError("LEN parameters must be integral type"); 545 } 546 if (op.getShape() && !isArray) 547 return op.emitOpError("shape must not be provided for a scalar"); 548 if (op.getSlice() && !isArray) 549 return op.emitOpError("slice must not be provided for a scalar"); 550 return mlir::success(); 551 } 552 553 //===----------------------------------------------------------------------===// 554 // GenTypeDescOp 555 //===----------------------------------------------------------------------===// 556 557 void fir::GenTypeDescOp::build(OpBuilder &, OperationState &result, 558 mlir::TypeAttr inty) { 559 result.addAttribute("in_type", inty); 560 result.addTypes(TypeDescType::get(inty.getValue())); 561 } 562 563 //===----------------------------------------------------------------------===// 564 // GlobalOp 565 //===----------------------------------------------------------------------===// 566 567 static ParseResult parseGlobalOp(OpAsmParser &parser, OperationState &result) { 568 // Parse the optional linkage 569 llvm::StringRef linkage; 570 auto &builder = parser.getBuilder(); 571 if (mlir::succeeded(parser.parseOptionalKeyword(&linkage))) { 572 if (fir::GlobalOp::verifyValidLinkage(linkage)) 573 return mlir::failure(); 574 mlir::StringAttr linkAttr = builder.getStringAttr(linkage); 575 result.addAttribute(fir::GlobalOp::linkageAttrName(), linkAttr); 576 } 577 578 // Parse the name as a symbol reference attribute. 579 mlir::SymbolRefAttr nameAttr; 580 if (parser.parseAttribute(nameAttr, fir::GlobalOp::symbolAttrName(), 581 result.attributes)) 582 return mlir::failure(); 583 result.addAttribute(mlir::SymbolTable::getSymbolAttrName(), 584 builder.getStringAttr(nameAttr.getRootReference())); 585 586 bool simpleInitializer = false; 587 if (mlir::succeeded(parser.parseOptionalLParen())) { 588 Attribute attr; 589 if (parser.parseAttribute(attr, fir::GlobalOp::initValAttrName(), 590 result.attributes) || 591 parser.parseRParen()) 592 return mlir::failure(); 593 simpleInitializer = true; 594 } 595 596 if (succeeded(parser.parseOptionalKeyword("constant"))) { 597 // if "constant" keyword then mark this as a constant, not a variable 598 result.addAttribute(fir::GlobalOp::constantAttrName(), 599 builder.getUnitAttr()); 600 } 601 602 mlir::Type globalType; 603 if (parser.parseColonType(globalType)) 604 return mlir::failure(); 605 606 result.addAttribute(fir::GlobalOp::typeAttrName(), 607 mlir::TypeAttr::get(globalType)); 608 609 if (simpleInitializer) { 610 result.addRegion(); 611 } else { 612 // Parse the optional initializer body. 613 auto parseResult = parser.parseOptionalRegion( 614 *result.addRegion(), /*arguments=*/llvm::None, /*argTypes=*/llvm::None); 615 if (parseResult.hasValue() && mlir::failed(*parseResult)) 616 return mlir::failure(); 617 } 618 619 return mlir::success(); 620 } 621 622 void fir::GlobalOp::appendInitialValue(mlir::Operation *op) { 623 getBlock().getOperations().push_back(op); 624 } 625 626 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result, 627 StringRef name, bool isConstant, Type type, 628 Attribute initialVal, StringAttr linkage, 629 ArrayRef<NamedAttribute> attrs) { 630 result.addRegion(); 631 result.addAttribute(typeAttrName(), mlir::TypeAttr::get(type)); 632 result.addAttribute(mlir::SymbolTable::getSymbolAttrName(), 633 builder.getStringAttr(name)); 634 result.addAttribute(symbolAttrName(), builder.getSymbolRefAttr(name)); 635 if (isConstant) 636 result.addAttribute(constantAttrName(), builder.getUnitAttr()); 637 if (initialVal) 638 result.addAttribute(initValAttrName(), initialVal); 639 if (linkage) 640 result.addAttribute(linkageAttrName(), linkage); 641 result.attributes.append(attrs.begin(), attrs.end()); 642 } 643 644 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result, 645 StringRef name, Type type, Attribute initialVal, 646 StringAttr linkage, ArrayRef<NamedAttribute> attrs) { 647 build(builder, result, name, /*isConstant=*/false, type, {}, linkage, attrs); 648 } 649 650 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result, 651 StringRef name, bool isConstant, Type type, 652 StringAttr linkage, ArrayRef<NamedAttribute> attrs) { 653 build(builder, result, name, isConstant, type, {}, linkage, attrs); 654 } 655 656 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result, 657 StringRef name, Type type, StringAttr linkage, 658 ArrayRef<NamedAttribute> attrs) { 659 build(builder, result, name, /*isConstant=*/false, type, {}, linkage, attrs); 660 } 661 662 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result, 663 StringRef name, bool isConstant, Type type, 664 ArrayRef<NamedAttribute> attrs) { 665 build(builder, result, name, isConstant, type, StringAttr{}, attrs); 666 } 667 668 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result, 669 StringRef name, Type type, 670 ArrayRef<NamedAttribute> attrs) { 671 build(builder, result, name, /*isConstant=*/false, type, attrs); 672 } 673 674 mlir::ParseResult fir::GlobalOp::verifyValidLinkage(StringRef linkage) { 675 // Supporting only a subset of the LLVM linkage types for now 676 static const char *validNames[] = {"common", "internal", "linkonce", "weak"}; 677 return mlir::success(llvm::is_contained(validNames, linkage)); 678 } 679 680 //===----------------------------------------------------------------------===// 681 // InsertValueOp 682 //===----------------------------------------------------------------------===// 683 684 static bool checkIsIntegerConstant(mlir::Value v, int64_t conVal) { 685 if (auto c = dyn_cast_or_null<mlir::ConstantOp>(v.getDefiningOp())) { 686 auto attr = c.getValue(); 687 if (auto iattr = attr.dyn_cast<mlir::IntegerAttr>()) 688 return iattr.getInt() == conVal; 689 } 690 return false; 691 } 692 static bool isZero(mlir::Value v) { return checkIsIntegerConstant(v, 0); } 693 static bool isOne(mlir::Value v) { return checkIsIntegerConstant(v, 1); } 694 695 // Undo some complex patterns created in the front-end and turn them back into 696 // complex ops. 697 template <typename FltOp, typename CpxOp> 698 struct UndoComplexPattern : public mlir::RewritePattern { 699 UndoComplexPattern(mlir::MLIRContext *ctx) 700 : mlir::RewritePattern("fir.insert_value", 2, ctx) {} 701 702 mlir::LogicalResult 703 matchAndRewrite(mlir::Operation *op, 704 mlir::PatternRewriter &rewriter) const override { 705 auto insval = dyn_cast_or_null<fir::InsertValueOp>(op); 706 if (!insval || !insval.getType().isa<fir::ComplexType>()) 707 return mlir::failure(); 708 auto insval2 = 709 dyn_cast_or_null<fir::InsertValueOp>(insval.adt().getDefiningOp()); 710 if (!insval2 || !isa<fir::UndefOp>(insval2.adt().getDefiningOp())) 711 return mlir::failure(); 712 auto binf = dyn_cast_or_null<FltOp>(insval.val().getDefiningOp()); 713 auto binf2 = dyn_cast_or_null<FltOp>(insval2.val().getDefiningOp()); 714 if (!binf || !binf2 || insval.coor().size() != 1 || 715 !isOne(insval.coor()[0]) || insval2.coor().size() != 1 || 716 !isZero(insval2.coor()[0])) 717 return mlir::failure(); 718 auto eai = 719 dyn_cast_or_null<fir::ExtractValueOp>(binf.lhs().getDefiningOp()); 720 auto ebi = 721 dyn_cast_or_null<fir::ExtractValueOp>(binf.rhs().getDefiningOp()); 722 auto ear = 723 dyn_cast_or_null<fir::ExtractValueOp>(binf2.lhs().getDefiningOp()); 724 auto ebr = 725 dyn_cast_or_null<fir::ExtractValueOp>(binf2.rhs().getDefiningOp()); 726 if (!eai || !ebi || !ear || !ebr || ear.adt() != eai.adt() || 727 ebr.adt() != ebi.adt() || eai.coor().size() != 1 || 728 !isOne(eai.coor()[0]) || ebi.coor().size() != 1 || 729 !isOne(ebi.coor()[0]) || ear.coor().size() != 1 || 730 !isZero(ear.coor()[0]) || ebr.coor().size() != 1 || 731 !isZero(ebr.coor()[0])) 732 return mlir::failure(); 733 rewriter.replaceOpWithNewOp<CpxOp>(op, ear.adt(), ebr.adt()); 734 return mlir::success(); 735 } 736 }; 737 738 void fir::InsertValueOp::getCanonicalizationPatterns( 739 mlir::OwningRewritePatternList &results, mlir::MLIRContext *context) { 740 results.insert<UndoComplexPattern<mlir::AddFOp, fir::AddcOp>, 741 UndoComplexPattern<mlir::SubFOp, fir::SubcOp>>(context); 742 } 743 744 //===----------------------------------------------------------------------===// 745 // IterWhileOp 746 //===----------------------------------------------------------------------===// 747 748 void fir::IterWhileOp::build(mlir::OpBuilder &builder, 749 mlir::OperationState &result, mlir::Value lb, 750 mlir::Value ub, mlir::Value step, 751 mlir::Value iterate, bool finalCountValue, 752 mlir::ValueRange iterArgs, 753 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 754 result.addOperands({lb, ub, step, iterate}); 755 if (finalCountValue) { 756 result.addTypes(builder.getIndexType()); 757 result.addAttribute(finalValueAttrName(), builder.getUnitAttr()); 758 } 759 result.addTypes(iterate.getType()); 760 result.addOperands(iterArgs); 761 for (auto v : iterArgs) 762 result.addTypes(v.getType()); 763 mlir::Region *bodyRegion = result.addRegion(); 764 bodyRegion->push_back(new Block{}); 765 bodyRegion->front().addArgument(builder.getIndexType()); 766 bodyRegion->front().addArgument(iterate.getType()); 767 bodyRegion->front().addArguments(iterArgs.getTypes()); 768 result.addAttributes(attributes); 769 } 770 771 static mlir::ParseResult parseIterWhileOp(mlir::OpAsmParser &parser, 772 mlir::OperationState &result) { 773 auto &builder = parser.getBuilder(); 774 mlir::OpAsmParser::OperandType inductionVariable, lb, ub, step; 775 if (parser.parseLParen() || parser.parseRegionArgument(inductionVariable) || 776 parser.parseEqual()) 777 return mlir::failure(); 778 779 // Parse loop bounds. 780 auto indexType = builder.getIndexType(); 781 auto i1Type = builder.getIntegerType(1); 782 if (parser.parseOperand(lb) || 783 parser.resolveOperand(lb, indexType, result.operands) || 784 parser.parseKeyword("to") || parser.parseOperand(ub) || 785 parser.resolveOperand(ub, indexType, result.operands) || 786 parser.parseKeyword("step") || parser.parseOperand(step) || 787 parser.parseRParen() || 788 parser.resolveOperand(step, indexType, result.operands)) 789 return mlir::failure(); 790 791 mlir::OpAsmParser::OperandType iterateVar, iterateInput; 792 if (parser.parseKeyword("and") || parser.parseLParen() || 793 parser.parseRegionArgument(iterateVar) || parser.parseEqual() || 794 parser.parseOperand(iterateInput) || parser.parseRParen() || 795 parser.resolveOperand(iterateInput, i1Type, result.operands)) 796 return mlir::failure(); 797 798 // Parse the initial iteration arguments. 799 llvm::SmallVector<mlir::OpAsmParser::OperandType, 4> regionArgs; 800 auto prependCount = false; 801 802 // Induction variable. 803 regionArgs.push_back(inductionVariable); 804 regionArgs.push_back(iterateVar); 805 806 if (succeeded(parser.parseOptionalKeyword("iter_args"))) { 807 llvm::SmallVector<mlir::OpAsmParser::OperandType, 4> operands; 808 llvm::SmallVector<mlir::Type, 4> regionTypes; 809 // Parse assignment list and results type list. 810 if (parser.parseAssignmentList(regionArgs, operands) || 811 parser.parseArrowTypeList(regionTypes)) 812 return failure(); 813 if (regionTypes.size() == operands.size() + 2) 814 prependCount = true; 815 llvm::ArrayRef<mlir::Type> resTypes = regionTypes; 816 resTypes = prependCount ? resTypes.drop_front(2) : resTypes; 817 // Resolve input operands. 818 for (auto operand_type : llvm::zip(operands, resTypes)) 819 if (parser.resolveOperand(std::get<0>(operand_type), 820 std::get<1>(operand_type), result.operands)) 821 return failure(); 822 if (prependCount) { 823 result.addTypes(regionTypes); 824 } else { 825 result.addTypes(i1Type); 826 result.addTypes(resTypes); 827 } 828 } else if (succeeded(parser.parseOptionalArrow())) { 829 llvm::SmallVector<mlir::Type, 4> typeList; 830 if (parser.parseLParen() || parser.parseTypeList(typeList) || 831 parser.parseRParen()) 832 return failure(); 833 // Type list must be "(index, i1)". 834 if (typeList.size() != 2 || !typeList[0].isa<mlir::IndexType>() || 835 !typeList[1].isSignlessInteger(1)) 836 return failure(); 837 result.addTypes(typeList); 838 prependCount = true; 839 } else { 840 result.addTypes(i1Type); 841 } 842 843 if (parser.parseOptionalAttrDictWithKeyword(result.attributes)) 844 return mlir::failure(); 845 846 llvm::SmallVector<mlir::Type, 4> argTypes; 847 // Induction variable (hidden) 848 if (prependCount) 849 result.addAttribute(IterWhileOp::finalValueAttrName(), 850 builder.getUnitAttr()); 851 else 852 argTypes.push_back(indexType); 853 // Loop carried variables (including iterate) 854 argTypes.append(result.types.begin(), result.types.end()); 855 // Parse the body region. 856 auto *body = result.addRegion(); 857 if (regionArgs.size() != argTypes.size()) 858 return parser.emitError( 859 parser.getNameLoc(), 860 "mismatch in number of loop-carried values and defined values"); 861 862 if (parser.parseRegion(*body, regionArgs, argTypes)) 863 return failure(); 864 865 fir::IterWhileOp::ensureTerminator(*body, builder, result.location); 866 867 return mlir::success(); 868 } 869 870 static mlir::LogicalResult verify(fir::IterWhileOp op) { 871 // Check that the body defines as single block argument for the induction 872 // variable. 873 auto *body = op.getBody(); 874 if (!body->getArgument(1).getType().isInteger(1)) 875 return op.emitOpError( 876 "expected body second argument to be an index argument for " 877 "the induction variable"); 878 if (!body->getArgument(0).getType().isIndex()) 879 return op.emitOpError( 880 "expected body first argument to be an index argument for " 881 "the induction variable"); 882 883 auto opNumResults = op.getNumResults(); 884 if (op.finalValue()) { 885 // Result type must be "(index, i1, ...)". 886 if (!op.getResult(0).getType().isa<mlir::IndexType>()) 887 return op.emitOpError("result #0 expected to be index"); 888 if (!op.getResult(1).getType().isSignlessInteger(1)) 889 return op.emitOpError("result #1 expected to be i1"); 890 opNumResults--; 891 } else { 892 // iterate_while always returns the early exit induction value. 893 // Result type must be "(i1, ...)" 894 if (!op.getResult(0).getType().isSignlessInteger(1)) 895 return op.emitOpError("result #0 expected to be i1"); 896 } 897 if (opNumResults == 0) 898 return mlir::failure(); 899 if (op.getNumIterOperands() != opNumResults) 900 return op.emitOpError( 901 "mismatch in number of loop-carried values and defined values"); 902 if (op.getNumRegionIterArgs() != opNumResults) 903 return op.emitOpError( 904 "mismatch in number of basic block args and defined values"); 905 auto iterOperands = op.getIterOperands(); 906 auto iterArgs = op.getRegionIterArgs(); 907 auto opResults = 908 op.finalValue() ? op.getResults().drop_front() : op.getResults(); 909 unsigned i = 0; 910 for (auto e : llvm::zip(iterOperands, iterArgs, opResults)) { 911 if (std::get<0>(e).getType() != std::get<2>(e).getType()) 912 return op.emitOpError() << "types mismatch between " << i 913 << "th iter operand and defined value"; 914 if (std::get<1>(e).getType() != std::get<2>(e).getType()) 915 return op.emitOpError() << "types mismatch between " << i 916 << "th iter region arg and defined value"; 917 918 i++; 919 } 920 return mlir::success(); 921 } 922 923 static void print(mlir::OpAsmPrinter &p, fir::IterWhileOp op) { 924 p << fir::IterWhileOp::getOperationName() << " (" << op.getInductionVar() 925 << " = " << op.lowerBound() << " to " << op.upperBound() << " step " 926 << op.step() << ") and ("; 927 assert(op.hasIterOperands()); 928 auto regionArgs = op.getRegionIterArgs(); 929 auto operands = op.getIterOperands(); 930 p << regionArgs.front() << " = " << *operands.begin() << ")"; 931 if (regionArgs.size() > 1) { 932 p << " iter_args("; 933 llvm::interleaveComma( 934 llvm::zip(regionArgs.drop_front(), operands.drop_front()), p, 935 [&](auto it) { p << std::get<0>(it) << " = " << std::get<1>(it); }); 936 p << ") -> ("; 937 llvm::interleaveComma( 938 llvm::drop_begin(op.getResultTypes(), op.finalValue() ? 0 : 1), p); 939 p << ")"; 940 } else if (op.finalValue()) { 941 p << " -> (" << op.getResultTypes() << ')'; 942 } 943 p.printOptionalAttrDictWithKeyword(op->getAttrs(), 944 {IterWhileOp::finalValueAttrName()}); 945 p.printRegion(op.region(), /*printEntryBlockArgs=*/false, 946 /*printBlockTerminators=*/true); 947 } 948 949 mlir::Region &fir::IterWhileOp::getLoopBody() { return region(); } 950 951 bool fir::IterWhileOp::isDefinedOutsideOfLoop(mlir::Value value) { 952 return !region().isAncestor(value.getParentRegion()); 953 } 954 955 mlir::LogicalResult 956 fir::IterWhileOp::moveOutOfLoop(llvm::ArrayRef<mlir::Operation *> ops) { 957 for (auto op : ops) 958 op->moveBefore(*this); 959 return success(); 960 } 961 962 mlir::BlockArgument fir::IterWhileOp::iterArgToBlockArg(mlir::Value iterArg) { 963 for (auto i : llvm::enumerate(initArgs())) 964 if (iterArg == i.value()) 965 return region().front().getArgument(i.index() + 1); 966 return {}; 967 } 968 969 void fir::IterWhileOp::resultToSourceOps( 970 llvm::SmallVectorImpl<mlir::Value> &results, unsigned resultNum) { 971 auto oper = finalValue() ? resultNum + 1 : resultNum; 972 auto *term = region().front().getTerminator(); 973 if (oper < term->getNumOperands()) 974 results.push_back(term->getOperand(oper)); 975 } 976 977 mlir::Value fir::IterWhileOp::blockArgToSourceOp(unsigned blockArgNum) { 978 if (blockArgNum > 0 && blockArgNum <= initArgs().size()) 979 return initArgs()[blockArgNum - 1]; 980 return {}; 981 } 982 983 //===----------------------------------------------------------------------===// 984 // LoadOp 985 //===----------------------------------------------------------------------===// 986 987 /// Get the element type of a reference like type; otherwise null 988 static mlir::Type elementTypeOf(mlir::Type ref) { 989 return llvm::TypeSwitch<mlir::Type, mlir::Type>(ref) 990 .Case<ReferenceType, PointerType, HeapType>( 991 [](auto type) { return type.getEleTy(); }) 992 .Default([](mlir::Type) { return mlir::Type{}; }); 993 } 994 995 mlir::ParseResult fir::LoadOp::getElementOf(mlir::Type &ele, mlir::Type ref) { 996 if ((ele = elementTypeOf(ref))) 997 return mlir::success(); 998 return mlir::failure(); 999 } 1000 1001 //===----------------------------------------------------------------------===// 1002 // DoLoopOp 1003 //===----------------------------------------------------------------------===// 1004 1005 void fir::DoLoopOp::build(mlir::OpBuilder &builder, 1006 mlir::OperationState &result, mlir::Value lb, 1007 mlir::Value ub, mlir::Value step, bool unordered, 1008 bool finalCountValue, mlir::ValueRange iterArgs, 1009 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 1010 result.addOperands({lb, ub, step}); 1011 result.addOperands(iterArgs); 1012 if (finalCountValue) { 1013 result.addTypes(builder.getIndexType()); 1014 result.addAttribute(finalValueAttrName(), builder.getUnitAttr()); 1015 } 1016 for (auto v : iterArgs) 1017 result.addTypes(v.getType()); 1018 mlir::Region *bodyRegion = result.addRegion(); 1019 bodyRegion->push_back(new Block{}); 1020 if (iterArgs.empty() && !finalCountValue) 1021 DoLoopOp::ensureTerminator(*bodyRegion, builder, result.location); 1022 bodyRegion->front().addArgument(builder.getIndexType()); 1023 bodyRegion->front().addArguments(iterArgs.getTypes()); 1024 if (unordered) 1025 result.addAttribute(unorderedAttrName(), builder.getUnitAttr()); 1026 result.addAttributes(attributes); 1027 } 1028 1029 static mlir::ParseResult parseDoLoopOp(mlir::OpAsmParser &parser, 1030 mlir::OperationState &result) { 1031 auto &builder = parser.getBuilder(); 1032 mlir::OpAsmParser::OperandType inductionVariable, lb, ub, step; 1033 // Parse the induction variable followed by '='. 1034 if (parser.parseRegionArgument(inductionVariable) || parser.parseEqual()) 1035 return mlir::failure(); 1036 1037 // Parse loop bounds. 1038 auto indexType = builder.getIndexType(); 1039 if (parser.parseOperand(lb) || 1040 parser.resolveOperand(lb, indexType, result.operands) || 1041 parser.parseKeyword("to") || parser.parseOperand(ub) || 1042 parser.resolveOperand(ub, indexType, result.operands) || 1043 parser.parseKeyword("step") || parser.parseOperand(step) || 1044 parser.resolveOperand(step, indexType, result.operands)) 1045 return failure(); 1046 1047 if (mlir::succeeded(parser.parseOptionalKeyword("unordered"))) 1048 result.addAttribute(fir::DoLoopOp::unorderedAttrName(), 1049 builder.getUnitAttr()); 1050 1051 // Parse the optional initial iteration arguments. 1052 llvm::SmallVector<mlir::OpAsmParser::OperandType, 4> regionArgs, operands; 1053 llvm::SmallVector<mlir::Type, 4> argTypes; 1054 auto prependCount = false; 1055 regionArgs.push_back(inductionVariable); 1056 1057 if (succeeded(parser.parseOptionalKeyword("iter_args"))) { 1058 // Parse assignment list and results type list. 1059 if (parser.parseAssignmentList(regionArgs, operands) || 1060 parser.parseArrowTypeList(result.types)) 1061 return failure(); 1062 if (result.types.size() == operands.size() + 1) 1063 prependCount = true; 1064 // Resolve input operands. 1065 llvm::ArrayRef<mlir::Type> resTypes = result.types; 1066 for (auto operand_type : 1067 llvm::zip(operands, prependCount ? resTypes.drop_front() : resTypes)) 1068 if (parser.resolveOperand(std::get<0>(operand_type), 1069 std::get<1>(operand_type), result.operands)) 1070 return failure(); 1071 } else if (succeeded(parser.parseOptionalArrow())) { 1072 if (parser.parseKeyword("index")) 1073 return failure(); 1074 result.types.push_back(indexType); 1075 prependCount = true; 1076 } 1077 1078 if (parser.parseOptionalAttrDictWithKeyword(result.attributes)) 1079 return mlir::failure(); 1080 1081 // Induction variable. 1082 if (prependCount) 1083 result.addAttribute(DoLoopOp::finalValueAttrName(), builder.getUnitAttr()); 1084 else 1085 argTypes.push_back(indexType); 1086 // Loop carried variables 1087 argTypes.append(result.types.begin(), result.types.end()); 1088 // Parse the body region. 1089 auto *body = result.addRegion(); 1090 if (regionArgs.size() != argTypes.size()) 1091 return parser.emitError( 1092 parser.getNameLoc(), 1093 "mismatch in number of loop-carried values and defined values"); 1094 1095 if (parser.parseRegion(*body, regionArgs, argTypes)) 1096 return failure(); 1097 1098 DoLoopOp::ensureTerminator(*body, builder, result.location); 1099 1100 return mlir::success(); 1101 } 1102 1103 fir::DoLoopOp fir::getForInductionVarOwner(mlir::Value val) { 1104 auto ivArg = val.dyn_cast<mlir::BlockArgument>(); 1105 if (!ivArg) 1106 return {}; 1107 assert(ivArg.getOwner() && "unlinked block argument"); 1108 auto *containingInst = ivArg.getOwner()->getParentOp(); 1109 return dyn_cast_or_null<fir::DoLoopOp>(containingInst); 1110 } 1111 1112 // Lifted from loop.loop 1113 static mlir::LogicalResult verify(fir::DoLoopOp op) { 1114 // Check that the body defines as single block argument for the induction 1115 // variable. 1116 auto *body = op.getBody(); 1117 if (!body->getArgument(0).getType().isIndex()) 1118 return op.emitOpError( 1119 "expected body first argument to be an index argument for " 1120 "the induction variable"); 1121 1122 auto opNumResults = op.getNumResults(); 1123 if (opNumResults == 0) 1124 return success(); 1125 1126 if (op.finalValue()) { 1127 if (op.unordered()) 1128 return op.emitOpError("unordered loop has no final value"); 1129 opNumResults--; 1130 } 1131 if (op.getNumIterOperands() != opNumResults) 1132 return op.emitOpError( 1133 "mismatch in number of loop-carried values and defined values"); 1134 if (op.getNumRegionIterArgs() != opNumResults) 1135 return op.emitOpError( 1136 "mismatch in number of basic block args and defined values"); 1137 auto iterOperands = op.getIterOperands(); 1138 auto iterArgs = op.getRegionIterArgs(); 1139 auto opResults = 1140 op.finalValue() ? op.getResults().drop_front() : op.getResults(); 1141 unsigned i = 0; 1142 for (auto e : llvm::zip(iterOperands, iterArgs, opResults)) { 1143 if (std::get<0>(e).getType() != std::get<2>(e).getType()) 1144 return op.emitOpError() << "types mismatch between " << i 1145 << "th iter operand and defined value"; 1146 if (std::get<1>(e).getType() != std::get<2>(e).getType()) 1147 return op.emitOpError() << "types mismatch between " << i 1148 << "th iter region arg and defined value"; 1149 1150 i++; 1151 } 1152 return success(); 1153 } 1154 1155 static void print(mlir::OpAsmPrinter &p, fir::DoLoopOp op) { 1156 bool printBlockTerminators = false; 1157 p << fir::DoLoopOp::getOperationName() << ' ' << op.getInductionVar() << " = " 1158 << op.lowerBound() << " to " << op.upperBound() << " step " << op.step(); 1159 if (op.unordered()) 1160 p << " unordered"; 1161 if (op.hasIterOperands()) { 1162 p << " iter_args("; 1163 auto regionArgs = op.getRegionIterArgs(); 1164 auto operands = op.getIterOperands(); 1165 llvm::interleaveComma(llvm::zip(regionArgs, operands), p, [&](auto it) { 1166 p << std::get<0>(it) << " = " << std::get<1>(it); 1167 }); 1168 p << ") -> (" << op.getResultTypes() << ')'; 1169 printBlockTerminators = true; 1170 } else if (op.finalValue()) { 1171 p << " -> " << op.getResultTypes(); 1172 printBlockTerminators = true; 1173 } 1174 p.printOptionalAttrDictWithKeyword(op->getAttrs(), 1175 {fir::DoLoopOp::unorderedAttrName(), 1176 fir::DoLoopOp::finalValueAttrName()}); 1177 p.printRegion(op.region(), /*printEntryBlockArgs=*/false, 1178 printBlockTerminators); 1179 } 1180 1181 mlir::Region &fir::DoLoopOp::getLoopBody() { return region(); } 1182 1183 bool fir::DoLoopOp::isDefinedOutsideOfLoop(mlir::Value value) { 1184 return !region().isAncestor(value.getParentRegion()); 1185 } 1186 1187 mlir::LogicalResult 1188 fir::DoLoopOp::moveOutOfLoop(llvm::ArrayRef<mlir::Operation *> ops) { 1189 for (auto op : ops) 1190 op->moveBefore(*this); 1191 return success(); 1192 } 1193 1194 /// Translate a value passed as an iter_arg to the corresponding block 1195 /// argument in the body of the loop. 1196 mlir::BlockArgument fir::DoLoopOp::iterArgToBlockArg(mlir::Value iterArg) { 1197 for (auto i : llvm::enumerate(initArgs())) 1198 if (iterArg == i.value()) 1199 return region().front().getArgument(i.index() + 1); 1200 return {}; 1201 } 1202 1203 /// Translate the result vector (by index number) to the corresponding value 1204 /// to the `fir.result` Op. 1205 void fir::DoLoopOp::resultToSourceOps( 1206 llvm::SmallVectorImpl<mlir::Value> &results, unsigned resultNum) { 1207 auto oper = finalValue() ? resultNum + 1 : resultNum; 1208 auto *term = region().front().getTerminator(); 1209 if (oper < term->getNumOperands()) 1210 results.push_back(term->getOperand(oper)); 1211 } 1212 1213 /// Translate the block argument (by index number) to the corresponding value 1214 /// passed as an iter_arg to the parent DoLoopOp. 1215 mlir::Value fir::DoLoopOp::blockArgToSourceOp(unsigned blockArgNum) { 1216 if (blockArgNum > 0 && blockArgNum <= initArgs().size()) 1217 return initArgs()[blockArgNum - 1]; 1218 return {}; 1219 } 1220 1221 //===----------------------------------------------------------------------===// 1222 // ReboxOp 1223 //===----------------------------------------------------------------------===// 1224 1225 /// Get the scalar type related to a fir.box type. 1226 /// Example: return f32 for !fir.box<!fir.heap<!fir.array<?x?xf32>>. 1227 static mlir::Type getBoxScalarEleTy(mlir::Type boxTy) { 1228 auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy); 1229 if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) 1230 return seqTy.getEleTy(); 1231 return eleTy; 1232 } 1233 1234 /// Get the rank from a !fir.box type 1235 static unsigned getBoxRank(mlir::Type boxTy) { 1236 auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy); 1237 if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) 1238 return seqTy.getDimension(); 1239 return 0; 1240 } 1241 1242 static mlir::LogicalResult verify(fir::ReboxOp op) { 1243 auto inputBoxTy = op.box().getType(); 1244 if (fir::isa_unknown_size_box(inputBoxTy)) 1245 return op.emitOpError("box operand must not have unknown rank or type"); 1246 auto outBoxTy = op.getType(); 1247 if (fir::isa_unknown_size_box(outBoxTy)) 1248 return op.emitOpError("result type must not have unknown rank or type"); 1249 auto inputRank = getBoxRank(inputBoxTy); 1250 auto inputEleTy = getBoxScalarEleTy(inputBoxTy); 1251 auto outRank = getBoxRank(outBoxTy); 1252 auto outEleTy = getBoxScalarEleTy(outBoxTy); 1253 1254 if (auto slice = op.slice()) { 1255 // Slicing case 1256 if (slice.getType().cast<fir::SliceType>().getRank() != inputRank) 1257 return op.emitOpError("slice operand rank must match box operand rank"); 1258 if (auto shape = op.shape()) { 1259 if (auto shiftTy = shape.getType().dyn_cast<fir::ShiftType>()) { 1260 if (shiftTy.getRank() != inputRank) 1261 return op.emitOpError("shape operand and input box ranks must match " 1262 "when there is a slice"); 1263 } else { 1264 return op.emitOpError("shape operand must absent or be a fir.shift " 1265 "when there is a slice"); 1266 } 1267 } 1268 if (auto sliceOp = slice.getDefiningOp()) { 1269 auto slicedRank = mlir::cast<fir::SliceOp>(sliceOp).getOutRank(); 1270 if (slicedRank != outRank) 1271 return op.emitOpError("result type rank and rank after applying slice " 1272 "operand must match"); 1273 } 1274 } else { 1275 // Reshaping case 1276 unsigned shapeRank = inputRank; 1277 if (auto shape = op.shape()) { 1278 auto ty = shape.getType(); 1279 if (auto shapeTy = ty.dyn_cast<fir::ShapeType>()) { 1280 shapeRank = shapeTy.getRank(); 1281 } else if (auto shapeShiftTy = ty.dyn_cast<fir::ShapeShiftType>()) { 1282 shapeRank = shapeShiftTy.getRank(); 1283 } else { 1284 auto shiftTy = ty.cast<fir::ShiftType>(); 1285 shapeRank = shiftTy.getRank(); 1286 if (shapeRank != inputRank) 1287 return op.emitOpError("shape operand and input box ranks must match " 1288 "when the shape is a fir.shift"); 1289 } 1290 } 1291 if (shapeRank != outRank) 1292 return op.emitOpError("result type and shape operand ranks must match"); 1293 } 1294 1295 if (inputEleTy != outEleTy) 1296 // TODO: check that outBoxTy is a parent type of inputBoxTy for derived 1297 // types. 1298 if (!inputEleTy.isa<fir::RecordType>()) 1299 return op.emitOpError( 1300 "op input and output element types must match for intrinsic types"); 1301 return mlir::success(); 1302 } 1303 1304 //===----------------------------------------------------------------------===// 1305 // ResultOp 1306 //===----------------------------------------------------------------------===// 1307 1308 static mlir::LogicalResult verify(fir::ResultOp op) { 1309 auto *parentOp = op->getParentOp(); 1310 auto results = parentOp->getResults(); 1311 auto operands = op->getOperands(); 1312 1313 if (parentOp->getNumResults() != op.getNumOperands()) 1314 return op.emitOpError() << "parent of result must have same arity"; 1315 for (auto e : llvm::zip(results, operands)) 1316 if (std::get<0>(e).getType() != std::get<1>(e).getType()) 1317 return op.emitOpError() 1318 << "types mismatch between result op and its parent"; 1319 return success(); 1320 } 1321 1322 //===----------------------------------------------------------------------===// 1323 // SelectOp 1324 //===----------------------------------------------------------------------===// 1325 1326 static constexpr llvm::StringRef getCompareOffsetAttr() { 1327 return "compare_operand_offsets"; 1328 } 1329 1330 static constexpr llvm::StringRef getTargetOffsetAttr() { 1331 return "target_operand_offsets"; 1332 } 1333 1334 template <typename A, typename... AdditionalArgs> 1335 static A getSubOperands(unsigned pos, A allArgs, 1336 mlir::DenseIntElementsAttr ranges, 1337 AdditionalArgs &&... additionalArgs) { 1338 unsigned start = 0; 1339 for (unsigned i = 0; i < pos; ++i) 1340 start += (*(ranges.begin() + i)).getZExtValue(); 1341 return allArgs.slice(start, (*(ranges.begin() + pos)).getZExtValue(), 1342 std::forward<AdditionalArgs>(additionalArgs)...); 1343 } 1344 1345 static mlir::MutableOperandRange 1346 getMutableSuccessorOperands(unsigned pos, mlir::MutableOperandRange operands, 1347 StringRef offsetAttr) { 1348 Operation *owner = operands.getOwner(); 1349 NamedAttribute targetOffsetAttr = 1350 *owner->getAttrDictionary().getNamed(offsetAttr); 1351 return getSubOperands( 1352 pos, operands, targetOffsetAttr.second.cast<DenseIntElementsAttr>(), 1353 mlir::MutableOperandRange::OperandSegment(pos, targetOffsetAttr)); 1354 } 1355 1356 static unsigned denseElementsSize(mlir::DenseIntElementsAttr attr) { 1357 return attr.getNumElements(); 1358 } 1359 1360 llvm::Optional<mlir::OperandRange> fir::SelectOp::getCompareOperands(unsigned) { 1361 return {}; 1362 } 1363 1364 llvm::Optional<llvm::ArrayRef<mlir::Value>> 1365 fir::SelectOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) { 1366 return {}; 1367 } 1368 1369 llvm::Optional<mlir::MutableOperandRange> 1370 fir::SelectOp::getMutableSuccessorOperands(unsigned oper) { 1371 return ::getMutableSuccessorOperands(oper, targetArgsMutable(), 1372 getTargetOffsetAttr()); 1373 } 1374 1375 llvm::Optional<llvm::ArrayRef<mlir::Value>> 1376 fir::SelectOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands, 1377 unsigned oper) { 1378 auto a = 1379 (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr()); 1380 auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 1381 getOperandSegmentSizeAttr()); 1382 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)}; 1383 } 1384 1385 unsigned fir::SelectOp::targetOffsetSize() { 1386 return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 1387 getTargetOffsetAttr())); 1388 } 1389 1390 //===----------------------------------------------------------------------===// 1391 // SelectCaseOp 1392 //===----------------------------------------------------------------------===// 1393 1394 llvm::Optional<mlir::OperandRange> 1395 fir::SelectCaseOp::getCompareOperands(unsigned cond) { 1396 auto a = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 1397 getCompareOffsetAttr()); 1398 return {getSubOperands(cond, compareArgs(), a)}; 1399 } 1400 1401 llvm::Optional<llvm::ArrayRef<mlir::Value>> 1402 fir::SelectCaseOp::getCompareOperands(llvm::ArrayRef<mlir::Value> operands, 1403 unsigned cond) { 1404 auto a = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 1405 getCompareOffsetAttr()); 1406 auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 1407 getOperandSegmentSizeAttr()); 1408 return {getSubOperands(cond, getSubOperands(1, operands, segments), a)}; 1409 } 1410 1411 llvm::Optional<mlir::MutableOperandRange> 1412 fir::SelectCaseOp::getMutableSuccessorOperands(unsigned oper) { 1413 return ::getMutableSuccessorOperands(oper, targetArgsMutable(), 1414 getTargetOffsetAttr()); 1415 } 1416 1417 llvm::Optional<llvm::ArrayRef<mlir::Value>> 1418 fir::SelectCaseOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands, 1419 unsigned oper) { 1420 auto a = 1421 (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr()); 1422 auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 1423 getOperandSegmentSizeAttr()); 1424 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)}; 1425 } 1426 1427 // parser for fir.select_case Op 1428 static mlir::ParseResult parseSelectCase(mlir::OpAsmParser &parser, 1429 mlir::OperationState &result) { 1430 mlir::OpAsmParser::OperandType selector; 1431 mlir::Type type; 1432 if (parseSelector(parser, result, selector, type)) 1433 return mlir::failure(); 1434 1435 llvm::SmallVector<mlir::Attribute, 8> attrs; 1436 llvm::SmallVector<mlir::OpAsmParser::OperandType, 8> opers; 1437 llvm::SmallVector<mlir::Block *, 8> dests; 1438 llvm::SmallVector<llvm::SmallVector<mlir::Value, 8>, 8> destArgs; 1439 llvm::SmallVector<int32_t, 8> argOffs; 1440 int32_t offSize = 0; 1441 while (true) { 1442 mlir::Attribute attr; 1443 mlir::Block *dest; 1444 llvm::SmallVector<mlir::Value, 8> destArg; 1445 mlir::NamedAttrList temp; 1446 if (parser.parseAttribute(attr, "a", temp) || isValidCaseAttr(attr) || 1447 parser.parseComma()) 1448 return mlir::failure(); 1449 attrs.push_back(attr); 1450 if (attr.dyn_cast_or_null<mlir::UnitAttr>()) { 1451 argOffs.push_back(0); 1452 } else if (attr.dyn_cast_or_null<fir::ClosedIntervalAttr>()) { 1453 mlir::OpAsmParser::OperandType oper1; 1454 mlir::OpAsmParser::OperandType oper2; 1455 if (parser.parseOperand(oper1) || parser.parseComma() || 1456 parser.parseOperand(oper2) || parser.parseComma()) 1457 return mlir::failure(); 1458 opers.push_back(oper1); 1459 opers.push_back(oper2); 1460 argOffs.push_back(2); 1461 offSize += 2; 1462 } else { 1463 mlir::OpAsmParser::OperandType oper; 1464 if (parser.parseOperand(oper) || parser.parseComma()) 1465 return mlir::failure(); 1466 opers.push_back(oper); 1467 argOffs.push_back(1); 1468 ++offSize; 1469 } 1470 if (parser.parseSuccessorAndUseList(dest, destArg)) 1471 return mlir::failure(); 1472 dests.push_back(dest); 1473 destArgs.push_back(destArg); 1474 if (mlir::succeeded(parser.parseOptionalRSquare())) 1475 break; 1476 if (parser.parseComma()) 1477 return mlir::failure(); 1478 } 1479 result.addAttribute(fir::SelectCaseOp::getCasesAttr(), 1480 parser.getBuilder().getArrayAttr(attrs)); 1481 if (parser.resolveOperands(opers, type, result.operands)) 1482 return mlir::failure(); 1483 llvm::SmallVector<int32_t, 8> targOffs; 1484 int32_t toffSize = 0; 1485 const auto count = dests.size(); 1486 for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) { 1487 result.addSuccessors(dests[i]); 1488 result.addOperands(destArgs[i]); 1489 auto argSize = destArgs[i].size(); 1490 targOffs.push_back(argSize); 1491 toffSize += argSize; 1492 } 1493 auto &bld = parser.getBuilder(); 1494 result.addAttribute(fir::SelectCaseOp::getOperandSegmentSizeAttr(), 1495 bld.getI32VectorAttr({1, offSize, toffSize})); 1496 result.addAttribute(getCompareOffsetAttr(), bld.getI32VectorAttr(argOffs)); 1497 result.addAttribute(getTargetOffsetAttr(), bld.getI32VectorAttr(targOffs)); 1498 return mlir::success(); 1499 } 1500 1501 unsigned fir::SelectCaseOp::compareOffsetSize() { 1502 return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 1503 getCompareOffsetAttr())); 1504 } 1505 1506 unsigned fir::SelectCaseOp::targetOffsetSize() { 1507 return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 1508 getTargetOffsetAttr())); 1509 } 1510 1511 void fir::SelectCaseOp::build(mlir::OpBuilder &builder, 1512 mlir::OperationState &result, 1513 mlir::Value selector, 1514 llvm::ArrayRef<mlir::Attribute> compareAttrs, 1515 llvm::ArrayRef<mlir::ValueRange> cmpOperands, 1516 llvm::ArrayRef<mlir::Block *> destinations, 1517 llvm::ArrayRef<mlir::ValueRange> destOperands, 1518 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 1519 result.addOperands(selector); 1520 result.addAttribute(getCasesAttr(), builder.getArrayAttr(compareAttrs)); 1521 llvm::SmallVector<int32_t, 8> operOffs; 1522 int32_t operSize = 0; 1523 for (auto attr : compareAttrs) { 1524 if (attr.isa<fir::ClosedIntervalAttr>()) { 1525 operOffs.push_back(2); 1526 operSize += 2; 1527 } else if (attr.isa<mlir::UnitAttr>()) { 1528 operOffs.push_back(0); 1529 } else { 1530 operOffs.push_back(1); 1531 ++operSize; 1532 } 1533 } 1534 for (auto ops : cmpOperands) 1535 result.addOperands(ops); 1536 result.addAttribute(getCompareOffsetAttr(), 1537 builder.getI32VectorAttr(operOffs)); 1538 const auto count = destinations.size(); 1539 for (auto d : destinations) 1540 result.addSuccessors(d); 1541 const auto opCount = destOperands.size(); 1542 llvm::SmallVector<int32_t, 8> argOffs; 1543 int32_t sumArgs = 0; 1544 for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) { 1545 if (i < opCount) { 1546 result.addOperands(destOperands[i]); 1547 const auto argSz = destOperands[i].size(); 1548 argOffs.push_back(argSz); 1549 sumArgs += argSz; 1550 } else { 1551 argOffs.push_back(0); 1552 } 1553 } 1554 result.addAttribute(getOperandSegmentSizeAttr(), 1555 builder.getI32VectorAttr({1, operSize, sumArgs})); 1556 result.addAttribute(getTargetOffsetAttr(), builder.getI32VectorAttr(argOffs)); 1557 result.addAttributes(attributes); 1558 } 1559 1560 /// This builder has a slightly simplified interface in that the list of 1561 /// operands need not be partitioned by the builder. Instead the operands are 1562 /// partitioned here, before being passed to the default builder. This 1563 /// partitioning is unchecked, so can go awry on bad input. 1564 void fir::SelectCaseOp::build(mlir::OpBuilder &builder, 1565 mlir::OperationState &result, 1566 mlir::Value selector, 1567 llvm::ArrayRef<mlir::Attribute> compareAttrs, 1568 llvm::ArrayRef<mlir::Value> cmpOpList, 1569 llvm::ArrayRef<mlir::Block *> destinations, 1570 llvm::ArrayRef<mlir::ValueRange> destOperands, 1571 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 1572 llvm::SmallVector<mlir::ValueRange, 16> cmpOpers; 1573 auto iter = cmpOpList.begin(); 1574 for (auto &attr : compareAttrs) { 1575 if (attr.isa<fir::ClosedIntervalAttr>()) { 1576 cmpOpers.push_back(mlir::ValueRange({iter, iter + 2})); 1577 iter += 2; 1578 } else if (attr.isa<UnitAttr>()) { 1579 cmpOpers.push_back(mlir::ValueRange{}); 1580 } else { 1581 cmpOpers.push_back(mlir::ValueRange({iter, iter + 1})); 1582 ++iter; 1583 } 1584 } 1585 build(builder, result, selector, compareAttrs, cmpOpers, destinations, 1586 destOperands, attributes); 1587 } 1588 1589 //===----------------------------------------------------------------------===// 1590 // SelectRankOp 1591 //===----------------------------------------------------------------------===// 1592 1593 llvm::Optional<mlir::OperandRange> 1594 fir::SelectRankOp::getCompareOperands(unsigned) { 1595 return {}; 1596 } 1597 1598 llvm::Optional<llvm::ArrayRef<mlir::Value>> 1599 fir::SelectRankOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) { 1600 return {}; 1601 } 1602 1603 llvm::Optional<mlir::MutableOperandRange> 1604 fir::SelectRankOp::getMutableSuccessorOperands(unsigned oper) { 1605 return ::getMutableSuccessorOperands(oper, targetArgsMutable(), 1606 getTargetOffsetAttr()); 1607 } 1608 1609 llvm::Optional<llvm::ArrayRef<mlir::Value>> 1610 fir::SelectRankOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands, 1611 unsigned oper) { 1612 auto a = 1613 (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr()); 1614 auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 1615 getOperandSegmentSizeAttr()); 1616 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)}; 1617 } 1618 1619 unsigned fir::SelectRankOp::targetOffsetSize() { 1620 return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 1621 getTargetOffsetAttr())); 1622 } 1623 1624 //===----------------------------------------------------------------------===// 1625 // SelectTypeOp 1626 //===----------------------------------------------------------------------===// 1627 1628 llvm::Optional<mlir::OperandRange> 1629 fir::SelectTypeOp::getCompareOperands(unsigned) { 1630 return {}; 1631 } 1632 1633 llvm::Optional<llvm::ArrayRef<mlir::Value>> 1634 fir::SelectTypeOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) { 1635 return {}; 1636 } 1637 1638 llvm::Optional<mlir::MutableOperandRange> 1639 fir::SelectTypeOp::getMutableSuccessorOperands(unsigned oper) { 1640 return ::getMutableSuccessorOperands(oper, targetArgsMutable(), 1641 getTargetOffsetAttr()); 1642 } 1643 1644 llvm::Optional<llvm::ArrayRef<mlir::Value>> 1645 fir::SelectTypeOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands, 1646 unsigned oper) { 1647 auto a = 1648 (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr()); 1649 auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 1650 getOperandSegmentSizeAttr()); 1651 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)}; 1652 } 1653 1654 static ParseResult parseSelectType(OpAsmParser &parser, 1655 OperationState &result) { 1656 mlir::OpAsmParser::OperandType selector; 1657 mlir::Type type; 1658 if (parseSelector(parser, result, selector, type)) 1659 return mlir::failure(); 1660 1661 llvm::SmallVector<mlir::Attribute, 8> attrs; 1662 llvm::SmallVector<mlir::Block *, 8> dests; 1663 llvm::SmallVector<llvm::SmallVector<mlir::Value, 8>, 8> destArgs; 1664 while (true) { 1665 mlir::Attribute attr; 1666 mlir::Block *dest; 1667 llvm::SmallVector<mlir::Value, 8> destArg; 1668 mlir::NamedAttrList temp; 1669 if (parser.parseAttribute(attr, "a", temp) || parser.parseComma() || 1670 parser.parseSuccessorAndUseList(dest, destArg)) 1671 return mlir::failure(); 1672 attrs.push_back(attr); 1673 dests.push_back(dest); 1674 destArgs.push_back(destArg); 1675 if (mlir::succeeded(parser.parseOptionalRSquare())) 1676 break; 1677 if (parser.parseComma()) 1678 return mlir::failure(); 1679 } 1680 auto &bld = parser.getBuilder(); 1681 result.addAttribute(fir::SelectTypeOp::getCasesAttr(), 1682 bld.getArrayAttr(attrs)); 1683 llvm::SmallVector<int32_t, 8> argOffs; 1684 int32_t offSize = 0; 1685 const auto count = dests.size(); 1686 for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) { 1687 result.addSuccessors(dests[i]); 1688 result.addOperands(destArgs[i]); 1689 auto argSize = destArgs[i].size(); 1690 argOffs.push_back(argSize); 1691 offSize += argSize; 1692 } 1693 result.addAttribute(fir::SelectTypeOp::getOperandSegmentSizeAttr(), 1694 bld.getI32VectorAttr({1, 0, offSize})); 1695 result.addAttribute(getTargetOffsetAttr(), bld.getI32VectorAttr(argOffs)); 1696 return mlir::success(); 1697 } 1698 1699 unsigned fir::SelectTypeOp::targetOffsetSize() { 1700 return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 1701 getTargetOffsetAttr())); 1702 } 1703 1704 //===----------------------------------------------------------------------===// 1705 // SliceOp 1706 //===----------------------------------------------------------------------===// 1707 1708 /// Return the output rank of a slice op. The output rank must be between 1 and 1709 /// the rank of the array being sliced (inclusive). 1710 unsigned fir::SliceOp::getOutputRank(mlir::ValueRange triples) { 1711 unsigned rank = 0; 1712 if (!triples.empty()) { 1713 for (unsigned i = 1, end = triples.size(); i < end; i += 3) { 1714 auto op = triples[i].getDefiningOp(); 1715 if (!mlir::isa_and_nonnull<fir::UndefOp>(op)) 1716 ++rank; 1717 } 1718 assert(rank > 0); 1719 } 1720 return rank; 1721 } 1722 1723 //===----------------------------------------------------------------------===// 1724 // StoreOp 1725 //===----------------------------------------------------------------------===// 1726 1727 mlir::Type fir::StoreOp::elementType(mlir::Type refType) { 1728 if (auto ref = refType.dyn_cast<ReferenceType>()) 1729 return ref.getEleTy(); 1730 if (auto ref = refType.dyn_cast<PointerType>()) 1731 return ref.getEleTy(); 1732 if (auto ref = refType.dyn_cast<HeapType>()) 1733 return ref.getEleTy(); 1734 return {}; 1735 } 1736 1737 //===----------------------------------------------------------------------===// 1738 // StringLitOp 1739 //===----------------------------------------------------------------------===// 1740 1741 bool fir::StringLitOp::isWideValue() { 1742 auto eleTy = getType().cast<fir::SequenceType>().getEleTy(); 1743 return eleTy.cast<fir::CharacterType>().getFKind() != 1; 1744 } 1745 1746 //===----------------------------------------------------------------------===// 1747 // IfOp 1748 //===----------------------------------------------------------------------===// 1749 1750 void fir::IfOp::build(mlir::OpBuilder &builder, OperationState &result, 1751 mlir::Value cond, bool withElseRegion) { 1752 build(builder, result, llvm::None, cond, withElseRegion); 1753 } 1754 1755 void fir::IfOp::build(mlir::OpBuilder &builder, OperationState &result, 1756 mlir::TypeRange resultTypes, mlir::Value cond, 1757 bool withElseRegion) { 1758 result.addOperands(cond); 1759 result.addTypes(resultTypes); 1760 1761 mlir::Region *thenRegion = result.addRegion(); 1762 thenRegion->push_back(new mlir::Block()); 1763 if (resultTypes.empty()) 1764 IfOp::ensureTerminator(*thenRegion, builder, result.location); 1765 1766 mlir::Region *elseRegion = result.addRegion(); 1767 if (withElseRegion) { 1768 elseRegion->push_back(new mlir::Block()); 1769 if (resultTypes.empty()) 1770 IfOp::ensureTerminator(*elseRegion, builder, result.location); 1771 } 1772 } 1773 1774 static mlir::ParseResult parseIfOp(OpAsmParser &parser, 1775 OperationState &result) { 1776 result.regions.reserve(2); 1777 mlir::Region *thenRegion = result.addRegion(); 1778 mlir::Region *elseRegion = result.addRegion(); 1779 1780 auto &builder = parser.getBuilder(); 1781 OpAsmParser::OperandType cond; 1782 mlir::Type i1Type = builder.getIntegerType(1); 1783 if (parser.parseOperand(cond) || 1784 parser.resolveOperand(cond, i1Type, result.operands)) 1785 return mlir::failure(); 1786 1787 if (parser.parseOptionalArrowTypeList(result.types)) 1788 return mlir::failure(); 1789 1790 if (parser.parseRegion(*thenRegion, {}, {})) 1791 return mlir::failure(); 1792 IfOp::ensureTerminator(*thenRegion, parser.getBuilder(), result.location); 1793 1794 if (mlir::succeeded(parser.parseOptionalKeyword("else"))) { 1795 if (parser.parseRegion(*elseRegion, {}, {})) 1796 return mlir::failure(); 1797 IfOp::ensureTerminator(*elseRegion, parser.getBuilder(), result.location); 1798 } 1799 1800 // Parse the optional attribute list. 1801 if (parser.parseOptionalAttrDict(result.attributes)) 1802 return mlir::failure(); 1803 return mlir::success(); 1804 } 1805 1806 static LogicalResult verify(fir::IfOp op) { 1807 if (op.getNumResults() != 0 && op.elseRegion().empty()) 1808 return op.emitOpError("must have an else block if defining values"); 1809 1810 return mlir::success(); 1811 } 1812 1813 static void print(mlir::OpAsmPrinter &p, fir::IfOp op) { 1814 bool printBlockTerminators = false; 1815 p << fir::IfOp::getOperationName() << ' ' << op.condition(); 1816 if (!op.results().empty()) { 1817 p << " -> (" << op.getResultTypes() << ')'; 1818 printBlockTerminators = true; 1819 } 1820 p.printRegion(op.thenRegion(), /*printEntryBlockArgs=*/false, 1821 printBlockTerminators); 1822 1823 // Print the 'else' regions if it exists and has a block. 1824 auto &otherReg = op.elseRegion(); 1825 if (!otherReg.empty()) { 1826 p << " else"; 1827 p.printRegion(otherReg, /*printEntryBlockArgs=*/false, 1828 printBlockTerminators); 1829 } 1830 p.printOptionalAttrDict(op->getAttrs()); 1831 } 1832 1833 void fir::IfOp::resultToSourceOps(llvm::SmallVectorImpl<mlir::Value> &results, 1834 unsigned resultNum) { 1835 auto *term = thenRegion().front().getTerminator(); 1836 if (resultNum < term->getNumOperands()) 1837 results.push_back(term->getOperand(resultNum)); 1838 term = elseRegion().front().getTerminator(); 1839 if (resultNum < term->getNumOperands()) 1840 results.push_back(term->getOperand(resultNum)); 1841 } 1842 1843 //===----------------------------------------------------------------------===// 1844 1845 mlir::ParseResult fir::isValidCaseAttr(mlir::Attribute attr) { 1846 if (attr.dyn_cast_or_null<mlir::UnitAttr>() || 1847 attr.dyn_cast_or_null<ClosedIntervalAttr>() || 1848 attr.dyn_cast_or_null<PointIntervalAttr>() || 1849 attr.dyn_cast_or_null<LowerBoundAttr>() || 1850 attr.dyn_cast_or_null<UpperBoundAttr>()) 1851 return mlir::success(); 1852 return mlir::failure(); 1853 } 1854 1855 unsigned fir::getCaseArgumentOffset(llvm::ArrayRef<mlir::Attribute> cases, 1856 unsigned dest) { 1857 unsigned o = 0; 1858 for (unsigned i = 0; i < dest; ++i) { 1859 auto &attr = cases[i]; 1860 if (!attr.dyn_cast_or_null<mlir::UnitAttr>()) { 1861 ++o; 1862 if (attr.dyn_cast_or_null<ClosedIntervalAttr>()) 1863 ++o; 1864 } 1865 } 1866 return o; 1867 } 1868 1869 mlir::ParseResult fir::parseSelector(mlir::OpAsmParser &parser, 1870 mlir::OperationState &result, 1871 mlir::OpAsmParser::OperandType &selector, 1872 mlir::Type &type) { 1873 if (parser.parseOperand(selector) || parser.parseColonType(type) || 1874 parser.resolveOperand(selector, type, result.operands) || 1875 parser.parseLSquare()) 1876 return mlir::failure(); 1877 return mlir::success(); 1878 } 1879 1880 /// Generic pretty-printer of a binary operation 1881 static void printBinaryOp(Operation *op, OpAsmPrinter &p) { 1882 assert(op->getNumOperands() == 2 && "binary op must have two operands"); 1883 assert(op->getNumResults() == 1 && "binary op must have one result"); 1884 1885 p << op->getName() << ' ' << op->getOperand(0) << ", " << op->getOperand(1); 1886 p.printOptionalAttrDict(op->getAttrs()); 1887 p << " : " << op->getResult(0).getType(); 1888 } 1889 1890 /// Generic pretty-printer of an unary operation 1891 static void printUnaryOp(Operation *op, OpAsmPrinter &p) { 1892 assert(op->getNumOperands() == 1 && "unary op must have one operand"); 1893 assert(op->getNumResults() == 1 && "unary op must have one result"); 1894 1895 p << op->getName() << ' ' << op->getOperand(0); 1896 p.printOptionalAttrDict(op->getAttrs()); 1897 p << " : " << op->getResult(0).getType(); 1898 } 1899 1900 bool fir::isReferenceLike(mlir::Type type) { 1901 return type.isa<fir::ReferenceType>() || type.isa<fir::HeapType>() || 1902 type.isa<fir::PointerType>(); 1903 } 1904 1905 mlir::FuncOp fir::createFuncOp(mlir::Location loc, mlir::ModuleOp module, 1906 StringRef name, mlir::FunctionType type, 1907 llvm::ArrayRef<mlir::NamedAttribute> attrs) { 1908 if (auto f = module.lookupSymbol<mlir::FuncOp>(name)) 1909 return f; 1910 mlir::OpBuilder modBuilder(module.getBodyRegion()); 1911 modBuilder.setInsertionPoint(module.getBody()->getTerminator()); 1912 auto result = modBuilder.create<mlir::FuncOp>(loc, name, type, attrs); 1913 result.setVisibility(mlir::SymbolTable::Visibility::Private); 1914 return result; 1915 } 1916 1917 fir::GlobalOp fir::createGlobalOp(mlir::Location loc, mlir::ModuleOp module, 1918 StringRef name, mlir::Type type, 1919 llvm::ArrayRef<mlir::NamedAttribute> attrs) { 1920 if (auto g = module.lookupSymbol<fir::GlobalOp>(name)) 1921 return g; 1922 mlir::OpBuilder modBuilder(module.getBodyRegion()); 1923 auto result = modBuilder.create<fir::GlobalOp>(loc, name, type, attrs); 1924 result.setVisibility(mlir::SymbolTable::Visibility::Private); 1925 return result; 1926 } 1927 1928 bool fir::valueHasFirAttribute(mlir::Value value, 1929 llvm::StringRef attributeName) { 1930 // If this is a fir.box that was loaded, the fir attributes will be on the 1931 // related fir.ref<fir.box> creation. 1932 if (value.getType().isa<fir::BoxType>()) 1933 if (auto definingOp = value.getDefiningOp()) 1934 if (auto loadOp = mlir::dyn_cast<fir::LoadOp>(definingOp)) 1935 value = loadOp.memref(); 1936 // If this is a function argument, look in the argument attributes. 1937 if (auto blockArg = value.dyn_cast<mlir::BlockArgument>()) { 1938 if (blockArg.getOwner() && blockArg.getOwner()->isEntryBlock()) 1939 if (auto funcOp = 1940 mlir::dyn_cast<mlir::FuncOp>(blockArg.getOwner()->getParentOp())) 1941 if (funcOp.getArgAttr(blockArg.getArgNumber(), attributeName)) 1942 return true; 1943 return false; 1944 } 1945 1946 if (auto definingOp = value.getDefiningOp()) { 1947 // If this is an allocated value, look at the allocation attributes. 1948 if (mlir::isa<fir::AllocMemOp>(definingOp) || 1949 mlir::isa<AllocaOp>(definingOp)) 1950 return definingOp->hasAttr(attributeName); 1951 // If this is an imported global, look at AddrOfOp and GlobalOp attributes. 1952 // Both operations are looked at because use/host associated variable (the 1953 // AddrOfOp) can have ASYNCHRONOUS/VOLATILE attributes even if the ultimate 1954 // entity (the globalOp) does not have them. 1955 if (auto addressOfOp = mlir::dyn_cast<fir::AddrOfOp>(definingOp)) { 1956 if (addressOfOp->hasAttr(attributeName)) 1957 return true; 1958 if (auto module = definingOp->getParentOfType<mlir::ModuleOp>()) 1959 if (auto globalOp = 1960 module.lookupSymbol<fir::GlobalOp>(addressOfOp.symbol())) 1961 return globalOp->hasAttr(attributeName); 1962 } 1963 } 1964 // TODO: Construct associated entities attributes. Decide where the fir 1965 // attributes must be placed/looked for in this case. 1966 return false; 1967 } 1968 1969 // Tablegen operators 1970 1971 #define GET_OP_CLASSES 1972 #include "flang/Optimizer/Dialect/FIROps.cpp.inc" 1973