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 "flang/Optimizer/Support/Utils.h" 18 #include "mlir/Dialect/CommonFolders.h" 19 #include "mlir/Dialect/Func/IR/FuncOps.h" 20 #include "mlir/IR/BuiltinAttributes.h" 21 #include "mlir/IR/BuiltinOps.h" 22 #include "mlir/IR/Diagnostics.h" 23 #include "mlir/IR/Matchers.h" 24 #include "mlir/IR/OpDefinition.h" 25 #include "mlir/IR/PatternMatch.h" 26 #include "llvm/ADT/STLExtras.h" 27 #include "llvm/ADT/SmallVector.h" 28 #include "llvm/ADT/StringSwitch.h" 29 #include "llvm/ADT/TypeSwitch.h" 30 31 namespace { 32 #include "flang/Optimizer/Dialect/CanonicalizationPatterns.inc" 33 } // namespace 34 using namespace fir; 35 using namespace mlir; 36 37 /// Return true if a sequence type is of some incomplete size or a record type 38 /// is malformed or contains an incomplete sequence type. An incomplete sequence 39 /// type is one with more unknown extents in the type than have been provided 40 /// via `dynamicExtents`. Sequence types with an unknown rank are incomplete by 41 /// definition. 42 static bool verifyInType(mlir::Type inType, 43 llvm::SmallVectorImpl<llvm::StringRef> &visited, 44 unsigned dynamicExtents = 0) { 45 if (auto st = inType.dyn_cast<fir::SequenceType>()) { 46 auto shape = st.getShape(); 47 if (shape.size() == 0) 48 return true; 49 for (std::size_t i = 0, end{shape.size()}; i < end; ++i) { 50 if (shape[i] != fir::SequenceType::getUnknownExtent()) 51 continue; 52 if (dynamicExtents-- == 0) 53 return true; 54 } 55 } else if (auto rt = inType.dyn_cast<fir::RecordType>()) { 56 // don't recurse if we're already visiting this one 57 if (llvm::is_contained(visited, rt.getName())) 58 return false; 59 // keep track of record types currently being visited 60 visited.push_back(rt.getName()); 61 for (auto &field : rt.getTypeList()) 62 if (verifyInType(field.second, visited)) 63 return true; 64 visited.pop_back(); 65 } 66 return false; 67 } 68 69 static bool verifyTypeParamCount(mlir::Type inType, unsigned numParams) { 70 auto ty = fir::unwrapSequenceType(inType); 71 if (numParams > 0) { 72 if (auto recTy = ty.dyn_cast<fir::RecordType>()) 73 return numParams != recTy.getNumLenParams(); 74 if (auto chrTy = ty.dyn_cast<fir::CharacterType>()) 75 return !(numParams == 1 && chrTy.hasDynamicLen()); 76 return true; 77 } 78 if (auto chrTy = ty.dyn_cast<fir::CharacterType>()) 79 return !chrTy.hasConstantLen(); 80 return false; 81 } 82 83 /// Parser shared by Alloca and Allocmem 84 /// 85 /// operation ::= %res = (`fir.alloca` | `fir.allocmem`) $in_type 86 /// ( `(` $typeparams `)` )? ( `,` $shape )? 87 /// attr-dict-without-keyword 88 template <typename FN> 89 static mlir::ParseResult parseAllocatableOp(FN wrapResultType, 90 mlir::OpAsmParser &parser, 91 mlir::OperationState &result) { 92 mlir::Type intype; 93 if (parser.parseType(intype)) 94 return mlir::failure(); 95 auto &builder = parser.getBuilder(); 96 result.addAttribute("in_type", mlir::TypeAttr::get(intype)); 97 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> operands; 98 llvm::SmallVector<mlir::Type> typeVec; 99 bool hasOperands = false; 100 std::int32_t typeparamsSize = 0; 101 if (!parser.parseOptionalLParen()) { 102 // parse the LEN params of the derived type. (<params> : <types>) 103 if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::None) || 104 parser.parseColonTypeList(typeVec) || parser.parseRParen()) 105 return mlir::failure(); 106 typeparamsSize = operands.size(); 107 hasOperands = true; 108 } 109 std::int32_t shapeSize = 0; 110 if (!parser.parseOptionalComma()) { 111 // parse size to scale by, vector of n dimensions of type index 112 if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::None)) 113 return mlir::failure(); 114 shapeSize = operands.size() - typeparamsSize; 115 auto idxTy = builder.getIndexType(); 116 for (std::int32_t i = typeparamsSize, end = operands.size(); i != end; ++i) 117 typeVec.push_back(idxTy); 118 hasOperands = true; 119 } 120 if (hasOperands && 121 parser.resolveOperands(operands, typeVec, parser.getNameLoc(), 122 result.operands)) 123 return mlir::failure(); 124 mlir::Type restype = wrapResultType(intype); 125 if (!restype) { 126 parser.emitError(parser.getNameLoc(), "invalid allocate type: ") << intype; 127 return mlir::failure(); 128 } 129 result.addAttribute("operand_segment_sizes", 130 builder.getI32VectorAttr({typeparamsSize, shapeSize})); 131 if (parser.parseOptionalAttrDict(result.attributes) || 132 parser.addTypeToList(restype, result.types)) 133 return mlir::failure(); 134 return mlir::success(); 135 } 136 137 template <typename OP> 138 static void printAllocatableOp(mlir::OpAsmPrinter &p, OP &op) { 139 p << ' ' << op.getInType(); 140 if (!op.getTypeparams().empty()) { 141 p << '(' << op.getTypeparams() << " : " << op.getTypeparams().getTypes() 142 << ')'; 143 } 144 // print the shape of the allocation (if any); all must be index type 145 for (auto sh : op.getShape()) { 146 p << ", "; 147 p.printOperand(sh); 148 } 149 p.printOptionalAttrDict(op->getAttrs(), {"in_type", "operand_segment_sizes"}); 150 } 151 152 //===----------------------------------------------------------------------===// 153 // AllocaOp 154 //===----------------------------------------------------------------------===// 155 156 /// Create a legal memory reference as return type 157 static mlir::Type wrapAllocaResultType(mlir::Type intype) { 158 // FIR semantics: memory references to memory references are disallowed 159 if (intype.isa<ReferenceType>()) 160 return {}; 161 return ReferenceType::get(intype); 162 } 163 164 mlir::Type fir::AllocaOp::getAllocatedType() { 165 return getType().cast<ReferenceType>().getEleTy(); 166 } 167 168 mlir::Type fir::AllocaOp::getRefTy(mlir::Type ty) { 169 return ReferenceType::get(ty); 170 } 171 172 void fir::AllocaOp::build(mlir::OpBuilder &builder, 173 mlir::OperationState &result, mlir::Type inType, 174 llvm::StringRef uniqName, mlir::ValueRange typeparams, 175 mlir::ValueRange shape, 176 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 177 auto nameAttr = builder.getStringAttr(uniqName); 178 build(builder, result, wrapAllocaResultType(inType), inType, nameAttr, {}, 179 /*pinned=*/false, typeparams, shape); 180 result.addAttributes(attributes); 181 } 182 183 void fir::AllocaOp::build(mlir::OpBuilder &builder, 184 mlir::OperationState &result, mlir::Type inType, 185 llvm::StringRef uniqName, bool pinned, 186 mlir::ValueRange typeparams, mlir::ValueRange shape, 187 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 188 auto nameAttr = builder.getStringAttr(uniqName); 189 build(builder, result, wrapAllocaResultType(inType), inType, nameAttr, {}, 190 pinned, typeparams, shape); 191 result.addAttributes(attributes); 192 } 193 194 void fir::AllocaOp::build(mlir::OpBuilder &builder, 195 mlir::OperationState &result, mlir::Type inType, 196 llvm::StringRef uniqName, llvm::StringRef bindcName, 197 mlir::ValueRange typeparams, mlir::ValueRange shape, 198 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 199 auto nameAttr = 200 uniqName.empty() ? mlir::StringAttr{} : builder.getStringAttr(uniqName); 201 auto bindcAttr = 202 bindcName.empty() ? mlir::StringAttr{} : builder.getStringAttr(bindcName); 203 build(builder, result, wrapAllocaResultType(inType), inType, nameAttr, 204 bindcAttr, /*pinned=*/false, typeparams, shape); 205 result.addAttributes(attributes); 206 } 207 208 void fir::AllocaOp::build(mlir::OpBuilder &builder, 209 mlir::OperationState &result, mlir::Type inType, 210 llvm::StringRef uniqName, llvm::StringRef bindcName, 211 bool pinned, mlir::ValueRange typeparams, 212 mlir::ValueRange shape, 213 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 214 auto nameAttr = 215 uniqName.empty() ? mlir::StringAttr{} : builder.getStringAttr(uniqName); 216 auto bindcAttr = 217 bindcName.empty() ? mlir::StringAttr{} : builder.getStringAttr(bindcName); 218 build(builder, result, wrapAllocaResultType(inType), inType, nameAttr, 219 bindcAttr, pinned, typeparams, shape); 220 result.addAttributes(attributes); 221 } 222 223 void fir::AllocaOp::build(mlir::OpBuilder &builder, 224 mlir::OperationState &result, mlir::Type inType, 225 mlir::ValueRange typeparams, mlir::ValueRange shape, 226 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 227 build(builder, result, wrapAllocaResultType(inType), inType, {}, {}, 228 /*pinned=*/false, typeparams, shape); 229 result.addAttributes(attributes); 230 } 231 232 void fir::AllocaOp::build(mlir::OpBuilder &builder, 233 mlir::OperationState &result, mlir::Type inType, 234 bool pinned, mlir::ValueRange typeparams, 235 mlir::ValueRange shape, 236 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 237 build(builder, result, wrapAllocaResultType(inType), inType, {}, {}, pinned, 238 typeparams, shape); 239 result.addAttributes(attributes); 240 } 241 242 mlir::ParseResult fir::AllocaOp::parse(OpAsmParser &parser, 243 OperationState &result) { 244 return parseAllocatableOp(wrapAllocaResultType, parser, result); 245 } 246 247 void fir::AllocaOp::print(OpAsmPrinter &p) { printAllocatableOp(p, *this); } 248 249 mlir::LogicalResult fir::AllocaOp::verify() { 250 llvm::SmallVector<llvm::StringRef> visited; 251 if (verifyInType(getInType(), visited, numShapeOperands())) 252 return emitOpError("invalid type for allocation"); 253 if (verifyTypeParamCount(getInType(), numLenParams())) 254 return emitOpError("LEN params do not correspond to type"); 255 mlir::Type outType = getType(); 256 if (!outType.isa<fir::ReferenceType>()) 257 return emitOpError("must be a !fir.ref type"); 258 if (fir::isa_unknown_size_box(fir::dyn_cast_ptrEleTy(outType))) 259 return emitOpError("cannot allocate !fir.box of unknown rank or type"); 260 return mlir::success(); 261 } 262 263 //===----------------------------------------------------------------------===// 264 // AllocMemOp 265 //===----------------------------------------------------------------------===// 266 267 /// Create a legal heap reference as return type 268 static mlir::Type wrapAllocMemResultType(mlir::Type intype) { 269 // Fortran semantics: C852 an entity cannot be both ALLOCATABLE and POINTER 270 // 8.5.3 note 1 prohibits ALLOCATABLE procedures as well 271 // FIR semantics: one may not allocate a memory reference value 272 if (intype.isa<ReferenceType>() || intype.isa<HeapType>() || 273 intype.isa<PointerType>() || intype.isa<FunctionType>()) 274 return {}; 275 return HeapType::get(intype); 276 } 277 278 mlir::Type fir::AllocMemOp::getAllocatedType() { 279 return getType().cast<HeapType>().getEleTy(); 280 } 281 282 mlir::Type fir::AllocMemOp::getRefTy(mlir::Type ty) { 283 return HeapType::get(ty); 284 } 285 286 void fir::AllocMemOp::build(mlir::OpBuilder &builder, 287 mlir::OperationState &result, mlir::Type inType, 288 llvm::StringRef uniqName, 289 mlir::ValueRange typeparams, mlir::ValueRange shape, 290 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 291 auto nameAttr = builder.getStringAttr(uniqName); 292 build(builder, result, wrapAllocMemResultType(inType), inType, nameAttr, {}, 293 typeparams, shape); 294 result.addAttributes(attributes); 295 } 296 297 void fir::AllocMemOp::build(mlir::OpBuilder &builder, 298 mlir::OperationState &result, mlir::Type inType, 299 llvm::StringRef uniqName, llvm::StringRef bindcName, 300 mlir::ValueRange typeparams, mlir::ValueRange shape, 301 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 302 auto nameAttr = builder.getStringAttr(uniqName); 303 auto bindcAttr = builder.getStringAttr(bindcName); 304 build(builder, result, wrapAllocMemResultType(inType), inType, nameAttr, 305 bindcAttr, typeparams, shape); 306 result.addAttributes(attributes); 307 } 308 309 void fir::AllocMemOp::build(mlir::OpBuilder &builder, 310 mlir::OperationState &result, mlir::Type inType, 311 mlir::ValueRange typeparams, mlir::ValueRange shape, 312 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 313 build(builder, result, wrapAllocMemResultType(inType), inType, {}, {}, 314 typeparams, shape); 315 result.addAttributes(attributes); 316 } 317 318 mlir::ParseResult AllocMemOp::parse(OpAsmParser &parser, 319 OperationState &result) { 320 return parseAllocatableOp(wrapAllocMemResultType, parser, result); 321 } 322 323 void AllocMemOp::print(OpAsmPrinter &p) { printAllocatableOp(p, *this); } 324 325 mlir::LogicalResult AllocMemOp::verify() { 326 llvm::SmallVector<llvm::StringRef> visited; 327 if (verifyInType(getInType(), visited, numShapeOperands())) 328 return emitOpError("invalid type for allocation"); 329 if (verifyTypeParamCount(getInType(), numLenParams())) 330 return emitOpError("LEN params do not correspond to type"); 331 mlir::Type outType = getType(); 332 if (!outType.dyn_cast<fir::HeapType>()) 333 return emitOpError("must be a !fir.heap type"); 334 if (fir::isa_unknown_size_box(fir::dyn_cast_ptrEleTy(outType))) 335 return emitOpError("cannot allocate !fir.box of unknown rank or type"); 336 return mlir::success(); 337 } 338 339 //===----------------------------------------------------------------------===// 340 // ArrayCoorOp 341 //===----------------------------------------------------------------------===// 342 343 mlir::LogicalResult ArrayCoorOp::verify() { 344 auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(getMemref().getType()); 345 auto arrTy = eleTy.dyn_cast<fir::SequenceType>(); 346 if (!arrTy) 347 return emitOpError("must be a reference to an array"); 348 auto arrDim = arrTy.getDimension(); 349 350 if (auto shapeOp = getShape()) { 351 auto shapeTy = shapeOp.getType(); 352 unsigned shapeTyRank = 0; 353 if (auto s = shapeTy.dyn_cast<fir::ShapeType>()) { 354 shapeTyRank = s.getRank(); 355 } else if (auto ss = shapeTy.dyn_cast<fir::ShapeShiftType>()) { 356 shapeTyRank = ss.getRank(); 357 } else { 358 auto s = shapeTy.cast<fir::ShiftType>(); 359 shapeTyRank = s.getRank(); 360 if (!getMemref().getType().isa<fir::BoxType>()) 361 return emitOpError("shift can only be provided with fir.box memref"); 362 } 363 if (arrDim && arrDim != shapeTyRank) 364 return emitOpError("rank of dimension mismatched"); 365 if (shapeTyRank != getIndices().size()) 366 return emitOpError("number of indices do not match dim rank"); 367 } 368 369 if (auto sliceOp = getSlice()) { 370 if (auto sl = mlir::dyn_cast_or_null<fir::SliceOp>(sliceOp.getDefiningOp())) 371 if (!sl.getSubstr().empty()) 372 return emitOpError("array_coor cannot take a slice with substring"); 373 if (auto sliceTy = sliceOp.getType().dyn_cast<fir::SliceType>()) 374 if (sliceTy.getRank() != arrDim) 375 return emitOpError("rank of dimension in slice mismatched"); 376 } 377 378 return mlir::success(); 379 } 380 381 //===----------------------------------------------------------------------===// 382 // ArrayLoadOp 383 //===----------------------------------------------------------------------===// 384 385 static mlir::Type adjustedElementType(mlir::Type t) { 386 if (auto ty = t.dyn_cast<fir::ReferenceType>()) { 387 auto eleTy = ty.getEleTy(); 388 if (fir::isa_char(eleTy)) 389 return eleTy; 390 if (fir::isa_derived(eleTy)) 391 return eleTy; 392 if (eleTy.isa<fir::SequenceType>()) 393 return eleTy; 394 } 395 return t; 396 } 397 398 std::vector<mlir::Value> fir::ArrayLoadOp::getExtents() { 399 if (auto sh = getShape()) 400 if (auto *op = sh.getDefiningOp()) { 401 if (auto shOp = dyn_cast<fir::ShapeOp>(op)) { 402 auto extents = shOp.getExtents(); 403 return {extents.begin(), extents.end()}; 404 } 405 return cast<fir::ShapeShiftOp>(op).getExtents(); 406 } 407 return {}; 408 } 409 410 mlir::LogicalResult ArrayLoadOp::verify() { 411 auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(getMemref().getType()); 412 auto arrTy = eleTy.dyn_cast<fir::SequenceType>(); 413 if (!arrTy) 414 return emitOpError("must be a reference to an array"); 415 auto arrDim = arrTy.getDimension(); 416 417 if (auto shapeOp = getShape()) { 418 auto shapeTy = shapeOp.getType(); 419 unsigned shapeTyRank = 0; 420 if (auto s = shapeTy.dyn_cast<fir::ShapeType>()) { 421 shapeTyRank = s.getRank(); 422 } else if (auto ss = shapeTy.dyn_cast<fir::ShapeShiftType>()) { 423 shapeTyRank = ss.getRank(); 424 } else { 425 auto s = shapeTy.cast<fir::ShiftType>(); 426 shapeTyRank = s.getRank(); 427 if (!getMemref().getType().isa<fir::BoxType>()) 428 return emitOpError("shift can only be provided with fir.box memref"); 429 } 430 if (arrDim && arrDim != shapeTyRank) 431 return emitOpError("rank of dimension mismatched"); 432 } 433 434 if (auto sliceOp = getSlice()) { 435 if (auto sl = mlir::dyn_cast_or_null<fir::SliceOp>(sliceOp.getDefiningOp())) 436 if (!sl.getSubstr().empty()) 437 return emitOpError("array_load cannot take a slice with substring"); 438 if (auto sliceTy = sliceOp.getType().dyn_cast<fir::SliceType>()) 439 if (sliceTy.getRank() != arrDim) 440 return emitOpError("rank of dimension in slice mismatched"); 441 } 442 443 return mlir::success(); 444 } 445 446 //===----------------------------------------------------------------------===// 447 // ArrayMergeStoreOp 448 //===----------------------------------------------------------------------===// 449 450 mlir::LogicalResult ArrayMergeStoreOp::verify() { 451 if (!isa<ArrayLoadOp>(getOriginal().getDefiningOp())) 452 return emitOpError("operand #0 must be result of a fir.array_load op"); 453 if (auto sl = getSlice()) { 454 if (auto sliceOp = 455 mlir::dyn_cast_or_null<fir::SliceOp>(sl.getDefiningOp())) { 456 if (!sliceOp.getSubstr().empty()) 457 return emitOpError( 458 "array_merge_store cannot take a slice with substring"); 459 if (!sliceOp.getFields().empty()) { 460 // This is an intra-object merge, where the slice is projecting the 461 // subfields that are to be overwritten by the merge operation. 462 auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(getMemref().getType()); 463 if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) { 464 auto projTy = 465 fir::applyPathToType(seqTy.getEleTy(), sliceOp.getFields()); 466 if (fir::unwrapSequenceType(getOriginal().getType()) != projTy) 467 return emitOpError( 468 "type of origin does not match sliced memref type"); 469 if (fir::unwrapSequenceType(getSequence().getType()) != projTy) 470 return emitOpError( 471 "type of sequence does not match sliced memref type"); 472 return mlir::success(); 473 } 474 return emitOpError("referenced type is not an array"); 475 } 476 } 477 return mlir::success(); 478 } 479 auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(getMemref().getType()); 480 if (getOriginal().getType() != eleTy) 481 return emitOpError("type of origin does not match memref element type"); 482 if (getSequence().getType() != eleTy) 483 return emitOpError("type of sequence does not match memref element type"); 484 return mlir::success(); 485 } 486 487 //===----------------------------------------------------------------------===// 488 // ArrayFetchOp 489 //===----------------------------------------------------------------------===// 490 491 // Template function used for both array_fetch and array_update verification. 492 template <typename A> 493 mlir::Type validArraySubobject(A op) { 494 auto ty = op.getSequence().getType(); 495 return fir::applyPathToType(ty, op.getIndices()); 496 } 497 498 mlir::LogicalResult ArrayFetchOp::verify() { 499 auto arrTy = getSequence().getType().cast<fir::SequenceType>(); 500 auto indSize = getIndices().size(); 501 if (indSize < arrTy.getDimension()) 502 return emitOpError("number of indices != dimension of array"); 503 if (indSize == arrTy.getDimension() && 504 ::adjustedElementType(getElement().getType()) != arrTy.getEleTy()) 505 return emitOpError("return type does not match array"); 506 auto ty = validArraySubobject(*this); 507 if (!ty || ty != ::adjustedElementType(getType())) 508 return emitOpError("return type and/or indices do not type check"); 509 if (!isa<fir::ArrayLoadOp>(getSequence().getDefiningOp())) 510 return emitOpError("argument #0 must be result of fir.array_load"); 511 return mlir::success(); 512 } 513 514 //===----------------------------------------------------------------------===// 515 // ArrayAccessOp 516 //===----------------------------------------------------------------------===// 517 518 mlir::LogicalResult ArrayAccessOp::verify() { 519 auto arrTy = getSequence().getType().cast<fir::SequenceType>(); 520 std::size_t indSize = getIndices().size(); 521 if (indSize < arrTy.getDimension()) 522 return emitOpError("number of indices != dimension of array"); 523 if (indSize == arrTy.getDimension() && 524 getElement().getType() != fir::ReferenceType::get(arrTy.getEleTy())) 525 return emitOpError("return type does not match array"); 526 mlir::Type ty = validArraySubobject(*this); 527 if (!ty || fir::ReferenceType::get(ty) != getType()) 528 return emitOpError("return type and/or indices do not type check"); 529 return mlir::success(); 530 } 531 532 //===----------------------------------------------------------------------===// 533 // ArrayUpdateOp 534 //===----------------------------------------------------------------------===// 535 536 mlir::LogicalResult ArrayUpdateOp::verify() { 537 if (fir::isa_ref_type(getMerge().getType())) 538 return emitOpError("does not support reference type for merge"); 539 auto arrTy = getSequence().getType().cast<fir::SequenceType>(); 540 auto indSize = getIndices().size(); 541 if (indSize < arrTy.getDimension()) 542 return emitOpError("number of indices != dimension of array"); 543 if (indSize == arrTy.getDimension() && 544 ::adjustedElementType(getMerge().getType()) != arrTy.getEleTy()) 545 return emitOpError("merged value does not have element type"); 546 auto ty = validArraySubobject(*this); 547 if (!ty || ty != ::adjustedElementType(getMerge().getType())) 548 return emitOpError("merged value and/or indices do not type check"); 549 return mlir::success(); 550 } 551 552 //===----------------------------------------------------------------------===// 553 // ArrayModifyOp 554 //===----------------------------------------------------------------------===// 555 556 mlir::LogicalResult ArrayModifyOp::verify() { 557 auto arrTy = getSequence().getType().cast<fir::SequenceType>(); 558 auto indSize = getIndices().size(); 559 if (indSize < arrTy.getDimension()) 560 return emitOpError("number of indices must match array dimension"); 561 return mlir::success(); 562 } 563 564 //===----------------------------------------------------------------------===// 565 // BoxAddrOp 566 //===----------------------------------------------------------------------===// 567 568 mlir::OpFoldResult fir::BoxAddrOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) { 569 if (auto v = getVal().getDefiningOp()) { 570 if (auto box = dyn_cast<fir::EmboxOp>(v)) 571 return box.getMemref(); 572 if (auto box = dyn_cast<fir::EmboxCharOp>(v)) 573 return box.getMemref(); 574 } 575 return {}; 576 } 577 578 //===----------------------------------------------------------------------===// 579 // BoxCharLenOp 580 //===----------------------------------------------------------------------===// 581 582 mlir::OpFoldResult 583 fir::BoxCharLenOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) { 584 if (auto v = getVal().getDefiningOp()) { 585 if (auto box = dyn_cast<fir::EmboxCharOp>(v)) 586 return box.getLen(); 587 } 588 return {}; 589 } 590 591 //===----------------------------------------------------------------------===// 592 // BoxDimsOp 593 //===----------------------------------------------------------------------===// 594 595 /// Get the result types packed in a tuple tuple 596 mlir::Type fir::BoxDimsOp::getTupleType() { 597 // note: triple, but 4 is nearest power of 2 598 llvm::SmallVector<mlir::Type> triple{ 599 getResult(0).getType(), getResult(1).getType(), getResult(2).getType()}; 600 return mlir::TupleType::get(getContext(), triple); 601 } 602 603 //===----------------------------------------------------------------------===// 604 // CallOp 605 //===----------------------------------------------------------------------===// 606 607 mlir::FunctionType fir::CallOp::getFunctionType() { 608 return mlir::FunctionType::get(getContext(), getOperandTypes(), 609 getResultTypes()); 610 } 611 612 void fir::CallOp::print(mlir::OpAsmPrinter &p) { 613 bool isDirect = getCallee().hasValue(); 614 p << ' '; 615 if (isDirect) 616 p << getCallee().getValue(); 617 else 618 p << getOperand(0); 619 p << '(' << (*this)->getOperands().drop_front(isDirect ? 0 : 1) << ')'; 620 p.printOptionalAttrDict((*this)->getAttrs(), 621 {fir::CallOp::getCalleeAttrNameStr()}); 622 auto resultTypes{getResultTypes()}; 623 llvm::SmallVector<Type> argTypes( 624 llvm::drop_begin(getOperandTypes(), isDirect ? 0 : 1)); 625 p << " : " << FunctionType::get(getContext(), argTypes, resultTypes); 626 } 627 628 mlir::ParseResult fir::CallOp::parse(mlir::OpAsmParser &parser, 629 mlir::OperationState &result) { 630 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> operands; 631 if (parser.parseOperandList(operands)) 632 return mlir::failure(); 633 634 mlir::NamedAttrList attrs; 635 mlir::SymbolRefAttr funcAttr; 636 bool isDirect = operands.empty(); 637 if (isDirect) 638 if (parser.parseAttribute(funcAttr, fir::CallOp::getCalleeAttrNameStr(), 639 attrs)) 640 return mlir::failure(); 641 642 Type type; 643 if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::Paren) || 644 parser.parseOptionalAttrDict(attrs) || parser.parseColon() || 645 parser.parseType(type)) 646 return mlir::failure(); 647 648 auto funcType = type.dyn_cast<mlir::FunctionType>(); 649 if (!funcType) 650 return parser.emitError(parser.getNameLoc(), "expected function type"); 651 if (isDirect) { 652 if (parser.resolveOperands(operands, funcType.getInputs(), 653 parser.getNameLoc(), result.operands)) 654 return mlir::failure(); 655 } else { 656 auto funcArgs = 657 llvm::ArrayRef<mlir::OpAsmParser::UnresolvedOperand>(operands) 658 .drop_front(); 659 if (parser.resolveOperand(operands[0], funcType, result.operands) || 660 parser.resolveOperands(funcArgs, funcType.getInputs(), 661 parser.getNameLoc(), result.operands)) 662 return mlir::failure(); 663 } 664 result.addTypes(funcType.getResults()); 665 result.attributes = attrs; 666 return mlir::success(); 667 } 668 669 void fir::CallOp::build(mlir::OpBuilder &builder, mlir::OperationState &result, 670 mlir::FuncOp callee, mlir::ValueRange operands) { 671 result.addOperands(operands); 672 result.addAttribute(getCalleeAttrNameStr(), SymbolRefAttr::get(callee)); 673 result.addTypes(callee.getFunctionType().getResults()); 674 } 675 676 void fir::CallOp::build(mlir::OpBuilder &builder, mlir::OperationState &result, 677 mlir::SymbolRefAttr callee, 678 llvm::ArrayRef<mlir::Type> results, 679 mlir::ValueRange operands) { 680 result.addOperands(operands); 681 if (callee) 682 result.addAttribute(getCalleeAttrNameStr(), callee); 683 result.addTypes(results); 684 } 685 686 //===----------------------------------------------------------------------===// 687 // CmpOp 688 //===----------------------------------------------------------------------===// 689 690 template <typename OPTY> 691 static void printCmpOp(OpAsmPrinter &p, OPTY op) { 692 p << ' '; 693 auto predSym = mlir::arith::symbolizeCmpFPredicate( 694 op->template getAttrOfType<mlir::IntegerAttr>( 695 OPTY::getPredicateAttrName()) 696 .getInt()); 697 assert(predSym.hasValue() && "invalid symbol value for predicate"); 698 p << '"' << mlir::arith::stringifyCmpFPredicate(predSym.getValue()) << '"' 699 << ", "; 700 p.printOperand(op.getLhs()); 701 p << ", "; 702 p.printOperand(op.getRhs()); 703 p.printOptionalAttrDict(op->getAttrs(), 704 /*elidedAttrs=*/{OPTY::getPredicateAttrName()}); 705 p << " : " << op.getLhs().getType(); 706 } 707 708 template <typename OPTY> 709 static mlir::ParseResult parseCmpOp(mlir::OpAsmParser &parser, 710 mlir::OperationState &result) { 711 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> ops; 712 mlir::NamedAttrList attrs; 713 mlir::Attribute predicateNameAttr; 714 mlir::Type type; 715 if (parser.parseAttribute(predicateNameAttr, OPTY::getPredicateAttrName(), 716 attrs) || 717 parser.parseComma() || parser.parseOperandList(ops, 2) || 718 parser.parseOptionalAttrDict(attrs) || parser.parseColonType(type) || 719 parser.resolveOperands(ops, type, result.operands)) 720 return failure(); 721 722 if (!predicateNameAttr.isa<mlir::StringAttr>()) 723 return parser.emitError(parser.getNameLoc(), 724 "expected string comparison predicate attribute"); 725 726 // Rewrite string attribute to an enum value. 727 llvm::StringRef predicateName = 728 predicateNameAttr.cast<mlir::StringAttr>().getValue(); 729 auto predicate = fir::CmpcOp::getPredicateByName(predicateName); 730 auto builder = parser.getBuilder(); 731 mlir::Type i1Type = builder.getI1Type(); 732 attrs.set(OPTY::getPredicateAttrName(), 733 builder.getI64IntegerAttr(static_cast<int64_t>(predicate))); 734 result.attributes = attrs; 735 result.addTypes({i1Type}); 736 return success(); 737 } 738 739 //===----------------------------------------------------------------------===// 740 // CharConvertOp 741 //===----------------------------------------------------------------------===// 742 743 mlir::LogicalResult CharConvertOp::verify() { 744 auto unwrap = [&](mlir::Type t) { 745 t = fir::unwrapSequenceType(fir::dyn_cast_ptrEleTy(t)); 746 return t.dyn_cast<fir::CharacterType>(); 747 }; 748 auto inTy = unwrap(getFrom().getType()); 749 auto outTy = unwrap(getTo().getType()); 750 if (!(inTy && outTy)) 751 return emitOpError("not a reference to a character"); 752 if (inTy.getFKind() == outTy.getFKind()) 753 return emitOpError("buffers must have different KIND values"); 754 return mlir::success(); 755 } 756 757 //===----------------------------------------------------------------------===// 758 // CmpcOp 759 //===----------------------------------------------------------------------===// 760 761 void fir::buildCmpCOp(OpBuilder &builder, OperationState &result, 762 arith::CmpFPredicate predicate, Value lhs, Value rhs) { 763 result.addOperands({lhs, rhs}); 764 result.types.push_back(builder.getI1Type()); 765 result.addAttribute( 766 fir::CmpcOp::getPredicateAttrName(), 767 builder.getI64IntegerAttr(static_cast<int64_t>(predicate))); 768 } 769 770 mlir::arith::CmpFPredicate 771 fir::CmpcOp::getPredicateByName(llvm::StringRef name) { 772 auto pred = mlir::arith::symbolizeCmpFPredicate(name); 773 assert(pred.hasValue() && "invalid predicate name"); 774 return pred.getValue(); 775 } 776 777 void CmpcOp::print(OpAsmPrinter &p) { printCmpOp(p, *this); } 778 779 mlir::ParseResult CmpcOp::parse(mlir::OpAsmParser &parser, 780 mlir::OperationState &result) { 781 return parseCmpOp<fir::CmpcOp>(parser, result); 782 } 783 784 //===----------------------------------------------------------------------===// 785 // ConstcOp 786 //===----------------------------------------------------------------------===// 787 788 mlir::ParseResult ConstcOp::parse(mlir::OpAsmParser &parser, 789 mlir::OperationState &result) { 790 fir::RealAttr realp; 791 fir::RealAttr imagp; 792 mlir::Type type; 793 if (parser.parseLParen() || 794 parser.parseAttribute(realp, fir::ConstcOp::realAttrName(), 795 result.attributes) || 796 parser.parseComma() || 797 parser.parseAttribute(imagp, fir::ConstcOp::imagAttrName(), 798 result.attributes) || 799 parser.parseRParen() || parser.parseColonType(type) || 800 parser.addTypesToList(type, result.types)) 801 return mlir::failure(); 802 return mlir::success(); 803 } 804 805 void ConstcOp::print(mlir::OpAsmPrinter &p) { 806 p << '('; 807 p << getOperation()->getAttr(fir::ConstcOp::realAttrName()) << ", "; 808 p << getOperation()->getAttr(fir::ConstcOp::imagAttrName()) << ") : "; 809 p.printType(getType()); 810 } 811 812 mlir::LogicalResult ConstcOp::verify() { 813 if (!getType().isa<fir::ComplexType>()) 814 return emitOpError("must be a !fir.complex type"); 815 return mlir::success(); 816 } 817 818 //===----------------------------------------------------------------------===// 819 // ConvertOp 820 //===----------------------------------------------------------------------===// 821 822 void fir::ConvertOp::getCanonicalizationPatterns(RewritePatternSet &results, 823 MLIRContext *context) { 824 results.insert<ConvertConvertOptPattern, ConvertAscendingIndexOptPattern, 825 ConvertDescendingIndexOptPattern, RedundantConvertOptPattern, 826 CombineConvertOptPattern, CombineConvertTruncOptPattern, 827 ForwardConstantConvertPattern>(context); 828 } 829 830 mlir::OpFoldResult fir::ConvertOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) { 831 if (getValue().getType() == getType()) 832 return getValue(); 833 if (matchPattern(getValue(), m_Op<fir::ConvertOp>())) { 834 auto inner = cast<fir::ConvertOp>(getValue().getDefiningOp()); 835 // (convert (convert 'a : logical -> i1) : i1 -> logical) ==> forward 'a 836 if (auto toTy = getType().dyn_cast<fir::LogicalType>()) 837 if (auto fromTy = inner.getValue().getType().dyn_cast<fir::LogicalType>()) 838 if (inner.getType().isa<mlir::IntegerType>() && (toTy == fromTy)) 839 return inner.getValue(); 840 // (convert (convert 'a : i1 -> logical) : logical -> i1) ==> forward 'a 841 if (auto toTy = getType().dyn_cast<mlir::IntegerType>()) 842 if (auto fromTy = 843 inner.getValue().getType().dyn_cast<mlir::IntegerType>()) 844 if (inner.getType().isa<fir::LogicalType>() && (toTy == fromTy) && 845 (fromTy.getWidth() == 1)) 846 return inner.getValue(); 847 } 848 return {}; 849 } 850 851 bool fir::ConvertOp::isIntegerCompatible(mlir::Type ty) { 852 return ty.isa<mlir::IntegerType>() || ty.isa<mlir::IndexType>() || 853 ty.isa<fir::IntegerType>() || ty.isa<fir::LogicalType>(); 854 } 855 856 bool fir::ConvertOp::isFloatCompatible(mlir::Type ty) { 857 return ty.isa<mlir::FloatType>() || ty.isa<fir::RealType>(); 858 } 859 860 bool fir::ConvertOp::isPointerCompatible(mlir::Type ty) { 861 return ty.isa<fir::ReferenceType>() || ty.isa<fir::PointerType>() || 862 ty.isa<fir::HeapType>() || ty.isa<fir::LLVMPointerType>() || 863 ty.isa<mlir::MemRefType>() || ty.isa<mlir::FunctionType>() || 864 ty.isa<fir::TypeDescType>(); 865 } 866 867 mlir::LogicalResult ConvertOp::verify() { 868 auto inType = getValue().getType(); 869 auto outType = getType(); 870 if (inType == outType) 871 return mlir::success(); 872 if ((isPointerCompatible(inType) && isPointerCompatible(outType)) || 873 (isIntegerCompatible(inType) && isIntegerCompatible(outType)) || 874 (isIntegerCompatible(inType) && isFloatCompatible(outType)) || 875 (isFloatCompatible(inType) && isIntegerCompatible(outType)) || 876 (isFloatCompatible(inType) && isFloatCompatible(outType)) || 877 (isIntegerCompatible(inType) && isPointerCompatible(outType)) || 878 (isPointerCompatible(inType) && isIntegerCompatible(outType)) || 879 (inType.isa<fir::BoxType>() && outType.isa<fir::BoxType>()) || 880 (inType.isa<fir::BoxProcType>() && outType.isa<fir::BoxProcType>()) || 881 (fir::isa_complex(inType) && fir::isa_complex(outType))) 882 return mlir::success(); 883 return emitOpError("invalid type conversion"); 884 } 885 886 //===----------------------------------------------------------------------===// 887 // CoordinateOp 888 //===----------------------------------------------------------------------===// 889 890 void CoordinateOp::print(mlir::OpAsmPrinter &p) { 891 p << ' ' << getRef() << ", " << getCoor(); 892 p.printOptionalAttrDict((*this)->getAttrs(), /*elideAttrs=*/{"baseType"}); 893 p << " : "; 894 p.printFunctionalType(getOperandTypes(), (*this)->getResultTypes()); 895 } 896 897 mlir::ParseResult CoordinateOp::parse(mlir::OpAsmParser &parser, 898 mlir::OperationState &result) { 899 mlir::OpAsmParser::UnresolvedOperand memref; 900 if (parser.parseOperand(memref) || parser.parseComma()) 901 return mlir::failure(); 902 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> coorOperands; 903 if (parser.parseOperandList(coorOperands)) 904 return mlir::failure(); 905 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> allOperands; 906 allOperands.push_back(memref); 907 allOperands.append(coorOperands.begin(), coorOperands.end()); 908 mlir::FunctionType funcTy; 909 auto loc = parser.getCurrentLocation(); 910 if (parser.parseOptionalAttrDict(result.attributes) || 911 parser.parseColonType(funcTy) || 912 parser.resolveOperands(allOperands, funcTy.getInputs(), loc, 913 result.operands)) 914 return failure(); 915 parser.addTypesToList(funcTy.getResults(), result.types); 916 result.addAttribute("baseType", mlir::TypeAttr::get(funcTy.getInput(0))); 917 return mlir::success(); 918 } 919 920 mlir::LogicalResult CoordinateOp::verify() { 921 auto refTy = getRef().getType(); 922 if (fir::isa_ref_type(refTy)) { 923 auto eleTy = fir::dyn_cast_ptrEleTy(refTy); 924 if (auto arrTy = eleTy.dyn_cast<fir::SequenceType>()) { 925 if (arrTy.hasUnknownShape()) 926 return emitOpError("cannot find coordinate in unknown shape"); 927 if (arrTy.getConstantRows() < arrTy.getDimension() - 1) 928 return emitOpError("cannot find coordinate with unknown extents"); 929 } 930 if (!(fir::isa_aggregate(eleTy) || fir::isa_complex(eleTy) || 931 fir::isa_char_string(eleTy))) 932 return emitOpError("cannot apply coordinate_of to this type"); 933 } 934 // Recovering a LEN type parameter only makes sense from a boxed value. For a 935 // bare reference, the LEN type parameters must be passed as additional 936 // arguments to `op`. 937 for (auto co : getCoor()) 938 if (dyn_cast_or_null<fir::LenParamIndexOp>(co.getDefiningOp())) { 939 if (getNumOperands() != 2) 940 return emitOpError("len_param_index must be last argument"); 941 if (!getRef().getType().isa<BoxType>()) 942 return emitOpError("len_param_index must be used on box type"); 943 } 944 return mlir::success(); 945 } 946 947 //===----------------------------------------------------------------------===// 948 // DispatchOp 949 //===----------------------------------------------------------------------===// 950 951 mlir::FunctionType fir::DispatchOp::getFunctionType() { 952 return mlir::FunctionType::get(getContext(), getOperandTypes(), 953 getResultTypes()); 954 } 955 956 mlir::ParseResult DispatchOp::parse(mlir::OpAsmParser &parser, 957 mlir::OperationState &result) { 958 mlir::FunctionType calleeType; 959 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> operands; 960 auto calleeLoc = parser.getNameLoc(); 961 llvm::StringRef calleeName; 962 if (failed(parser.parseOptionalKeyword(&calleeName))) { 963 mlir::StringAttr calleeAttr; 964 if (parser.parseAttribute(calleeAttr, 965 fir::DispatchOp::getMethodAttrNameStr(), 966 result.attributes)) 967 return mlir::failure(); 968 } else { 969 result.addAttribute(fir::DispatchOp::getMethodAttrNameStr(), 970 parser.getBuilder().getStringAttr(calleeName)); 971 } 972 if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::Paren) || 973 parser.parseOptionalAttrDict(result.attributes) || 974 parser.parseColonType(calleeType) || 975 parser.addTypesToList(calleeType.getResults(), result.types) || 976 parser.resolveOperands(operands, calleeType.getInputs(), calleeLoc, 977 result.operands)) 978 return mlir::failure(); 979 return mlir::success(); 980 } 981 982 void DispatchOp::print(mlir::OpAsmPrinter &p) { 983 p << ' ' << getMethodAttr() << '('; 984 p.printOperand(getObject()); 985 if (!getArgs().empty()) { 986 p << ", "; 987 p.printOperands(getArgs()); 988 } 989 p << ") : "; 990 p.printFunctionalType(getOperation()->getOperandTypes(), 991 getOperation()->getResultTypes()); 992 } 993 994 //===----------------------------------------------------------------------===// 995 // DispatchTableOp 996 //===----------------------------------------------------------------------===// 997 998 void fir::DispatchTableOp::appendTableEntry(mlir::Operation *op) { 999 assert(mlir::isa<fir::DTEntryOp>(*op) && "operation must be a DTEntryOp"); 1000 auto &block = getBlock(); 1001 block.getOperations().insert(block.end(), op); 1002 } 1003 1004 mlir::ParseResult DispatchTableOp::parse(mlir::OpAsmParser &parser, 1005 mlir::OperationState &result) { 1006 // Parse the name as a symbol reference attribute. 1007 SymbolRefAttr nameAttr; 1008 if (parser.parseAttribute(nameAttr, mlir::SymbolTable::getSymbolAttrName(), 1009 result.attributes)) 1010 return failure(); 1011 1012 // Convert the parsed name attr into a string attr. 1013 result.attributes.set(mlir::SymbolTable::getSymbolAttrName(), 1014 nameAttr.getRootReference()); 1015 1016 // Parse the optional table body. 1017 mlir::Region *body = result.addRegion(); 1018 OptionalParseResult parseResult = parser.parseOptionalRegion(*body); 1019 if (parseResult.hasValue() && failed(*parseResult)) 1020 return mlir::failure(); 1021 1022 fir::DispatchTableOp::ensureTerminator(*body, parser.getBuilder(), 1023 result.location); 1024 return mlir::success(); 1025 } 1026 1027 void DispatchTableOp::print(mlir::OpAsmPrinter &p) { 1028 auto tableName = 1029 getOperation() 1030 ->getAttrOfType<StringAttr>(mlir::SymbolTable::getSymbolAttrName()) 1031 .getValue(); 1032 p << " @" << tableName; 1033 1034 Region &body = getOperation()->getRegion(0); 1035 if (!body.empty()) { 1036 p << ' '; 1037 p.printRegion(body, /*printEntryBlockArgs=*/false, 1038 /*printBlockTerminators=*/false); 1039 } 1040 } 1041 1042 mlir::LogicalResult DispatchTableOp::verify() { 1043 for (auto &op : getBlock()) 1044 if (!(isa<fir::DTEntryOp>(op) || isa<fir::FirEndOp>(op))) 1045 return op.emitOpError("dispatch table must contain dt_entry"); 1046 return mlir::success(); 1047 } 1048 1049 //===----------------------------------------------------------------------===// 1050 // EmboxOp 1051 //===----------------------------------------------------------------------===// 1052 1053 mlir::LogicalResult EmboxOp::verify() { 1054 auto eleTy = fir::dyn_cast_ptrEleTy(getMemref().getType()); 1055 bool isArray = false; 1056 if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) { 1057 eleTy = seqTy.getEleTy(); 1058 isArray = true; 1059 } 1060 if (hasLenParams()) { 1061 auto lenPs = numLenParams(); 1062 if (auto rt = eleTy.dyn_cast<fir::RecordType>()) { 1063 if (lenPs != rt.getNumLenParams()) 1064 return emitOpError("number of LEN params does not correspond" 1065 " to the !fir.type type"); 1066 } else if (auto strTy = eleTy.dyn_cast<fir::CharacterType>()) { 1067 if (strTy.getLen() != fir::CharacterType::unknownLen()) 1068 return emitOpError("CHARACTER already has static LEN"); 1069 } else { 1070 return emitOpError("LEN parameters require CHARACTER or derived type"); 1071 } 1072 for (auto lp : getTypeparams()) 1073 if (!fir::isa_integer(lp.getType())) 1074 return emitOpError("LEN parameters must be integral type"); 1075 } 1076 if (getShape() && !isArray) 1077 return emitOpError("shape must not be provided for a scalar"); 1078 if (getSlice() && !isArray) 1079 return emitOpError("slice must not be provided for a scalar"); 1080 return mlir::success(); 1081 } 1082 1083 //===----------------------------------------------------------------------===// 1084 // EmboxCharOp 1085 //===----------------------------------------------------------------------===// 1086 1087 mlir::LogicalResult EmboxCharOp::verify() { 1088 auto eleTy = fir::dyn_cast_ptrEleTy(getMemref().getType()); 1089 if (!eleTy.dyn_cast_or_null<CharacterType>()) 1090 return mlir::failure(); 1091 return mlir::success(); 1092 } 1093 1094 //===----------------------------------------------------------------------===// 1095 // EmboxProcOp 1096 //===----------------------------------------------------------------------===// 1097 1098 mlir::LogicalResult EmboxProcOp::verify() { 1099 // host bindings (optional) must be a reference to a tuple 1100 if (auto h = getHost()) { 1101 if (auto r = h.getType().dyn_cast<ReferenceType>()) 1102 if (r.getEleTy().dyn_cast<mlir::TupleType>()) 1103 return mlir::success(); 1104 return mlir::failure(); 1105 } 1106 return mlir::success(); 1107 } 1108 1109 //===----------------------------------------------------------------------===// 1110 // GenTypeDescOp 1111 //===----------------------------------------------------------------------===// 1112 1113 void fir::GenTypeDescOp::build(OpBuilder &, OperationState &result, 1114 mlir::TypeAttr inty) { 1115 result.addAttribute("in_type", inty); 1116 result.addTypes(TypeDescType::get(inty.getValue())); 1117 } 1118 1119 mlir::ParseResult GenTypeDescOp::parse(mlir::OpAsmParser &parser, 1120 mlir::OperationState &result) { 1121 mlir::Type intype; 1122 if (parser.parseType(intype)) 1123 return mlir::failure(); 1124 result.addAttribute("in_type", mlir::TypeAttr::get(intype)); 1125 mlir::Type restype = TypeDescType::get(intype); 1126 if (parser.addTypeToList(restype, result.types)) 1127 return mlir::failure(); 1128 return mlir::success(); 1129 } 1130 1131 void GenTypeDescOp::print(mlir::OpAsmPrinter &p) { 1132 p << ' ' << getOperation()->getAttr("in_type"); 1133 p.printOptionalAttrDict(getOperation()->getAttrs(), {"in_type"}); 1134 } 1135 1136 mlir::LogicalResult GenTypeDescOp::verify() { 1137 mlir::Type resultTy = getType(); 1138 if (auto tdesc = resultTy.dyn_cast<TypeDescType>()) { 1139 if (tdesc.getOfTy() != getInType()) 1140 return emitOpError("wrapped type mismatched"); 1141 } else { 1142 return emitOpError("must be !fir.tdesc type"); 1143 } 1144 return mlir::success(); 1145 } 1146 1147 //===----------------------------------------------------------------------===// 1148 // GlobalOp 1149 //===----------------------------------------------------------------------===// 1150 1151 mlir::Type fir::GlobalOp::resultType() { 1152 return wrapAllocaResultType(getType()); 1153 } 1154 1155 ParseResult GlobalOp::parse(OpAsmParser &parser, OperationState &result) { 1156 // Parse the optional linkage 1157 llvm::StringRef linkage; 1158 auto &builder = parser.getBuilder(); 1159 if (mlir::succeeded(parser.parseOptionalKeyword(&linkage))) { 1160 if (fir::GlobalOp::verifyValidLinkage(linkage)) 1161 return mlir::failure(); 1162 mlir::StringAttr linkAttr = builder.getStringAttr(linkage); 1163 result.addAttribute(fir::GlobalOp::linkageAttrName(), linkAttr); 1164 } 1165 1166 // Parse the name as a symbol reference attribute. 1167 mlir::SymbolRefAttr nameAttr; 1168 if (parser.parseAttribute(nameAttr, fir::GlobalOp::symbolAttrNameStr(), 1169 result.attributes)) 1170 return mlir::failure(); 1171 result.addAttribute(mlir::SymbolTable::getSymbolAttrName(), 1172 nameAttr.getRootReference()); 1173 1174 bool simpleInitializer = false; 1175 if (mlir::succeeded(parser.parseOptionalLParen())) { 1176 Attribute attr; 1177 if (parser.parseAttribute(attr, "initVal", result.attributes) || 1178 parser.parseRParen()) 1179 return mlir::failure(); 1180 simpleInitializer = true; 1181 } 1182 1183 if (succeeded(parser.parseOptionalKeyword("constant"))) { 1184 // if "constant" keyword then mark this as a constant, not a variable 1185 result.addAttribute("constant", builder.getUnitAttr()); 1186 } 1187 1188 mlir::Type globalType; 1189 if (parser.parseColonType(globalType)) 1190 return mlir::failure(); 1191 1192 result.addAttribute(fir::GlobalOp::getTypeAttrName(result.name), 1193 mlir::TypeAttr::get(globalType)); 1194 1195 if (simpleInitializer) { 1196 result.addRegion(); 1197 } else { 1198 // Parse the optional initializer body. 1199 auto parseResult = parser.parseOptionalRegion( 1200 *result.addRegion(), /*arguments=*/llvm::None, /*argTypes=*/llvm::None); 1201 if (parseResult.hasValue() && mlir::failed(*parseResult)) 1202 return mlir::failure(); 1203 } 1204 1205 return mlir::success(); 1206 } 1207 1208 void GlobalOp::print(mlir::OpAsmPrinter &p) { 1209 if (getLinkName().hasValue()) 1210 p << ' ' << getLinkName().getValue(); 1211 p << ' '; 1212 p.printAttributeWithoutType(getSymrefAttr()); 1213 if (auto val = getValueOrNull()) 1214 p << '(' << val << ')'; 1215 if (getOperation()->getAttr(fir::GlobalOp::getConstantAttrNameStr())) 1216 p << " constant"; 1217 p << " : "; 1218 p.printType(getType()); 1219 if (hasInitializationBody()) { 1220 p << ' '; 1221 p.printRegion(getOperation()->getRegion(0), 1222 /*printEntryBlockArgs=*/false, 1223 /*printBlockTerminators=*/true); 1224 } 1225 } 1226 1227 void fir::GlobalOp::appendInitialValue(mlir::Operation *op) { 1228 getBlock().getOperations().push_back(op); 1229 } 1230 1231 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result, 1232 StringRef name, bool isConstant, Type type, 1233 Attribute initialVal, StringAttr linkage, 1234 ArrayRef<NamedAttribute> attrs) { 1235 result.addRegion(); 1236 result.addAttribute(getTypeAttrName(result.name), mlir::TypeAttr::get(type)); 1237 result.addAttribute(mlir::SymbolTable::getSymbolAttrName(), 1238 builder.getStringAttr(name)); 1239 result.addAttribute(symbolAttrNameStr(), 1240 SymbolRefAttr::get(builder.getContext(), name)); 1241 if (isConstant) 1242 result.addAttribute(getConstantAttrName(result.name), 1243 builder.getUnitAttr()); 1244 if (initialVal) 1245 result.addAttribute(getInitValAttrName(result.name), initialVal); 1246 if (linkage) 1247 result.addAttribute(linkageAttrName(), linkage); 1248 result.attributes.append(attrs.begin(), attrs.end()); 1249 } 1250 1251 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result, 1252 StringRef name, Type type, Attribute initialVal, 1253 StringAttr linkage, ArrayRef<NamedAttribute> attrs) { 1254 build(builder, result, name, /*isConstant=*/false, type, {}, linkage, attrs); 1255 } 1256 1257 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result, 1258 StringRef name, bool isConstant, Type type, 1259 StringAttr linkage, ArrayRef<NamedAttribute> attrs) { 1260 build(builder, result, name, isConstant, type, {}, linkage, attrs); 1261 } 1262 1263 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result, 1264 StringRef name, Type type, StringAttr linkage, 1265 ArrayRef<NamedAttribute> attrs) { 1266 build(builder, result, name, /*isConstant=*/false, type, {}, linkage, attrs); 1267 } 1268 1269 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result, 1270 StringRef name, bool isConstant, Type type, 1271 ArrayRef<NamedAttribute> attrs) { 1272 build(builder, result, name, isConstant, type, StringAttr{}, attrs); 1273 } 1274 1275 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result, 1276 StringRef name, Type type, 1277 ArrayRef<NamedAttribute> attrs) { 1278 build(builder, result, name, /*isConstant=*/false, type, attrs); 1279 } 1280 1281 mlir::ParseResult fir::GlobalOp::verifyValidLinkage(StringRef linkage) { 1282 // Supporting only a subset of the LLVM linkage types for now 1283 static const char *validNames[] = {"common", "internal", "linkonce", 1284 "linkonce_odr", "weak"}; 1285 return mlir::success(llvm::is_contained(validNames, linkage)); 1286 } 1287 1288 //===----------------------------------------------------------------------===// 1289 // GlobalLenOp 1290 //===----------------------------------------------------------------------===// 1291 1292 mlir::ParseResult GlobalLenOp::parse(mlir::OpAsmParser &parser, 1293 mlir::OperationState &result) { 1294 llvm::StringRef fieldName; 1295 if (failed(parser.parseOptionalKeyword(&fieldName))) { 1296 mlir::StringAttr fieldAttr; 1297 if (parser.parseAttribute(fieldAttr, fir::GlobalLenOp::lenParamAttrName(), 1298 result.attributes)) 1299 return mlir::failure(); 1300 } else { 1301 result.addAttribute(fir::GlobalLenOp::lenParamAttrName(), 1302 parser.getBuilder().getStringAttr(fieldName)); 1303 } 1304 mlir::IntegerAttr constant; 1305 if (parser.parseComma() || 1306 parser.parseAttribute(constant, fir::GlobalLenOp::intAttrName(), 1307 result.attributes)) 1308 return mlir::failure(); 1309 return mlir::success(); 1310 } 1311 1312 void GlobalLenOp::print(mlir::OpAsmPrinter &p) { 1313 p << ' ' << getOperation()->getAttr(fir::GlobalLenOp::lenParamAttrName()) 1314 << ", " << getOperation()->getAttr(fir::GlobalLenOp::intAttrName()); 1315 } 1316 1317 //===----------------------------------------------------------------------===// 1318 // FieldIndexOp 1319 //===----------------------------------------------------------------------===// 1320 1321 mlir::ParseResult FieldIndexOp::parse(mlir::OpAsmParser &parser, 1322 mlir::OperationState &result) { 1323 llvm::StringRef fieldName; 1324 auto &builder = parser.getBuilder(); 1325 mlir::Type recty; 1326 if (parser.parseOptionalKeyword(&fieldName) || parser.parseComma() || 1327 parser.parseType(recty)) 1328 return mlir::failure(); 1329 result.addAttribute(fir::FieldIndexOp::fieldAttrName(), 1330 builder.getStringAttr(fieldName)); 1331 if (!recty.dyn_cast<RecordType>()) 1332 return mlir::failure(); 1333 result.addAttribute(fir::FieldIndexOp::typeAttrName(), 1334 mlir::TypeAttr::get(recty)); 1335 if (!parser.parseOptionalLParen()) { 1336 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> operands; 1337 llvm::SmallVector<mlir::Type> types; 1338 auto loc = parser.getNameLoc(); 1339 if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::None) || 1340 parser.parseColonTypeList(types) || parser.parseRParen() || 1341 parser.resolveOperands(operands, types, loc, result.operands)) 1342 return mlir::failure(); 1343 } 1344 mlir::Type fieldType = fir::FieldType::get(builder.getContext()); 1345 if (parser.addTypeToList(fieldType, result.types)) 1346 return mlir::failure(); 1347 return mlir::success(); 1348 } 1349 1350 void FieldIndexOp::print(mlir::OpAsmPrinter &p) { 1351 p << ' ' 1352 << getOperation() 1353 ->getAttrOfType<mlir::StringAttr>(fir::FieldIndexOp::fieldAttrName()) 1354 .getValue() 1355 << ", " << getOperation()->getAttr(fir::FieldIndexOp::typeAttrName()); 1356 if (getNumOperands()) { 1357 p << '('; 1358 p.printOperands(getTypeparams()); 1359 const auto *sep = ") : "; 1360 for (auto op : getTypeparams()) { 1361 p << sep; 1362 if (op) 1363 p.printType(op.getType()); 1364 else 1365 p << "()"; 1366 sep = ", "; 1367 } 1368 } 1369 } 1370 1371 void fir::FieldIndexOp::build(mlir::OpBuilder &builder, 1372 mlir::OperationState &result, 1373 llvm::StringRef fieldName, mlir::Type recTy, 1374 mlir::ValueRange operands) { 1375 result.addAttribute(fieldAttrName(), builder.getStringAttr(fieldName)); 1376 result.addAttribute(typeAttrName(), TypeAttr::get(recTy)); 1377 result.addOperands(operands); 1378 } 1379 1380 llvm::SmallVector<mlir::Attribute> fir::FieldIndexOp::getAttributes() { 1381 llvm::SmallVector<mlir::Attribute> attrs; 1382 attrs.push_back(getFieldIdAttr()); 1383 attrs.push_back(getOnTypeAttr()); 1384 return attrs; 1385 } 1386 1387 //===----------------------------------------------------------------------===// 1388 // InsertOnRangeOp 1389 //===----------------------------------------------------------------------===// 1390 1391 static ParseResult 1392 parseCustomRangeSubscript(mlir::OpAsmParser &parser, 1393 mlir::DenseIntElementsAttr &coord) { 1394 llvm::SmallVector<int64_t> lbounds; 1395 llvm::SmallVector<int64_t> ubounds; 1396 if (parser.parseKeyword("from") || 1397 parser.parseCommaSeparatedList( 1398 AsmParser::Delimiter::Paren, 1399 [&] { return parser.parseInteger(lbounds.emplace_back(0)); }) || 1400 parser.parseKeyword("to") || 1401 parser.parseCommaSeparatedList(AsmParser::Delimiter::Paren, [&] { 1402 return parser.parseInteger(ubounds.emplace_back(0)); 1403 })) 1404 return failure(); 1405 llvm::SmallVector<int64_t> zippedBounds; 1406 for (auto zip : llvm::zip(lbounds, ubounds)) { 1407 zippedBounds.push_back(std::get<0>(zip)); 1408 zippedBounds.push_back(std::get<1>(zip)); 1409 } 1410 coord = mlir::Builder(parser.getContext()).getIndexTensorAttr(zippedBounds); 1411 return success(); 1412 } 1413 1414 void printCustomRangeSubscript(mlir::OpAsmPrinter &printer, InsertOnRangeOp op, 1415 mlir::DenseIntElementsAttr coord) { 1416 printer << "from ("; 1417 auto enumerate = llvm::enumerate(coord.getValues<int64_t>()); 1418 // Even entries are the lower bounds. 1419 llvm::interleaveComma( 1420 make_filter_range( 1421 enumerate, 1422 [](auto indexed_value) { return indexed_value.index() % 2 == 0; }), 1423 printer, [&](auto indexed_value) { printer << indexed_value.value(); }); 1424 printer << ") to ("; 1425 // Odd entries are the upper bounds. 1426 llvm::interleaveComma( 1427 make_filter_range( 1428 enumerate, 1429 [](auto indexed_value) { return indexed_value.index() % 2 != 0; }), 1430 printer, [&](auto indexed_value) { printer << indexed_value.value(); }); 1431 printer << ")"; 1432 } 1433 1434 /// Range bounds must be nonnegative, and the range must not be empty. 1435 mlir::LogicalResult InsertOnRangeOp::verify() { 1436 if (fir::hasDynamicSize(getSeq().getType())) 1437 return emitOpError("must have constant shape and size"); 1438 mlir::DenseIntElementsAttr coorAttr = getCoor(); 1439 if (coorAttr.size() < 2 || coorAttr.size() % 2 != 0) 1440 return emitOpError("has uneven number of values in ranges"); 1441 bool rangeIsKnownToBeNonempty = false; 1442 for (auto i = coorAttr.getValues<int64_t>().end(), 1443 b = coorAttr.getValues<int64_t>().begin(); 1444 i != b;) { 1445 int64_t ub = (*--i); 1446 int64_t lb = (*--i); 1447 if (lb < 0 || ub < 0) 1448 return emitOpError("negative range bound"); 1449 if (rangeIsKnownToBeNonempty) 1450 continue; 1451 if (lb > ub) 1452 return emitOpError("empty range"); 1453 rangeIsKnownToBeNonempty = lb < ub; 1454 } 1455 return mlir::success(); 1456 } 1457 1458 //===----------------------------------------------------------------------===// 1459 // InsertValueOp 1460 //===----------------------------------------------------------------------===// 1461 1462 static bool checkIsIntegerConstant(mlir::Attribute attr, int64_t conVal) { 1463 if (auto iattr = attr.dyn_cast<mlir::IntegerAttr>()) 1464 return iattr.getInt() == conVal; 1465 return false; 1466 } 1467 static bool isZero(mlir::Attribute a) { return checkIsIntegerConstant(a, 0); } 1468 static bool isOne(mlir::Attribute a) { return checkIsIntegerConstant(a, 1); } 1469 1470 // Undo some complex patterns created in the front-end and turn them back into 1471 // complex ops. 1472 template <typename FltOp, typename CpxOp> 1473 struct UndoComplexPattern : public mlir::RewritePattern { 1474 UndoComplexPattern(mlir::MLIRContext *ctx) 1475 : mlir::RewritePattern("fir.insert_value", 2, ctx) {} 1476 1477 mlir::LogicalResult 1478 matchAndRewrite(mlir::Operation *op, 1479 mlir::PatternRewriter &rewriter) const override { 1480 auto insval = dyn_cast_or_null<fir::InsertValueOp>(op); 1481 if (!insval || !insval.getType().isa<fir::ComplexType>()) 1482 return mlir::failure(); 1483 auto insval2 = 1484 dyn_cast_or_null<fir::InsertValueOp>(insval.getAdt().getDefiningOp()); 1485 if (!insval2 || !isa<fir::UndefOp>(insval2.getAdt().getDefiningOp())) 1486 return mlir::failure(); 1487 auto binf = dyn_cast_or_null<FltOp>(insval.getVal().getDefiningOp()); 1488 auto binf2 = dyn_cast_or_null<FltOp>(insval2.getVal().getDefiningOp()); 1489 if (!binf || !binf2 || insval.getCoor().size() != 1 || 1490 !isOne(insval.getCoor()[0]) || insval2.getCoor().size() != 1 || 1491 !isZero(insval2.getCoor()[0])) 1492 return mlir::failure(); 1493 auto eai = 1494 dyn_cast_or_null<fir::ExtractValueOp>(binf.getLhs().getDefiningOp()); 1495 auto ebi = 1496 dyn_cast_or_null<fir::ExtractValueOp>(binf.getRhs().getDefiningOp()); 1497 auto ear = 1498 dyn_cast_or_null<fir::ExtractValueOp>(binf2.getLhs().getDefiningOp()); 1499 auto ebr = 1500 dyn_cast_or_null<fir::ExtractValueOp>(binf2.getRhs().getDefiningOp()); 1501 if (!eai || !ebi || !ear || !ebr || ear.getAdt() != eai.getAdt() || 1502 ebr.getAdt() != ebi.getAdt() || eai.getCoor().size() != 1 || 1503 !isOne(eai.getCoor()[0]) || ebi.getCoor().size() != 1 || 1504 !isOne(ebi.getCoor()[0]) || ear.getCoor().size() != 1 || 1505 !isZero(ear.getCoor()[0]) || ebr.getCoor().size() != 1 || 1506 !isZero(ebr.getCoor()[0])) 1507 return mlir::failure(); 1508 rewriter.replaceOpWithNewOp<CpxOp>(op, ear.getAdt(), ebr.getAdt()); 1509 return mlir::success(); 1510 } 1511 }; 1512 1513 void fir::InsertValueOp::getCanonicalizationPatterns( 1514 mlir::RewritePatternSet &results, mlir::MLIRContext *context) { 1515 results.insert<UndoComplexPattern<mlir::arith::AddFOp, fir::AddcOp>, 1516 UndoComplexPattern<mlir::arith::SubFOp, fir::SubcOp>>(context); 1517 } 1518 1519 //===----------------------------------------------------------------------===// 1520 // IterWhileOp 1521 //===----------------------------------------------------------------------===// 1522 1523 void fir::IterWhileOp::build(mlir::OpBuilder &builder, 1524 mlir::OperationState &result, mlir::Value lb, 1525 mlir::Value ub, mlir::Value step, 1526 mlir::Value iterate, bool finalCountValue, 1527 mlir::ValueRange iterArgs, 1528 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 1529 result.addOperands({lb, ub, step, iterate}); 1530 if (finalCountValue) { 1531 result.addTypes(builder.getIndexType()); 1532 result.addAttribute(getFinalValueAttrNameStr(), builder.getUnitAttr()); 1533 } 1534 result.addTypes(iterate.getType()); 1535 result.addOperands(iterArgs); 1536 for (auto v : iterArgs) 1537 result.addTypes(v.getType()); 1538 mlir::Region *bodyRegion = result.addRegion(); 1539 bodyRegion->push_back(new Block{}); 1540 bodyRegion->front().addArgument(builder.getIndexType(), result.location); 1541 bodyRegion->front().addArgument(iterate.getType(), result.location); 1542 bodyRegion->front().addArguments( 1543 iterArgs.getTypes(), 1544 SmallVector<Location>(iterArgs.size(), result.location)); 1545 result.addAttributes(attributes); 1546 } 1547 1548 mlir::ParseResult IterWhileOp::parse(mlir::OpAsmParser &parser, 1549 mlir::OperationState &result) { 1550 auto &builder = parser.getBuilder(); 1551 mlir::OpAsmParser::UnresolvedOperand inductionVariable, lb, ub, step; 1552 if (parser.parseLParen() || parser.parseRegionArgument(inductionVariable) || 1553 parser.parseEqual()) 1554 return mlir::failure(); 1555 1556 // Parse loop bounds. 1557 auto indexType = builder.getIndexType(); 1558 auto i1Type = builder.getIntegerType(1); 1559 if (parser.parseOperand(lb) || 1560 parser.resolveOperand(lb, indexType, result.operands) || 1561 parser.parseKeyword("to") || parser.parseOperand(ub) || 1562 parser.resolveOperand(ub, indexType, result.operands) || 1563 parser.parseKeyword("step") || parser.parseOperand(step) || 1564 parser.parseRParen() || 1565 parser.resolveOperand(step, indexType, result.operands)) 1566 return mlir::failure(); 1567 1568 mlir::OpAsmParser::UnresolvedOperand iterateVar, iterateInput; 1569 if (parser.parseKeyword("and") || parser.parseLParen() || 1570 parser.parseRegionArgument(iterateVar) || parser.parseEqual() || 1571 parser.parseOperand(iterateInput) || parser.parseRParen() || 1572 parser.resolveOperand(iterateInput, i1Type, result.operands)) 1573 return mlir::failure(); 1574 1575 // Parse the initial iteration arguments. 1576 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> regionArgs; 1577 auto prependCount = false; 1578 1579 // Induction variable. 1580 regionArgs.push_back(inductionVariable); 1581 regionArgs.push_back(iterateVar); 1582 1583 if (succeeded(parser.parseOptionalKeyword("iter_args"))) { 1584 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> operands; 1585 llvm::SmallVector<mlir::Type> regionTypes; 1586 // Parse assignment list and results type list. 1587 if (parser.parseAssignmentList(regionArgs, operands) || 1588 parser.parseArrowTypeList(regionTypes)) 1589 return failure(); 1590 if (regionTypes.size() == operands.size() + 2) 1591 prependCount = true; 1592 llvm::ArrayRef<mlir::Type> resTypes = regionTypes; 1593 resTypes = prependCount ? resTypes.drop_front(2) : resTypes; 1594 // Resolve input operands. 1595 for (auto operandType : llvm::zip(operands, resTypes)) 1596 if (parser.resolveOperand(std::get<0>(operandType), 1597 std::get<1>(operandType), result.operands)) 1598 return failure(); 1599 if (prependCount) { 1600 result.addTypes(regionTypes); 1601 } else { 1602 result.addTypes(i1Type); 1603 result.addTypes(resTypes); 1604 } 1605 } else if (succeeded(parser.parseOptionalArrow())) { 1606 llvm::SmallVector<mlir::Type> typeList; 1607 if (parser.parseLParen() || parser.parseTypeList(typeList) || 1608 parser.parseRParen()) 1609 return failure(); 1610 // Type list must be "(index, i1)". 1611 if (typeList.size() != 2 || !typeList[0].isa<mlir::IndexType>() || 1612 !typeList[1].isSignlessInteger(1)) 1613 return failure(); 1614 result.addTypes(typeList); 1615 prependCount = true; 1616 } else { 1617 result.addTypes(i1Type); 1618 } 1619 1620 if (parser.parseOptionalAttrDictWithKeyword(result.attributes)) 1621 return mlir::failure(); 1622 1623 llvm::SmallVector<mlir::Type> argTypes; 1624 // Induction variable (hidden) 1625 if (prependCount) 1626 result.addAttribute(IterWhileOp::getFinalValueAttrNameStr(), 1627 builder.getUnitAttr()); 1628 else 1629 argTypes.push_back(indexType); 1630 // Loop carried variables (including iterate) 1631 argTypes.append(result.types.begin(), result.types.end()); 1632 // Parse the body region. 1633 auto *body = result.addRegion(); 1634 if (regionArgs.size() != argTypes.size()) 1635 return parser.emitError( 1636 parser.getNameLoc(), 1637 "mismatch in number of loop-carried values and defined values"); 1638 1639 if (parser.parseRegion(*body, regionArgs, argTypes)) 1640 return failure(); 1641 1642 fir::IterWhileOp::ensureTerminator(*body, builder, result.location); 1643 1644 return mlir::success(); 1645 } 1646 1647 mlir::LogicalResult IterWhileOp::verify() { 1648 // Check that the body defines as single block argument for the induction 1649 // variable. 1650 auto *body = getBody(); 1651 if (!body->getArgument(1).getType().isInteger(1)) 1652 return emitOpError( 1653 "expected body second argument to be an index argument for " 1654 "the induction variable"); 1655 if (!body->getArgument(0).getType().isIndex()) 1656 return emitOpError( 1657 "expected body first argument to be an index argument for " 1658 "the induction variable"); 1659 1660 auto opNumResults = getNumResults(); 1661 if (getFinalValue()) { 1662 // Result type must be "(index, i1, ...)". 1663 if (!getResult(0).getType().isa<mlir::IndexType>()) 1664 return emitOpError("result #0 expected to be index"); 1665 if (!getResult(1).getType().isSignlessInteger(1)) 1666 return emitOpError("result #1 expected to be i1"); 1667 opNumResults--; 1668 } else { 1669 // iterate_while always returns the early exit induction value. 1670 // Result type must be "(i1, ...)" 1671 if (!getResult(0).getType().isSignlessInteger(1)) 1672 return emitOpError("result #0 expected to be i1"); 1673 } 1674 if (opNumResults == 0) 1675 return mlir::failure(); 1676 if (getNumIterOperands() != opNumResults) 1677 return emitOpError( 1678 "mismatch in number of loop-carried values and defined values"); 1679 if (getNumRegionIterArgs() != opNumResults) 1680 return emitOpError( 1681 "mismatch in number of basic block args and defined values"); 1682 auto iterOperands = getIterOperands(); 1683 auto iterArgs = getRegionIterArgs(); 1684 auto opResults = getFinalValue() ? getResults().drop_front() : getResults(); 1685 unsigned i = 0; 1686 for (auto e : llvm::zip(iterOperands, iterArgs, opResults)) { 1687 if (std::get<0>(e).getType() != std::get<2>(e).getType()) 1688 return emitOpError() << "types mismatch between " << i 1689 << "th iter operand and defined value"; 1690 if (std::get<1>(e).getType() != std::get<2>(e).getType()) 1691 return emitOpError() << "types mismatch between " << i 1692 << "th iter region arg and defined value"; 1693 1694 i++; 1695 } 1696 return mlir::success(); 1697 } 1698 1699 void IterWhileOp::print(mlir::OpAsmPrinter &p) { 1700 p << " (" << getInductionVar() << " = " << getLowerBound() << " to " 1701 << getUpperBound() << " step " << getStep() << ") and ("; 1702 assert(hasIterOperands()); 1703 auto regionArgs = getRegionIterArgs(); 1704 auto operands = getIterOperands(); 1705 p << regionArgs.front() << " = " << *operands.begin() << ")"; 1706 if (regionArgs.size() > 1) { 1707 p << " iter_args("; 1708 llvm::interleaveComma( 1709 llvm::zip(regionArgs.drop_front(), operands.drop_front()), p, 1710 [&](auto it) { p << std::get<0>(it) << " = " << std::get<1>(it); }); 1711 p << ") -> ("; 1712 llvm::interleaveComma( 1713 llvm::drop_begin(getResultTypes(), getFinalValue() ? 0 : 1), p); 1714 p << ")"; 1715 } else if (getFinalValue()) { 1716 p << " -> (" << getResultTypes() << ')'; 1717 } 1718 p.printOptionalAttrDictWithKeyword((*this)->getAttrs(), 1719 {getFinalValueAttrNameStr()}); 1720 p << ' '; 1721 p.printRegion(getRegion(), /*printEntryBlockArgs=*/false, 1722 /*printBlockTerminators=*/true); 1723 } 1724 1725 mlir::Region &fir::IterWhileOp::getLoopBody() { return getRegion(); } 1726 1727 bool fir::IterWhileOp::isDefinedOutsideOfLoop(mlir::Value value) { 1728 return !getRegion().isAncestor(value.getParentRegion()); 1729 } 1730 1731 mlir::LogicalResult 1732 fir::IterWhileOp::moveOutOfLoop(llvm::ArrayRef<mlir::Operation *> ops) { 1733 for (auto *op : ops) 1734 op->moveBefore(*this); 1735 return success(); 1736 } 1737 1738 mlir::BlockArgument fir::IterWhileOp::iterArgToBlockArg(mlir::Value iterArg) { 1739 for (auto i : llvm::enumerate(getInitArgs())) 1740 if (iterArg == i.value()) 1741 return getRegion().front().getArgument(i.index() + 1); 1742 return {}; 1743 } 1744 1745 void fir::IterWhileOp::resultToSourceOps( 1746 llvm::SmallVectorImpl<mlir::Value> &results, unsigned resultNum) { 1747 auto oper = getFinalValue() ? resultNum + 1 : resultNum; 1748 auto *term = getRegion().front().getTerminator(); 1749 if (oper < term->getNumOperands()) 1750 results.push_back(term->getOperand(oper)); 1751 } 1752 1753 mlir::Value fir::IterWhileOp::blockArgToSourceOp(unsigned blockArgNum) { 1754 if (blockArgNum > 0 && blockArgNum <= getInitArgs().size()) 1755 return getInitArgs()[blockArgNum - 1]; 1756 return {}; 1757 } 1758 1759 //===----------------------------------------------------------------------===// 1760 // LenParamIndexOp 1761 //===----------------------------------------------------------------------===// 1762 1763 mlir::ParseResult LenParamIndexOp::parse(mlir::OpAsmParser &parser, 1764 mlir::OperationState &result) { 1765 llvm::StringRef fieldName; 1766 auto &builder = parser.getBuilder(); 1767 mlir::Type recty; 1768 if (parser.parseOptionalKeyword(&fieldName) || parser.parseComma() || 1769 parser.parseType(recty)) 1770 return mlir::failure(); 1771 result.addAttribute(fir::LenParamIndexOp::fieldAttrName(), 1772 builder.getStringAttr(fieldName)); 1773 if (!recty.dyn_cast<RecordType>()) 1774 return mlir::failure(); 1775 result.addAttribute(fir::LenParamIndexOp::typeAttrName(), 1776 mlir::TypeAttr::get(recty)); 1777 mlir::Type lenType = fir::LenType::get(builder.getContext()); 1778 if (parser.addTypeToList(lenType, result.types)) 1779 return mlir::failure(); 1780 return mlir::success(); 1781 } 1782 1783 void LenParamIndexOp::print(mlir::OpAsmPrinter &p) { 1784 p << ' ' 1785 << getOperation() 1786 ->getAttrOfType<mlir::StringAttr>( 1787 fir::LenParamIndexOp::fieldAttrName()) 1788 .getValue() 1789 << ", " << getOperation()->getAttr(fir::LenParamIndexOp::typeAttrName()); 1790 } 1791 1792 //===----------------------------------------------------------------------===// 1793 // LoadOp 1794 //===----------------------------------------------------------------------===// 1795 1796 void fir::LoadOp::build(mlir::OpBuilder &builder, mlir::OperationState &result, 1797 mlir::Value refVal) { 1798 if (!refVal) { 1799 mlir::emitError(result.location, "LoadOp has null argument"); 1800 return; 1801 } 1802 auto eleTy = fir::dyn_cast_ptrEleTy(refVal.getType()); 1803 if (!eleTy) { 1804 mlir::emitError(result.location, "not a memory reference type"); 1805 return; 1806 } 1807 result.addOperands(refVal); 1808 result.addTypes(eleTy); 1809 } 1810 1811 mlir::ParseResult fir::LoadOp::getElementOf(mlir::Type &ele, mlir::Type ref) { 1812 if ((ele = fir::dyn_cast_ptrEleTy(ref))) 1813 return mlir::success(); 1814 return mlir::failure(); 1815 } 1816 1817 mlir::ParseResult LoadOp::parse(mlir::OpAsmParser &parser, 1818 mlir::OperationState &result) { 1819 mlir::Type type; 1820 mlir::OpAsmParser::UnresolvedOperand oper; 1821 if (parser.parseOperand(oper) || 1822 parser.parseOptionalAttrDict(result.attributes) || 1823 parser.parseColonType(type) || 1824 parser.resolveOperand(oper, type, result.operands)) 1825 return mlir::failure(); 1826 mlir::Type eleTy; 1827 if (fir::LoadOp::getElementOf(eleTy, type) || 1828 parser.addTypeToList(eleTy, result.types)) 1829 return mlir::failure(); 1830 return mlir::success(); 1831 } 1832 1833 void LoadOp::print(mlir::OpAsmPrinter &p) { 1834 p << ' '; 1835 p.printOperand(getMemref()); 1836 p.printOptionalAttrDict(getOperation()->getAttrs(), {}); 1837 p << " : " << getMemref().getType(); 1838 } 1839 1840 //===----------------------------------------------------------------------===// 1841 // DoLoopOp 1842 //===----------------------------------------------------------------------===// 1843 1844 void fir::DoLoopOp::build(mlir::OpBuilder &builder, 1845 mlir::OperationState &result, mlir::Value lb, 1846 mlir::Value ub, mlir::Value step, bool unordered, 1847 bool finalCountValue, mlir::ValueRange iterArgs, 1848 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 1849 result.addOperands({lb, ub, step}); 1850 result.addOperands(iterArgs); 1851 if (finalCountValue) { 1852 result.addTypes(builder.getIndexType()); 1853 result.addAttribute(getFinalValueAttrName(result.name), 1854 builder.getUnitAttr()); 1855 } 1856 for (auto v : iterArgs) 1857 result.addTypes(v.getType()); 1858 mlir::Region *bodyRegion = result.addRegion(); 1859 bodyRegion->push_back(new Block{}); 1860 if (iterArgs.empty() && !finalCountValue) 1861 DoLoopOp::ensureTerminator(*bodyRegion, builder, result.location); 1862 bodyRegion->front().addArgument(builder.getIndexType(), result.location); 1863 bodyRegion->front().addArguments( 1864 iterArgs.getTypes(), 1865 SmallVector<Location>(iterArgs.size(), result.location)); 1866 if (unordered) 1867 result.addAttribute(getUnorderedAttrName(result.name), 1868 builder.getUnitAttr()); 1869 result.addAttributes(attributes); 1870 } 1871 1872 mlir::ParseResult DoLoopOp::parse(mlir::OpAsmParser &parser, 1873 mlir::OperationState &result) { 1874 auto &builder = parser.getBuilder(); 1875 mlir::OpAsmParser::UnresolvedOperand inductionVariable, lb, ub, step; 1876 // Parse the induction variable followed by '='. 1877 if (parser.parseRegionArgument(inductionVariable) || parser.parseEqual()) 1878 return mlir::failure(); 1879 1880 // Parse loop bounds. 1881 auto indexType = builder.getIndexType(); 1882 if (parser.parseOperand(lb) || 1883 parser.resolveOperand(lb, indexType, result.operands) || 1884 parser.parseKeyword("to") || parser.parseOperand(ub) || 1885 parser.resolveOperand(ub, indexType, result.operands) || 1886 parser.parseKeyword("step") || parser.parseOperand(step) || 1887 parser.resolveOperand(step, indexType, result.operands)) 1888 return failure(); 1889 1890 if (mlir::succeeded(parser.parseOptionalKeyword("unordered"))) 1891 result.addAttribute("unordered", builder.getUnitAttr()); 1892 1893 // Parse the optional initial iteration arguments. 1894 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> regionArgs, operands; 1895 llvm::SmallVector<mlir::Type> argTypes; 1896 auto prependCount = false; 1897 regionArgs.push_back(inductionVariable); 1898 1899 if (succeeded(parser.parseOptionalKeyword("iter_args"))) { 1900 // Parse assignment list and results type list. 1901 if (parser.parseAssignmentList(regionArgs, operands) || 1902 parser.parseArrowTypeList(result.types)) 1903 return failure(); 1904 if (result.types.size() == operands.size() + 1) 1905 prependCount = true; 1906 // Resolve input operands. 1907 llvm::ArrayRef<mlir::Type> resTypes = result.types; 1908 for (auto operand_type : 1909 llvm::zip(operands, prependCount ? resTypes.drop_front() : resTypes)) 1910 if (parser.resolveOperand(std::get<0>(operand_type), 1911 std::get<1>(operand_type), result.operands)) 1912 return failure(); 1913 } else if (succeeded(parser.parseOptionalArrow())) { 1914 if (parser.parseKeyword("index")) 1915 return failure(); 1916 result.types.push_back(indexType); 1917 prependCount = true; 1918 } 1919 1920 if (parser.parseOptionalAttrDictWithKeyword(result.attributes)) 1921 return mlir::failure(); 1922 1923 // Induction variable. 1924 if (prependCount) 1925 result.addAttribute(DoLoopOp::getFinalValueAttrName(result.name), 1926 builder.getUnitAttr()); 1927 else 1928 argTypes.push_back(indexType); 1929 // Loop carried variables 1930 argTypes.append(result.types.begin(), result.types.end()); 1931 // Parse the body region. 1932 auto *body = result.addRegion(); 1933 if (regionArgs.size() != argTypes.size()) 1934 return parser.emitError( 1935 parser.getNameLoc(), 1936 "mismatch in number of loop-carried values and defined values"); 1937 1938 if (parser.parseRegion(*body, regionArgs, argTypes)) 1939 return failure(); 1940 1941 DoLoopOp::ensureTerminator(*body, builder, result.location); 1942 1943 return mlir::success(); 1944 } 1945 1946 fir::DoLoopOp fir::getForInductionVarOwner(mlir::Value val) { 1947 auto ivArg = val.dyn_cast<mlir::BlockArgument>(); 1948 if (!ivArg) 1949 return {}; 1950 assert(ivArg.getOwner() && "unlinked block argument"); 1951 auto *containingInst = ivArg.getOwner()->getParentOp(); 1952 return dyn_cast_or_null<fir::DoLoopOp>(containingInst); 1953 } 1954 1955 // Lifted from loop.loop 1956 mlir::LogicalResult DoLoopOp::verify() { 1957 // Check that the body defines as single block argument for the induction 1958 // variable. 1959 auto *body = getBody(); 1960 if (!body->getArgument(0).getType().isIndex()) 1961 return emitOpError( 1962 "expected body first argument to be an index argument for " 1963 "the induction variable"); 1964 1965 auto opNumResults = getNumResults(); 1966 if (opNumResults == 0) 1967 return success(); 1968 1969 if (getFinalValue()) { 1970 if (getUnordered()) 1971 return emitOpError("unordered loop has no final value"); 1972 opNumResults--; 1973 } 1974 if (getNumIterOperands() != opNumResults) 1975 return emitOpError( 1976 "mismatch in number of loop-carried values and defined values"); 1977 if (getNumRegionIterArgs() != opNumResults) 1978 return emitOpError( 1979 "mismatch in number of basic block args and defined values"); 1980 auto iterOperands = getIterOperands(); 1981 auto iterArgs = getRegionIterArgs(); 1982 auto opResults = getFinalValue() ? getResults().drop_front() : getResults(); 1983 unsigned i = 0; 1984 for (auto e : llvm::zip(iterOperands, iterArgs, opResults)) { 1985 if (std::get<0>(e).getType() != std::get<2>(e).getType()) 1986 return emitOpError() << "types mismatch between " << i 1987 << "th iter operand and defined value"; 1988 if (std::get<1>(e).getType() != std::get<2>(e).getType()) 1989 return emitOpError() << "types mismatch between " << i 1990 << "th iter region arg and defined value"; 1991 1992 i++; 1993 } 1994 return success(); 1995 } 1996 1997 void DoLoopOp::print(mlir::OpAsmPrinter &p) { 1998 bool printBlockTerminators = false; 1999 p << ' ' << getInductionVar() << " = " << getLowerBound() << " to " 2000 << getUpperBound() << " step " << getStep(); 2001 if (getUnordered()) 2002 p << " unordered"; 2003 if (hasIterOperands()) { 2004 p << " iter_args("; 2005 auto regionArgs = getRegionIterArgs(); 2006 auto operands = getIterOperands(); 2007 llvm::interleaveComma(llvm::zip(regionArgs, operands), p, [&](auto it) { 2008 p << std::get<0>(it) << " = " << std::get<1>(it); 2009 }); 2010 p << ") -> (" << getResultTypes() << ')'; 2011 printBlockTerminators = true; 2012 } else if (getFinalValue()) { 2013 p << " -> " << getResultTypes(); 2014 printBlockTerminators = true; 2015 } 2016 p.printOptionalAttrDictWithKeyword((*this)->getAttrs(), 2017 {"unordered", "finalValue"}); 2018 p << ' '; 2019 p.printRegion(getRegion(), /*printEntryBlockArgs=*/false, 2020 printBlockTerminators); 2021 } 2022 2023 mlir::Region &fir::DoLoopOp::getLoopBody() { return getRegion(); } 2024 2025 bool fir::DoLoopOp::isDefinedOutsideOfLoop(mlir::Value value) { 2026 return !getRegion().isAncestor(value.getParentRegion()); 2027 } 2028 2029 mlir::LogicalResult 2030 fir::DoLoopOp::moveOutOfLoop(llvm::ArrayRef<mlir::Operation *> ops) { 2031 for (auto op : ops) 2032 op->moveBefore(*this); 2033 return success(); 2034 } 2035 2036 /// Translate a value passed as an iter_arg to the corresponding block 2037 /// argument in the body of the loop. 2038 mlir::BlockArgument fir::DoLoopOp::iterArgToBlockArg(mlir::Value iterArg) { 2039 for (auto i : llvm::enumerate(getInitArgs())) 2040 if (iterArg == i.value()) 2041 return getRegion().front().getArgument(i.index() + 1); 2042 return {}; 2043 } 2044 2045 /// Translate the result vector (by index number) to the corresponding value 2046 /// to the `fir.result` Op. 2047 void fir::DoLoopOp::resultToSourceOps( 2048 llvm::SmallVectorImpl<mlir::Value> &results, unsigned resultNum) { 2049 auto oper = getFinalValue() ? resultNum + 1 : resultNum; 2050 auto *term = getRegion().front().getTerminator(); 2051 if (oper < term->getNumOperands()) 2052 results.push_back(term->getOperand(oper)); 2053 } 2054 2055 /// Translate the block argument (by index number) to the corresponding value 2056 /// passed as an iter_arg to the parent DoLoopOp. 2057 mlir::Value fir::DoLoopOp::blockArgToSourceOp(unsigned blockArgNum) { 2058 if (blockArgNum > 0 && blockArgNum <= getInitArgs().size()) 2059 return getInitArgs()[blockArgNum - 1]; 2060 return {}; 2061 } 2062 2063 //===----------------------------------------------------------------------===// 2064 // DTEntryOp 2065 //===----------------------------------------------------------------------===// 2066 2067 mlir::ParseResult DTEntryOp::parse(mlir::OpAsmParser &parser, 2068 mlir::OperationState &result) { 2069 llvm::StringRef methodName; 2070 // allow `methodName` or `"methodName"` 2071 if (failed(parser.parseOptionalKeyword(&methodName))) { 2072 mlir::StringAttr methodAttr; 2073 if (parser.parseAttribute(methodAttr, 2074 fir::DTEntryOp::getMethodAttrNameStr(), 2075 result.attributes)) 2076 return mlir::failure(); 2077 } else { 2078 result.addAttribute(fir::DTEntryOp::getMethodAttrNameStr(), 2079 parser.getBuilder().getStringAttr(methodName)); 2080 } 2081 mlir::SymbolRefAttr calleeAttr; 2082 if (parser.parseComma() || 2083 parser.parseAttribute(calleeAttr, fir::DTEntryOp::getProcAttrNameStr(), 2084 result.attributes)) 2085 return mlir::failure(); 2086 return mlir::success(); 2087 } 2088 2089 void DTEntryOp::print(mlir::OpAsmPrinter &p) { 2090 p << ' ' << getMethodAttr() << ", " << getProcAttr(); 2091 } 2092 2093 //===----------------------------------------------------------------------===// 2094 // ReboxOp 2095 //===----------------------------------------------------------------------===// 2096 2097 /// Get the scalar type related to a fir.box type. 2098 /// Example: return f32 for !fir.box<!fir.heap<!fir.array<?x?xf32>>. 2099 static mlir::Type getBoxScalarEleTy(mlir::Type boxTy) { 2100 auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy); 2101 if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) 2102 return seqTy.getEleTy(); 2103 return eleTy; 2104 } 2105 2106 /// Get the rank from a !fir.box type 2107 static unsigned getBoxRank(mlir::Type boxTy) { 2108 auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy); 2109 if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) 2110 return seqTy.getDimension(); 2111 return 0; 2112 } 2113 2114 /// Test if \p t1 and \p t2 are compatible character types (if they can 2115 /// represent the same type at runtime). 2116 static bool areCompatibleCharacterTypes(mlir::Type t1, mlir::Type t2) { 2117 auto c1 = t1.dyn_cast<fir::CharacterType>(); 2118 auto c2 = t2.dyn_cast<fir::CharacterType>(); 2119 if (!c1 || !c2) 2120 return false; 2121 if (c1.hasDynamicLen() || c2.hasDynamicLen()) 2122 return true; 2123 return c1.getLen() == c2.getLen(); 2124 } 2125 2126 mlir::LogicalResult ReboxOp::verify() { 2127 auto inputBoxTy = getBox().getType(); 2128 if (fir::isa_unknown_size_box(inputBoxTy)) 2129 return emitOpError("box operand must not have unknown rank or type"); 2130 auto outBoxTy = getType(); 2131 if (fir::isa_unknown_size_box(outBoxTy)) 2132 return emitOpError("result type must not have unknown rank or type"); 2133 auto inputRank = getBoxRank(inputBoxTy); 2134 auto inputEleTy = getBoxScalarEleTy(inputBoxTy); 2135 auto outRank = getBoxRank(outBoxTy); 2136 auto outEleTy = getBoxScalarEleTy(outBoxTy); 2137 2138 if (auto sliceVal = getSlice()) { 2139 // Slicing case 2140 if (sliceVal.getType().cast<fir::SliceType>().getRank() != inputRank) 2141 return emitOpError("slice operand rank must match box operand rank"); 2142 if (auto shapeVal = getShape()) { 2143 if (auto shiftTy = shapeVal.getType().dyn_cast<fir::ShiftType>()) { 2144 if (shiftTy.getRank() != inputRank) 2145 return emitOpError("shape operand and input box ranks must match " 2146 "when there is a slice"); 2147 } else { 2148 return emitOpError("shape operand must absent or be a fir.shift " 2149 "when there is a slice"); 2150 } 2151 } 2152 if (auto sliceOp = sliceVal.getDefiningOp()) { 2153 auto slicedRank = mlir::cast<fir::SliceOp>(sliceOp).getOutRank(); 2154 if (slicedRank != outRank) 2155 return emitOpError("result type rank and rank after applying slice " 2156 "operand must match"); 2157 } 2158 } else { 2159 // Reshaping case 2160 unsigned shapeRank = inputRank; 2161 if (auto shapeVal = getShape()) { 2162 auto ty = shapeVal.getType(); 2163 if (auto shapeTy = ty.dyn_cast<fir::ShapeType>()) { 2164 shapeRank = shapeTy.getRank(); 2165 } else if (auto shapeShiftTy = ty.dyn_cast<fir::ShapeShiftType>()) { 2166 shapeRank = shapeShiftTy.getRank(); 2167 } else { 2168 auto shiftTy = ty.cast<fir::ShiftType>(); 2169 shapeRank = shiftTy.getRank(); 2170 if (shapeRank != inputRank) 2171 return emitOpError("shape operand and input box ranks must match " 2172 "when the shape is a fir.shift"); 2173 } 2174 } 2175 if (shapeRank != outRank) 2176 return emitOpError("result type and shape operand ranks must match"); 2177 } 2178 2179 if (inputEleTy != outEleTy) { 2180 // TODO: check that outBoxTy is a parent type of inputBoxTy for derived 2181 // types. 2182 // Character input and output types with constant length may be different if 2183 // there is a substring in the slice, otherwise, they must match. If any of 2184 // the types is a character with dynamic length, the other type can be any 2185 // character type. 2186 const bool typeCanMismatch = 2187 inputEleTy.isa<fir::RecordType>() || 2188 (getSlice() && inputEleTy.isa<fir::CharacterType>()) || 2189 areCompatibleCharacterTypes(inputEleTy, outEleTy); 2190 if (!typeCanMismatch) 2191 return emitOpError( 2192 "op input and output element types must match for intrinsic types"); 2193 } 2194 return mlir::success(); 2195 } 2196 2197 //===----------------------------------------------------------------------===// 2198 // ResultOp 2199 //===----------------------------------------------------------------------===// 2200 2201 mlir::LogicalResult ResultOp::verify() { 2202 auto *parentOp = (*this)->getParentOp(); 2203 auto results = parentOp->getResults(); 2204 auto operands = (*this)->getOperands(); 2205 2206 if (parentOp->getNumResults() != getNumOperands()) 2207 return emitOpError() << "parent of result must have same arity"; 2208 for (auto e : llvm::zip(results, operands)) 2209 if (std::get<0>(e).getType() != std::get<1>(e).getType()) 2210 return emitOpError() << "types mismatch between result op and its parent"; 2211 return success(); 2212 } 2213 2214 //===----------------------------------------------------------------------===// 2215 // SaveResultOp 2216 //===----------------------------------------------------------------------===// 2217 2218 mlir::LogicalResult SaveResultOp::verify() { 2219 auto resultType = getValue().getType(); 2220 if (resultType != fir::dyn_cast_ptrEleTy(getMemref().getType())) 2221 return emitOpError("value type must match memory reference type"); 2222 if (fir::isa_unknown_size_box(resultType)) 2223 return emitOpError("cannot save !fir.box of unknown rank or type"); 2224 2225 if (resultType.isa<fir::BoxType>()) { 2226 if (getShape() || !getTypeparams().empty()) 2227 return emitOpError( 2228 "must not have shape or length operands if the value is a fir.box"); 2229 return mlir::success(); 2230 } 2231 2232 // fir.record or fir.array case. 2233 unsigned shapeTyRank = 0; 2234 if (auto shapeVal = getShape()) { 2235 auto shapeTy = shapeVal.getType(); 2236 if (auto s = shapeTy.dyn_cast<fir::ShapeType>()) 2237 shapeTyRank = s.getRank(); 2238 else 2239 shapeTyRank = shapeTy.cast<fir::ShapeShiftType>().getRank(); 2240 } 2241 2242 auto eleTy = resultType; 2243 if (auto seqTy = resultType.dyn_cast<fir::SequenceType>()) { 2244 if (seqTy.getDimension() != shapeTyRank) 2245 emitOpError("shape operand must be provided and have the value rank " 2246 "when the value is a fir.array"); 2247 eleTy = seqTy.getEleTy(); 2248 } else { 2249 if (shapeTyRank != 0) 2250 emitOpError( 2251 "shape operand should only be provided if the value is a fir.array"); 2252 } 2253 2254 if (auto recTy = eleTy.dyn_cast<fir::RecordType>()) { 2255 if (recTy.getNumLenParams() != getTypeparams().size()) 2256 emitOpError("length parameters number must match with the value type " 2257 "length parameters"); 2258 } else if (auto charTy = eleTy.dyn_cast<fir::CharacterType>()) { 2259 if (getTypeparams().size() > 1) 2260 emitOpError("no more than one length parameter must be provided for " 2261 "character value"); 2262 } else { 2263 if (!getTypeparams().empty()) 2264 emitOpError("length parameters must not be provided for this value type"); 2265 } 2266 2267 return mlir::success(); 2268 } 2269 2270 //===----------------------------------------------------------------------===// 2271 // IntegralSwitchTerminator 2272 //===----------------------------------------------------------------------===// 2273 static constexpr llvm::StringRef getCompareOffsetAttr() { 2274 return "compare_operand_offsets"; 2275 } 2276 2277 static constexpr llvm::StringRef getTargetOffsetAttr() { 2278 return "target_operand_offsets"; 2279 } 2280 2281 template <typename OpT> 2282 static LogicalResult verifyIntegralSwitchTerminator(OpT op) { 2283 if (!(op.getSelector().getType().template isa<mlir::IntegerType>() || 2284 op.getSelector().getType().template isa<mlir::IndexType>() || 2285 op.getSelector().getType().template isa<fir::IntegerType>())) 2286 return op.emitOpError("must be an integer"); 2287 auto cases = 2288 op->template getAttrOfType<mlir::ArrayAttr>(op.getCasesAttr()).getValue(); 2289 auto count = op.getNumDest(); 2290 if (count == 0) 2291 return op.emitOpError("must have at least one successor"); 2292 if (op.getNumConditions() != count) 2293 return op.emitOpError("number of cases and targets don't match"); 2294 if (op.targetOffsetSize() != count) 2295 return op.emitOpError("incorrect number of successor operand groups"); 2296 for (decltype(count) i = 0; i != count; ++i) { 2297 if (!(cases[i].template isa<mlir::IntegerAttr, mlir::UnitAttr>())) 2298 return op.emitOpError("invalid case alternative"); 2299 } 2300 return mlir::success(); 2301 } 2302 2303 static mlir::ParseResult parseIntegralSwitchTerminator( 2304 mlir::OpAsmParser &parser, mlir::OperationState &result, 2305 llvm::StringRef casesAttr, llvm::StringRef operandSegmentAttr) { 2306 mlir::OpAsmParser::UnresolvedOperand selector; 2307 mlir::Type type; 2308 if (parseSelector(parser, result, selector, type)) 2309 return mlir::failure(); 2310 2311 llvm::SmallVector<mlir::Attribute> ivalues; 2312 llvm::SmallVector<mlir::Block *> dests; 2313 llvm::SmallVector<llvm::SmallVector<mlir::Value>> destArgs; 2314 while (true) { 2315 mlir::Attribute ivalue; // Integer or Unit 2316 mlir::Block *dest; 2317 llvm::SmallVector<mlir::Value> destArg; 2318 mlir::NamedAttrList temp; 2319 if (parser.parseAttribute(ivalue, "i", temp) || parser.parseComma() || 2320 parser.parseSuccessorAndUseList(dest, destArg)) 2321 return mlir::failure(); 2322 ivalues.push_back(ivalue); 2323 dests.push_back(dest); 2324 destArgs.push_back(destArg); 2325 if (!parser.parseOptionalRSquare()) 2326 break; 2327 if (parser.parseComma()) 2328 return mlir::failure(); 2329 } 2330 auto &bld = parser.getBuilder(); 2331 result.addAttribute(casesAttr, bld.getArrayAttr(ivalues)); 2332 llvm::SmallVector<int32_t> argOffs; 2333 int32_t sumArgs = 0; 2334 const auto count = dests.size(); 2335 for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) { 2336 result.addSuccessors(dests[i]); 2337 result.addOperands(destArgs[i]); 2338 auto argSize = destArgs[i].size(); 2339 argOffs.push_back(argSize); 2340 sumArgs += argSize; 2341 } 2342 result.addAttribute(operandSegmentAttr, 2343 bld.getI32VectorAttr({1, 0, sumArgs})); 2344 result.addAttribute(getTargetOffsetAttr(), bld.getI32VectorAttr(argOffs)); 2345 return mlir::success(); 2346 } 2347 2348 template <typename OpT> 2349 static void printIntegralSwitchTerminator(OpT op, mlir::OpAsmPrinter &p) { 2350 p << ' '; 2351 p.printOperand(op.getSelector()); 2352 p << " : " << op.getSelector().getType() << " ["; 2353 auto cases = 2354 op->template getAttrOfType<mlir::ArrayAttr>(op.getCasesAttr()).getValue(); 2355 auto count = op.getNumConditions(); 2356 for (decltype(count) i = 0; i != count; ++i) { 2357 if (i) 2358 p << ", "; 2359 auto &attr = cases[i]; 2360 if (auto intAttr = attr.template dyn_cast_or_null<mlir::IntegerAttr>()) 2361 p << intAttr.getValue(); 2362 else 2363 p.printAttribute(attr); 2364 p << ", "; 2365 op.printSuccessorAtIndex(p, i); 2366 } 2367 p << ']'; 2368 p.printOptionalAttrDict( 2369 op->getAttrs(), {op.getCasesAttr(), getCompareOffsetAttr(), 2370 getTargetOffsetAttr(), op.getOperandSegmentSizeAttr()}); 2371 } 2372 2373 //===----------------------------------------------------------------------===// 2374 // SelectOp 2375 //===----------------------------------------------------------------------===// 2376 2377 mlir::LogicalResult fir::SelectOp::verify() { 2378 return verifyIntegralSwitchTerminator(*this); 2379 } 2380 2381 mlir::ParseResult fir::SelectOp::parse(mlir::OpAsmParser &parser, 2382 mlir::OperationState &result) { 2383 return parseIntegralSwitchTerminator(parser, result, getCasesAttr(), 2384 getOperandSegmentSizeAttr()); 2385 } 2386 2387 void fir::SelectOp::print(mlir::OpAsmPrinter &p) { 2388 printIntegralSwitchTerminator(*this, p); 2389 } 2390 2391 template <typename A, typename... AdditionalArgs> 2392 static A getSubOperands(unsigned pos, A allArgs, 2393 mlir::DenseIntElementsAttr ranges, 2394 AdditionalArgs &&...additionalArgs) { 2395 unsigned start = 0; 2396 for (unsigned i = 0; i < pos; ++i) 2397 start += (*(ranges.begin() + i)).getZExtValue(); 2398 return allArgs.slice(start, (*(ranges.begin() + pos)).getZExtValue(), 2399 std::forward<AdditionalArgs>(additionalArgs)...); 2400 } 2401 2402 static mlir::MutableOperandRange 2403 getMutableSuccessorOperands(unsigned pos, mlir::MutableOperandRange operands, 2404 StringRef offsetAttr) { 2405 Operation *owner = operands.getOwner(); 2406 NamedAttribute targetOffsetAttr = 2407 *owner->getAttrDictionary().getNamed(offsetAttr); 2408 return getSubOperands( 2409 pos, operands, targetOffsetAttr.getValue().cast<DenseIntElementsAttr>(), 2410 mlir::MutableOperandRange::OperandSegment(pos, targetOffsetAttr)); 2411 } 2412 2413 static unsigned denseElementsSize(mlir::DenseIntElementsAttr attr) { 2414 return attr.getNumElements(); 2415 } 2416 2417 llvm::Optional<mlir::OperandRange> fir::SelectOp::getCompareOperands(unsigned) { 2418 return {}; 2419 } 2420 2421 llvm::Optional<llvm::ArrayRef<mlir::Value>> 2422 fir::SelectOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) { 2423 return {}; 2424 } 2425 2426 llvm::Optional<mlir::MutableOperandRange> 2427 fir::SelectOp::getMutableSuccessorOperands(unsigned oper) { 2428 return ::getMutableSuccessorOperands(oper, getTargetArgsMutable(), 2429 getTargetOffsetAttr()); 2430 } 2431 2432 llvm::Optional<llvm::ArrayRef<mlir::Value>> 2433 fir::SelectOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands, 2434 unsigned oper) { 2435 auto a = 2436 (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr()); 2437 auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2438 getOperandSegmentSizeAttr()); 2439 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)}; 2440 } 2441 2442 llvm::Optional<mlir::ValueRange> 2443 fir::SelectOp::getSuccessorOperands(mlir::ValueRange operands, unsigned oper) { 2444 auto a = 2445 (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr()); 2446 auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2447 getOperandSegmentSizeAttr()); 2448 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)}; 2449 } 2450 2451 unsigned fir::SelectOp::targetOffsetSize() { 2452 return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2453 getTargetOffsetAttr())); 2454 } 2455 2456 //===----------------------------------------------------------------------===// 2457 // SelectCaseOp 2458 //===----------------------------------------------------------------------===// 2459 2460 llvm::Optional<mlir::OperandRange> 2461 fir::SelectCaseOp::getCompareOperands(unsigned cond) { 2462 auto a = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2463 getCompareOffsetAttr()); 2464 return {getSubOperands(cond, getCompareArgs(), a)}; 2465 } 2466 2467 llvm::Optional<llvm::ArrayRef<mlir::Value>> 2468 fir::SelectCaseOp::getCompareOperands(llvm::ArrayRef<mlir::Value> operands, 2469 unsigned cond) { 2470 auto a = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2471 getCompareOffsetAttr()); 2472 auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2473 getOperandSegmentSizeAttr()); 2474 return {getSubOperands(cond, getSubOperands(1, operands, segments), a)}; 2475 } 2476 2477 llvm::Optional<mlir::ValueRange> 2478 fir::SelectCaseOp::getCompareOperands(mlir::ValueRange operands, 2479 unsigned cond) { 2480 auto a = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2481 getCompareOffsetAttr()); 2482 auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2483 getOperandSegmentSizeAttr()); 2484 return {getSubOperands(cond, getSubOperands(1, operands, segments), a)}; 2485 } 2486 2487 llvm::Optional<mlir::MutableOperandRange> 2488 fir::SelectCaseOp::getMutableSuccessorOperands(unsigned oper) { 2489 return ::getMutableSuccessorOperands(oper, getTargetArgsMutable(), 2490 getTargetOffsetAttr()); 2491 } 2492 2493 llvm::Optional<llvm::ArrayRef<mlir::Value>> 2494 fir::SelectCaseOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands, 2495 unsigned oper) { 2496 auto a = 2497 (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr()); 2498 auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2499 getOperandSegmentSizeAttr()); 2500 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)}; 2501 } 2502 2503 llvm::Optional<mlir::ValueRange> 2504 fir::SelectCaseOp::getSuccessorOperands(mlir::ValueRange operands, 2505 unsigned oper) { 2506 auto a = 2507 (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr()); 2508 auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2509 getOperandSegmentSizeAttr()); 2510 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)}; 2511 } 2512 2513 // parser for fir.select_case Op 2514 mlir::ParseResult SelectCaseOp::parse(mlir::OpAsmParser &parser, 2515 mlir::OperationState &result) { 2516 mlir::OpAsmParser::UnresolvedOperand selector; 2517 mlir::Type type; 2518 if (parseSelector(parser, result, selector, type)) 2519 return mlir::failure(); 2520 2521 llvm::SmallVector<mlir::Attribute> attrs; 2522 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> opers; 2523 llvm::SmallVector<mlir::Block *> dests; 2524 llvm::SmallVector<llvm::SmallVector<mlir::Value>> destArgs; 2525 llvm::SmallVector<int32_t> argOffs; 2526 int32_t offSize = 0; 2527 while (true) { 2528 mlir::Attribute attr; 2529 mlir::Block *dest; 2530 llvm::SmallVector<mlir::Value> destArg; 2531 mlir::NamedAttrList temp; 2532 if (parser.parseAttribute(attr, "a", temp) || isValidCaseAttr(attr) || 2533 parser.parseComma()) 2534 return mlir::failure(); 2535 attrs.push_back(attr); 2536 if (attr.dyn_cast_or_null<mlir::UnitAttr>()) { 2537 argOffs.push_back(0); 2538 } else if (attr.dyn_cast_or_null<fir::ClosedIntervalAttr>()) { 2539 mlir::OpAsmParser::UnresolvedOperand oper1; 2540 mlir::OpAsmParser::UnresolvedOperand oper2; 2541 if (parser.parseOperand(oper1) || parser.parseComma() || 2542 parser.parseOperand(oper2) || parser.parseComma()) 2543 return mlir::failure(); 2544 opers.push_back(oper1); 2545 opers.push_back(oper2); 2546 argOffs.push_back(2); 2547 offSize += 2; 2548 } else { 2549 mlir::OpAsmParser::UnresolvedOperand oper; 2550 if (parser.parseOperand(oper) || parser.parseComma()) 2551 return mlir::failure(); 2552 opers.push_back(oper); 2553 argOffs.push_back(1); 2554 ++offSize; 2555 } 2556 if (parser.parseSuccessorAndUseList(dest, destArg)) 2557 return mlir::failure(); 2558 dests.push_back(dest); 2559 destArgs.push_back(destArg); 2560 if (mlir::succeeded(parser.parseOptionalRSquare())) 2561 break; 2562 if (parser.parseComma()) 2563 return mlir::failure(); 2564 } 2565 result.addAttribute(fir::SelectCaseOp::getCasesAttr(), 2566 parser.getBuilder().getArrayAttr(attrs)); 2567 if (parser.resolveOperands(opers, type, result.operands)) 2568 return mlir::failure(); 2569 llvm::SmallVector<int32_t> targOffs; 2570 int32_t toffSize = 0; 2571 const auto count = dests.size(); 2572 for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) { 2573 result.addSuccessors(dests[i]); 2574 result.addOperands(destArgs[i]); 2575 auto argSize = destArgs[i].size(); 2576 targOffs.push_back(argSize); 2577 toffSize += argSize; 2578 } 2579 auto &bld = parser.getBuilder(); 2580 result.addAttribute(fir::SelectCaseOp::getOperandSegmentSizeAttr(), 2581 bld.getI32VectorAttr({1, offSize, toffSize})); 2582 result.addAttribute(getCompareOffsetAttr(), bld.getI32VectorAttr(argOffs)); 2583 result.addAttribute(getTargetOffsetAttr(), bld.getI32VectorAttr(targOffs)); 2584 return mlir::success(); 2585 } 2586 2587 void SelectCaseOp::print(mlir::OpAsmPrinter &p) { 2588 p << ' '; 2589 p.printOperand(getSelector()); 2590 p << " : " << getSelector().getType() << " ["; 2591 auto cases = 2592 getOperation()->getAttrOfType<mlir::ArrayAttr>(getCasesAttr()).getValue(); 2593 auto count = getNumConditions(); 2594 for (decltype(count) i = 0; i != count; ++i) { 2595 if (i) 2596 p << ", "; 2597 p << cases[i] << ", "; 2598 if (!cases[i].isa<mlir::UnitAttr>()) { 2599 auto caseArgs = *getCompareOperands(i); 2600 p.printOperand(*caseArgs.begin()); 2601 p << ", "; 2602 if (cases[i].isa<fir::ClosedIntervalAttr>()) { 2603 p.printOperand(*(++caseArgs.begin())); 2604 p << ", "; 2605 } 2606 } 2607 printSuccessorAtIndex(p, i); 2608 } 2609 p << ']'; 2610 p.printOptionalAttrDict(getOperation()->getAttrs(), 2611 {getCasesAttr(), getCompareOffsetAttr(), 2612 getTargetOffsetAttr(), getOperandSegmentSizeAttr()}); 2613 } 2614 2615 unsigned fir::SelectCaseOp::compareOffsetSize() { 2616 return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2617 getCompareOffsetAttr())); 2618 } 2619 2620 unsigned fir::SelectCaseOp::targetOffsetSize() { 2621 return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2622 getTargetOffsetAttr())); 2623 } 2624 2625 void fir::SelectCaseOp::build(mlir::OpBuilder &builder, 2626 mlir::OperationState &result, 2627 mlir::Value selector, 2628 llvm::ArrayRef<mlir::Attribute> compareAttrs, 2629 llvm::ArrayRef<mlir::ValueRange> cmpOperands, 2630 llvm::ArrayRef<mlir::Block *> destinations, 2631 llvm::ArrayRef<mlir::ValueRange> destOperands, 2632 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 2633 result.addOperands(selector); 2634 result.addAttribute(getCasesAttr(), builder.getArrayAttr(compareAttrs)); 2635 llvm::SmallVector<int32_t> operOffs; 2636 int32_t operSize = 0; 2637 for (auto attr : compareAttrs) { 2638 if (attr.isa<fir::ClosedIntervalAttr>()) { 2639 operOffs.push_back(2); 2640 operSize += 2; 2641 } else if (attr.isa<mlir::UnitAttr>()) { 2642 operOffs.push_back(0); 2643 } else { 2644 operOffs.push_back(1); 2645 ++operSize; 2646 } 2647 } 2648 for (auto ops : cmpOperands) 2649 result.addOperands(ops); 2650 result.addAttribute(getCompareOffsetAttr(), 2651 builder.getI32VectorAttr(operOffs)); 2652 const auto count = destinations.size(); 2653 for (auto d : destinations) 2654 result.addSuccessors(d); 2655 const auto opCount = destOperands.size(); 2656 llvm::SmallVector<int32_t> argOffs; 2657 int32_t sumArgs = 0; 2658 for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) { 2659 if (i < opCount) { 2660 result.addOperands(destOperands[i]); 2661 const auto argSz = destOperands[i].size(); 2662 argOffs.push_back(argSz); 2663 sumArgs += argSz; 2664 } else { 2665 argOffs.push_back(0); 2666 } 2667 } 2668 result.addAttribute(getOperandSegmentSizeAttr(), 2669 builder.getI32VectorAttr({1, operSize, sumArgs})); 2670 result.addAttribute(getTargetOffsetAttr(), builder.getI32VectorAttr(argOffs)); 2671 result.addAttributes(attributes); 2672 } 2673 2674 /// This builder has a slightly simplified interface in that the list of 2675 /// operands need not be partitioned by the builder. Instead the operands are 2676 /// partitioned here, before being passed to the default builder. This 2677 /// partitioning is unchecked, so can go awry on bad input. 2678 void fir::SelectCaseOp::build(mlir::OpBuilder &builder, 2679 mlir::OperationState &result, 2680 mlir::Value selector, 2681 llvm::ArrayRef<mlir::Attribute> compareAttrs, 2682 llvm::ArrayRef<mlir::Value> cmpOpList, 2683 llvm::ArrayRef<mlir::Block *> destinations, 2684 llvm::ArrayRef<mlir::ValueRange> destOperands, 2685 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 2686 llvm::SmallVector<mlir::ValueRange> cmpOpers; 2687 auto iter = cmpOpList.begin(); 2688 for (auto &attr : compareAttrs) { 2689 if (attr.isa<fir::ClosedIntervalAttr>()) { 2690 cmpOpers.push_back(mlir::ValueRange({iter, iter + 2})); 2691 iter += 2; 2692 } else if (attr.isa<UnitAttr>()) { 2693 cmpOpers.push_back(mlir::ValueRange{}); 2694 } else { 2695 cmpOpers.push_back(mlir::ValueRange({iter, iter + 1})); 2696 ++iter; 2697 } 2698 } 2699 build(builder, result, selector, compareAttrs, cmpOpers, destinations, 2700 destOperands, attributes); 2701 } 2702 2703 mlir::LogicalResult SelectCaseOp::verify() { 2704 if (!(getSelector().getType().isa<mlir::IntegerType>() || 2705 getSelector().getType().isa<mlir::IndexType>() || 2706 getSelector().getType().isa<fir::IntegerType>() || 2707 getSelector().getType().isa<fir::LogicalType>() || 2708 getSelector().getType().isa<fir::CharacterType>())) 2709 return emitOpError("must be an integer, character, or logical"); 2710 auto cases = 2711 getOperation()->getAttrOfType<mlir::ArrayAttr>(getCasesAttr()).getValue(); 2712 auto count = getNumDest(); 2713 if (count == 0) 2714 return emitOpError("must have at least one successor"); 2715 if (getNumConditions() != count) 2716 return emitOpError("number of conditions and successors don't match"); 2717 if (compareOffsetSize() != count) 2718 return emitOpError("incorrect number of compare operand groups"); 2719 if (targetOffsetSize() != count) 2720 return emitOpError("incorrect number of successor operand groups"); 2721 for (decltype(count) i = 0; i != count; ++i) { 2722 auto &attr = cases[i]; 2723 if (!(attr.isa<fir::PointIntervalAttr>() || 2724 attr.isa<fir::LowerBoundAttr>() || attr.isa<fir::UpperBoundAttr>() || 2725 attr.isa<fir::ClosedIntervalAttr>() || attr.isa<mlir::UnitAttr>())) 2726 return emitOpError("incorrect select case attribute type"); 2727 } 2728 return mlir::success(); 2729 } 2730 2731 //===----------------------------------------------------------------------===// 2732 // SelectRankOp 2733 //===----------------------------------------------------------------------===// 2734 2735 LogicalResult fir::SelectRankOp::verify() { 2736 return verifyIntegralSwitchTerminator(*this); 2737 } 2738 2739 mlir::ParseResult fir::SelectRankOp::parse(mlir::OpAsmParser &parser, 2740 mlir::OperationState &result) { 2741 return parseIntegralSwitchTerminator(parser, result, getCasesAttr(), 2742 getOperandSegmentSizeAttr()); 2743 } 2744 2745 void fir::SelectRankOp::print(mlir::OpAsmPrinter &p) { 2746 printIntegralSwitchTerminator(*this, p); 2747 } 2748 2749 llvm::Optional<mlir::OperandRange> 2750 fir::SelectRankOp::getCompareOperands(unsigned) { 2751 return {}; 2752 } 2753 2754 llvm::Optional<llvm::ArrayRef<mlir::Value>> 2755 fir::SelectRankOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) { 2756 return {}; 2757 } 2758 2759 llvm::Optional<mlir::MutableOperandRange> 2760 fir::SelectRankOp::getMutableSuccessorOperands(unsigned oper) { 2761 return ::getMutableSuccessorOperands(oper, getTargetArgsMutable(), 2762 getTargetOffsetAttr()); 2763 } 2764 2765 llvm::Optional<llvm::ArrayRef<mlir::Value>> 2766 fir::SelectRankOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands, 2767 unsigned oper) { 2768 auto a = 2769 (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr()); 2770 auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2771 getOperandSegmentSizeAttr()); 2772 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)}; 2773 } 2774 2775 llvm::Optional<mlir::ValueRange> 2776 fir::SelectRankOp::getSuccessorOperands(mlir::ValueRange operands, 2777 unsigned oper) { 2778 auto a = 2779 (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr()); 2780 auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2781 getOperandSegmentSizeAttr()); 2782 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)}; 2783 } 2784 2785 unsigned fir::SelectRankOp::targetOffsetSize() { 2786 return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2787 getTargetOffsetAttr())); 2788 } 2789 2790 //===----------------------------------------------------------------------===// 2791 // SelectTypeOp 2792 //===----------------------------------------------------------------------===// 2793 2794 llvm::Optional<mlir::OperandRange> 2795 fir::SelectTypeOp::getCompareOperands(unsigned) { 2796 return {}; 2797 } 2798 2799 llvm::Optional<llvm::ArrayRef<mlir::Value>> 2800 fir::SelectTypeOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) { 2801 return {}; 2802 } 2803 2804 llvm::Optional<mlir::MutableOperandRange> 2805 fir::SelectTypeOp::getMutableSuccessorOperands(unsigned oper) { 2806 return ::getMutableSuccessorOperands(oper, getTargetArgsMutable(), 2807 getTargetOffsetAttr()); 2808 } 2809 2810 llvm::Optional<llvm::ArrayRef<mlir::Value>> 2811 fir::SelectTypeOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands, 2812 unsigned oper) { 2813 auto a = 2814 (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr()); 2815 auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2816 getOperandSegmentSizeAttr()); 2817 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)}; 2818 } 2819 2820 ParseResult SelectTypeOp::parse(OpAsmParser &parser, OperationState &result) { 2821 mlir::OpAsmParser::UnresolvedOperand selector; 2822 mlir::Type type; 2823 if (parseSelector(parser, result, selector, type)) 2824 return mlir::failure(); 2825 2826 llvm::SmallVector<mlir::Attribute> attrs; 2827 llvm::SmallVector<mlir::Block *> dests; 2828 llvm::SmallVector<llvm::SmallVector<mlir::Value>> destArgs; 2829 while (true) { 2830 mlir::Attribute attr; 2831 mlir::Block *dest; 2832 llvm::SmallVector<mlir::Value> destArg; 2833 mlir::NamedAttrList temp; 2834 if (parser.parseAttribute(attr, "a", temp) || parser.parseComma() || 2835 parser.parseSuccessorAndUseList(dest, destArg)) 2836 return mlir::failure(); 2837 attrs.push_back(attr); 2838 dests.push_back(dest); 2839 destArgs.push_back(destArg); 2840 if (mlir::succeeded(parser.parseOptionalRSquare())) 2841 break; 2842 if (parser.parseComma()) 2843 return mlir::failure(); 2844 } 2845 auto &bld = parser.getBuilder(); 2846 result.addAttribute(fir::SelectTypeOp::getCasesAttr(), 2847 bld.getArrayAttr(attrs)); 2848 llvm::SmallVector<int32_t> argOffs; 2849 int32_t offSize = 0; 2850 const auto count = dests.size(); 2851 for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) { 2852 result.addSuccessors(dests[i]); 2853 result.addOperands(destArgs[i]); 2854 auto argSize = destArgs[i].size(); 2855 argOffs.push_back(argSize); 2856 offSize += argSize; 2857 } 2858 result.addAttribute(fir::SelectTypeOp::getOperandSegmentSizeAttr(), 2859 bld.getI32VectorAttr({1, 0, offSize})); 2860 result.addAttribute(getTargetOffsetAttr(), bld.getI32VectorAttr(argOffs)); 2861 return mlir::success(); 2862 } 2863 2864 unsigned fir::SelectTypeOp::targetOffsetSize() { 2865 return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>( 2866 getTargetOffsetAttr())); 2867 } 2868 2869 void SelectTypeOp::print(mlir::OpAsmPrinter &p) { 2870 p << ' '; 2871 p.printOperand(getSelector()); 2872 p << " : " << getSelector().getType() << " ["; 2873 auto cases = 2874 getOperation()->getAttrOfType<mlir::ArrayAttr>(getCasesAttr()).getValue(); 2875 auto count = getNumConditions(); 2876 for (decltype(count) i = 0; i != count; ++i) { 2877 if (i) 2878 p << ", "; 2879 p << cases[i] << ", "; 2880 printSuccessorAtIndex(p, i); 2881 } 2882 p << ']'; 2883 p.printOptionalAttrDict(getOperation()->getAttrs(), 2884 {getCasesAttr(), getCompareOffsetAttr(), 2885 getTargetOffsetAttr(), 2886 fir::SelectTypeOp::getOperandSegmentSizeAttr()}); 2887 } 2888 2889 mlir::LogicalResult SelectTypeOp::verify() { 2890 if (!(getSelector().getType().isa<fir::BoxType>())) 2891 return emitOpError("must be a boxed type"); 2892 auto cases = 2893 getOperation()->getAttrOfType<mlir::ArrayAttr>(getCasesAttr()).getValue(); 2894 auto count = getNumDest(); 2895 if (count == 0) 2896 return emitOpError("must have at least one successor"); 2897 if (getNumConditions() != count) 2898 return emitOpError("number of conditions and successors don't match"); 2899 if (targetOffsetSize() != count) 2900 return emitOpError("incorrect number of successor operand groups"); 2901 for (decltype(count) i = 0; i != count; ++i) { 2902 auto &attr = cases[i]; 2903 if (!(attr.isa<fir::ExactTypeAttr>() || attr.isa<fir::SubclassAttr>() || 2904 attr.isa<mlir::UnitAttr>())) 2905 return emitOpError("invalid type-case alternative"); 2906 } 2907 return mlir::success(); 2908 } 2909 2910 void fir::SelectTypeOp::build(mlir::OpBuilder &builder, 2911 mlir::OperationState &result, 2912 mlir::Value selector, 2913 llvm::ArrayRef<mlir::Attribute> typeOperands, 2914 llvm::ArrayRef<mlir::Block *> destinations, 2915 llvm::ArrayRef<mlir::ValueRange> destOperands, 2916 llvm::ArrayRef<mlir::NamedAttribute> attributes) { 2917 result.addOperands(selector); 2918 result.addAttribute(getCasesAttr(), builder.getArrayAttr(typeOperands)); 2919 const auto count = destinations.size(); 2920 for (mlir::Block *dest : destinations) 2921 result.addSuccessors(dest); 2922 const auto opCount = destOperands.size(); 2923 llvm::SmallVector<int32_t> argOffs; 2924 int32_t sumArgs = 0; 2925 for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) { 2926 if (i < opCount) { 2927 result.addOperands(destOperands[i]); 2928 const auto argSz = destOperands[i].size(); 2929 argOffs.push_back(argSz); 2930 sumArgs += argSz; 2931 } else { 2932 argOffs.push_back(0); 2933 } 2934 } 2935 result.addAttribute(getOperandSegmentSizeAttr(), 2936 builder.getI32VectorAttr({1, 0, sumArgs})); 2937 result.addAttribute(getTargetOffsetAttr(), builder.getI32VectorAttr(argOffs)); 2938 result.addAttributes(attributes); 2939 } 2940 2941 //===----------------------------------------------------------------------===// 2942 // ShapeOp 2943 //===----------------------------------------------------------------------===// 2944 2945 mlir::LogicalResult ShapeOp::verify() { 2946 auto size = getExtents().size(); 2947 auto shapeTy = getType().dyn_cast<fir::ShapeType>(); 2948 assert(shapeTy && "must be a shape type"); 2949 if (shapeTy.getRank() != size) 2950 return emitOpError("shape type rank mismatch"); 2951 return mlir::success(); 2952 } 2953 2954 //===----------------------------------------------------------------------===// 2955 // ShapeShiftOp 2956 //===----------------------------------------------------------------------===// 2957 2958 mlir::LogicalResult ShapeShiftOp::verify() { 2959 auto size = getPairs().size(); 2960 if (size < 2 || size > 16 * 2) 2961 return emitOpError("incorrect number of args"); 2962 if (size % 2 != 0) 2963 return emitOpError("requires a multiple of 2 args"); 2964 auto shapeTy = getType().dyn_cast<fir::ShapeShiftType>(); 2965 assert(shapeTy && "must be a shape shift type"); 2966 if (shapeTy.getRank() * 2 != size) 2967 return emitOpError("shape type rank mismatch"); 2968 return mlir::success(); 2969 } 2970 2971 //===----------------------------------------------------------------------===// 2972 // ShiftOp 2973 //===----------------------------------------------------------------------===// 2974 2975 mlir::LogicalResult ShiftOp::verify() { 2976 auto size = getOrigins().size(); 2977 auto shiftTy = getType().dyn_cast<fir::ShiftType>(); 2978 assert(shiftTy && "must be a shift type"); 2979 if (shiftTy.getRank() != size) 2980 return emitOpError("shift type rank mismatch"); 2981 return mlir::success(); 2982 } 2983 2984 //===----------------------------------------------------------------------===// 2985 // SliceOp 2986 //===----------------------------------------------------------------------===// 2987 2988 void fir::SliceOp::build(mlir::OpBuilder &builder, mlir::OperationState &result, 2989 mlir::ValueRange trips, mlir::ValueRange path, 2990 mlir::ValueRange substr) { 2991 const auto rank = trips.size() / 3; 2992 auto sliceTy = fir::SliceType::get(builder.getContext(), rank); 2993 build(builder, result, sliceTy, trips, path, substr); 2994 } 2995 2996 /// Return the output rank of a slice op. The output rank must be between 1 and 2997 /// the rank of the array being sliced (inclusive). 2998 unsigned fir::SliceOp::getOutputRank(mlir::ValueRange triples) { 2999 unsigned rank = 0; 3000 if (!triples.empty()) { 3001 for (unsigned i = 1, end = triples.size(); i < end; i += 3) { 3002 auto *op = triples[i].getDefiningOp(); 3003 if (!mlir::isa_and_nonnull<fir::UndefOp>(op)) 3004 ++rank; 3005 } 3006 assert(rank > 0); 3007 } 3008 return rank; 3009 } 3010 3011 mlir::LogicalResult SliceOp::verify() { 3012 auto size = getTriples().size(); 3013 if (size < 3 || size > 16 * 3) 3014 return emitOpError("incorrect number of args for triple"); 3015 if (size % 3 != 0) 3016 return emitOpError("requires a multiple of 3 args"); 3017 auto sliceTy = getType().dyn_cast<fir::SliceType>(); 3018 assert(sliceTy && "must be a slice type"); 3019 if (sliceTy.getRank() * 3 != size) 3020 return emitOpError("slice type rank mismatch"); 3021 return mlir::success(); 3022 } 3023 3024 //===----------------------------------------------------------------------===// 3025 // StoreOp 3026 //===----------------------------------------------------------------------===// 3027 3028 mlir::Type fir::StoreOp::elementType(mlir::Type refType) { 3029 return fir::dyn_cast_ptrEleTy(refType); 3030 } 3031 3032 mlir::ParseResult StoreOp::parse(mlir::OpAsmParser &parser, 3033 mlir::OperationState &result) { 3034 mlir::Type type; 3035 mlir::OpAsmParser::UnresolvedOperand oper; 3036 mlir::OpAsmParser::UnresolvedOperand store; 3037 if (parser.parseOperand(oper) || parser.parseKeyword("to") || 3038 parser.parseOperand(store) || 3039 parser.parseOptionalAttrDict(result.attributes) || 3040 parser.parseColonType(type) || 3041 parser.resolveOperand(oper, fir::StoreOp::elementType(type), 3042 result.operands) || 3043 parser.resolveOperand(store, type, result.operands)) 3044 return mlir::failure(); 3045 return mlir::success(); 3046 } 3047 3048 void StoreOp::print(mlir::OpAsmPrinter &p) { 3049 p << ' '; 3050 p.printOperand(getValue()); 3051 p << " to "; 3052 p.printOperand(getMemref()); 3053 p.printOptionalAttrDict(getOperation()->getAttrs(), {}); 3054 p << " : " << getMemref().getType(); 3055 } 3056 3057 mlir::LogicalResult StoreOp::verify() { 3058 if (getValue().getType() != fir::dyn_cast_ptrEleTy(getMemref().getType())) 3059 return emitOpError("store value type must match memory reference type"); 3060 if (fir::isa_unknown_size_box(getValue().getType())) 3061 return emitOpError("cannot store !fir.box of unknown rank or type"); 3062 return mlir::success(); 3063 } 3064 3065 //===----------------------------------------------------------------------===// 3066 // StringLitOp 3067 //===----------------------------------------------------------------------===// 3068 3069 bool fir::StringLitOp::isWideValue() { 3070 auto eleTy = getType().cast<fir::SequenceType>().getEleTy(); 3071 return eleTy.cast<fir::CharacterType>().getFKind() != 1; 3072 } 3073 3074 static mlir::NamedAttribute 3075 mkNamedIntegerAttr(mlir::OpBuilder &builder, llvm::StringRef name, int64_t v) { 3076 assert(v > 0); 3077 return builder.getNamedAttr( 3078 name, builder.getIntegerAttr(builder.getIntegerType(64), v)); 3079 } 3080 3081 void fir::StringLitOp::build(mlir::OpBuilder &builder, OperationState &result, 3082 fir::CharacterType inType, llvm::StringRef val, 3083 llvm::Optional<int64_t> len) { 3084 auto valAttr = builder.getNamedAttr(value(), builder.getStringAttr(val)); 3085 int64_t length = len.hasValue() ? len.getValue() : inType.getLen(); 3086 auto lenAttr = mkNamedIntegerAttr(builder, size(), length); 3087 result.addAttributes({valAttr, lenAttr}); 3088 result.addTypes(inType); 3089 } 3090 3091 template <typename C> 3092 static mlir::ArrayAttr convertToArrayAttr(mlir::OpBuilder &builder, 3093 llvm::ArrayRef<C> xlist) { 3094 llvm::SmallVector<mlir::Attribute> attrs; 3095 auto ty = builder.getIntegerType(8 * sizeof(C)); 3096 for (auto ch : xlist) 3097 attrs.push_back(builder.getIntegerAttr(ty, ch)); 3098 return builder.getArrayAttr(attrs); 3099 } 3100 3101 void fir::StringLitOp::build(mlir::OpBuilder &builder, OperationState &result, 3102 fir::CharacterType inType, 3103 llvm::ArrayRef<char> vlist, 3104 llvm::Optional<int64_t> len) { 3105 auto valAttr = 3106 builder.getNamedAttr(xlist(), convertToArrayAttr(builder, vlist)); 3107 std::int64_t length = len.hasValue() ? len.getValue() : inType.getLen(); 3108 auto lenAttr = mkNamedIntegerAttr(builder, size(), length); 3109 result.addAttributes({valAttr, lenAttr}); 3110 result.addTypes(inType); 3111 } 3112 3113 void fir::StringLitOp::build(mlir::OpBuilder &builder, OperationState &result, 3114 fir::CharacterType inType, 3115 llvm::ArrayRef<char16_t> vlist, 3116 llvm::Optional<int64_t> len) { 3117 auto valAttr = 3118 builder.getNamedAttr(xlist(), convertToArrayAttr(builder, vlist)); 3119 std::int64_t length = len.hasValue() ? len.getValue() : inType.getLen(); 3120 auto lenAttr = mkNamedIntegerAttr(builder, size(), length); 3121 result.addAttributes({valAttr, lenAttr}); 3122 result.addTypes(inType); 3123 } 3124 3125 void fir::StringLitOp::build(mlir::OpBuilder &builder, OperationState &result, 3126 fir::CharacterType inType, 3127 llvm::ArrayRef<char32_t> vlist, 3128 llvm::Optional<int64_t> len) { 3129 auto valAttr = 3130 builder.getNamedAttr(xlist(), convertToArrayAttr(builder, vlist)); 3131 std::int64_t length = len.hasValue() ? len.getValue() : inType.getLen(); 3132 auto lenAttr = mkNamedIntegerAttr(builder, size(), length); 3133 result.addAttributes({valAttr, lenAttr}); 3134 result.addTypes(inType); 3135 } 3136 3137 mlir::ParseResult StringLitOp::parse(mlir::OpAsmParser &parser, 3138 mlir::OperationState &result) { 3139 auto &builder = parser.getBuilder(); 3140 mlir::Attribute val; 3141 mlir::NamedAttrList attrs; 3142 llvm::SMLoc trailingTypeLoc; 3143 if (parser.parseAttribute(val, "fake", attrs)) 3144 return mlir::failure(); 3145 if (auto v = val.dyn_cast<mlir::StringAttr>()) 3146 result.attributes.push_back( 3147 builder.getNamedAttr(fir::StringLitOp::value(), v)); 3148 else if (auto v = val.dyn_cast<mlir::ArrayAttr>()) 3149 result.attributes.push_back( 3150 builder.getNamedAttr(fir::StringLitOp::xlist(), v)); 3151 else 3152 return parser.emitError(parser.getCurrentLocation(), 3153 "found an invalid constant"); 3154 mlir::IntegerAttr sz; 3155 mlir::Type type; 3156 if (parser.parseLParen() || 3157 parser.parseAttribute(sz, fir::StringLitOp::size(), result.attributes) || 3158 parser.parseRParen() || parser.getCurrentLocation(&trailingTypeLoc) || 3159 parser.parseColonType(type)) 3160 return mlir::failure(); 3161 auto charTy = type.dyn_cast<fir::CharacterType>(); 3162 if (!charTy) 3163 return parser.emitError(trailingTypeLoc, "must have character type"); 3164 type = fir::CharacterType::get(builder.getContext(), charTy.getFKind(), 3165 sz.getInt()); 3166 if (!type || parser.addTypesToList(type, result.types)) 3167 return mlir::failure(); 3168 return mlir::success(); 3169 } 3170 3171 void StringLitOp::print(mlir::OpAsmPrinter &p) { 3172 p << ' ' << getValue() << '('; 3173 p << getSize().cast<mlir::IntegerAttr>().getValue() << ") : "; 3174 p.printType(getType()); 3175 } 3176 3177 mlir::LogicalResult StringLitOp::verify() { 3178 if (getSize().cast<mlir::IntegerAttr>().getValue().isNegative()) 3179 return emitOpError("size must be non-negative"); 3180 if (auto xl = getOperation()->getAttr(fir::StringLitOp::xlist())) { 3181 auto xList = xl.cast<mlir::ArrayAttr>(); 3182 for (auto a : xList) 3183 if (!a.isa<mlir::IntegerAttr>()) 3184 return emitOpError("values in list must be integers"); 3185 } 3186 return mlir::success(); 3187 } 3188 3189 //===----------------------------------------------------------------------===// 3190 // UnboxProcOp 3191 //===----------------------------------------------------------------------===// 3192 3193 mlir::LogicalResult UnboxProcOp::verify() { 3194 if (auto eleTy = fir::dyn_cast_ptrEleTy(getRefTuple().getType())) 3195 if (eleTy.isa<mlir::TupleType>()) 3196 return mlir::success(); 3197 return emitOpError("second output argument has bad type"); 3198 } 3199 3200 //===----------------------------------------------------------------------===// 3201 // IfOp 3202 //===----------------------------------------------------------------------===// 3203 3204 void fir::IfOp::build(mlir::OpBuilder &builder, OperationState &result, 3205 mlir::Value cond, bool withElseRegion) { 3206 build(builder, result, llvm::None, cond, withElseRegion); 3207 } 3208 3209 void fir::IfOp::build(mlir::OpBuilder &builder, OperationState &result, 3210 mlir::TypeRange resultTypes, mlir::Value cond, 3211 bool withElseRegion) { 3212 result.addOperands(cond); 3213 result.addTypes(resultTypes); 3214 3215 mlir::Region *thenRegion = result.addRegion(); 3216 thenRegion->push_back(new mlir::Block()); 3217 if (resultTypes.empty()) 3218 IfOp::ensureTerminator(*thenRegion, builder, result.location); 3219 3220 mlir::Region *elseRegion = result.addRegion(); 3221 if (withElseRegion) { 3222 elseRegion->push_back(new mlir::Block()); 3223 if (resultTypes.empty()) 3224 IfOp::ensureTerminator(*elseRegion, builder, result.location); 3225 } 3226 } 3227 3228 mlir::ParseResult IfOp::parse(OpAsmParser &parser, OperationState &result) { 3229 result.regions.reserve(2); 3230 mlir::Region *thenRegion = result.addRegion(); 3231 mlir::Region *elseRegion = result.addRegion(); 3232 3233 auto &builder = parser.getBuilder(); 3234 OpAsmParser::UnresolvedOperand cond; 3235 mlir::Type i1Type = builder.getIntegerType(1); 3236 if (parser.parseOperand(cond) || 3237 parser.resolveOperand(cond, i1Type, result.operands)) 3238 return mlir::failure(); 3239 3240 if (parser.parseOptionalArrowTypeList(result.types)) 3241 return mlir::failure(); 3242 3243 if (parser.parseRegion(*thenRegion, {}, {})) 3244 return mlir::failure(); 3245 IfOp::ensureTerminator(*thenRegion, parser.getBuilder(), result.location); 3246 3247 if (mlir::succeeded(parser.parseOptionalKeyword("else"))) { 3248 if (parser.parseRegion(*elseRegion, {}, {})) 3249 return mlir::failure(); 3250 IfOp::ensureTerminator(*elseRegion, parser.getBuilder(), result.location); 3251 } 3252 3253 // Parse the optional attribute list. 3254 if (parser.parseOptionalAttrDict(result.attributes)) 3255 return mlir::failure(); 3256 return mlir::success(); 3257 } 3258 3259 LogicalResult IfOp::verify() { 3260 if (getNumResults() != 0 && getElseRegion().empty()) 3261 return emitOpError("must have an else block if defining values"); 3262 3263 return mlir::success(); 3264 } 3265 3266 void IfOp::print(mlir::OpAsmPrinter &p) { 3267 bool printBlockTerminators = false; 3268 p << ' ' << getCondition(); 3269 if (!getResults().empty()) { 3270 p << " -> (" << getResultTypes() << ')'; 3271 printBlockTerminators = true; 3272 } 3273 p << ' '; 3274 p.printRegion(getThenRegion(), /*printEntryBlockArgs=*/false, 3275 printBlockTerminators); 3276 3277 // Print the 'else' regions if it exists and has a block. 3278 auto &otherReg = getElseRegion(); 3279 if (!otherReg.empty()) { 3280 p << " else "; 3281 p.printRegion(otherReg, /*printEntryBlockArgs=*/false, 3282 printBlockTerminators); 3283 } 3284 p.printOptionalAttrDict((*this)->getAttrs()); 3285 } 3286 3287 void fir::IfOp::resultToSourceOps(llvm::SmallVectorImpl<mlir::Value> &results, 3288 unsigned resultNum) { 3289 auto *term = getThenRegion().front().getTerminator(); 3290 if (resultNum < term->getNumOperands()) 3291 results.push_back(term->getOperand(resultNum)); 3292 term = getElseRegion().front().getTerminator(); 3293 if (resultNum < term->getNumOperands()) 3294 results.push_back(term->getOperand(resultNum)); 3295 } 3296 3297 //===----------------------------------------------------------------------===// 3298 3299 mlir::ParseResult fir::isValidCaseAttr(mlir::Attribute attr) { 3300 if (attr.dyn_cast_or_null<mlir::UnitAttr>() || 3301 attr.dyn_cast_or_null<ClosedIntervalAttr>() || 3302 attr.dyn_cast_or_null<PointIntervalAttr>() || 3303 attr.dyn_cast_or_null<LowerBoundAttr>() || 3304 attr.dyn_cast_or_null<UpperBoundAttr>()) 3305 return mlir::success(); 3306 return mlir::failure(); 3307 } 3308 3309 unsigned fir::getCaseArgumentOffset(llvm::ArrayRef<mlir::Attribute> cases, 3310 unsigned dest) { 3311 unsigned o = 0; 3312 for (unsigned i = 0; i < dest; ++i) { 3313 auto &attr = cases[i]; 3314 if (!attr.dyn_cast_or_null<mlir::UnitAttr>()) { 3315 ++o; 3316 if (attr.dyn_cast_or_null<ClosedIntervalAttr>()) 3317 ++o; 3318 } 3319 } 3320 return o; 3321 } 3322 3323 mlir::ParseResult 3324 fir::parseSelector(mlir::OpAsmParser &parser, mlir::OperationState &result, 3325 mlir::OpAsmParser::UnresolvedOperand &selector, 3326 mlir::Type &type) { 3327 if (parser.parseOperand(selector) || parser.parseColonType(type) || 3328 parser.resolveOperand(selector, type, result.operands) || 3329 parser.parseLSquare()) 3330 return mlir::failure(); 3331 return mlir::success(); 3332 } 3333 3334 bool fir::isReferenceLike(mlir::Type type) { 3335 return type.isa<fir::ReferenceType>() || type.isa<fir::HeapType>() || 3336 type.isa<fir::PointerType>(); 3337 } 3338 3339 mlir::FuncOp fir::createFuncOp(mlir::Location loc, mlir::ModuleOp module, 3340 StringRef name, mlir::FunctionType type, 3341 llvm::ArrayRef<mlir::NamedAttribute> attrs) { 3342 if (auto f = module.lookupSymbol<mlir::FuncOp>(name)) 3343 return f; 3344 mlir::OpBuilder modBuilder(module.getBodyRegion()); 3345 modBuilder.setInsertionPointToEnd(module.getBody()); 3346 auto result = modBuilder.create<mlir::FuncOp>(loc, name, type, attrs); 3347 result.setVisibility(mlir::SymbolTable::Visibility::Private); 3348 return result; 3349 } 3350 3351 fir::GlobalOp fir::createGlobalOp(mlir::Location loc, mlir::ModuleOp module, 3352 StringRef name, mlir::Type type, 3353 llvm::ArrayRef<mlir::NamedAttribute> attrs) { 3354 if (auto g = module.lookupSymbol<fir::GlobalOp>(name)) 3355 return g; 3356 mlir::OpBuilder modBuilder(module.getBodyRegion()); 3357 auto result = modBuilder.create<fir::GlobalOp>(loc, name, type, attrs); 3358 result.setVisibility(mlir::SymbolTable::Visibility::Private); 3359 return result; 3360 } 3361 3362 bool fir::hasHostAssociationArgument(mlir::FuncOp func) { 3363 if (auto allArgAttrs = func.getAllArgAttrs()) 3364 for (auto attr : allArgAttrs) 3365 if (auto dict = attr.template dyn_cast_or_null<mlir::DictionaryAttr>()) 3366 if (dict.get(fir::getHostAssocAttrName())) 3367 return true; 3368 return false; 3369 } 3370 3371 bool fir::valueHasFirAttribute(mlir::Value value, 3372 llvm::StringRef attributeName) { 3373 // If this is a fir.box that was loaded, the fir attributes will be on the 3374 // related fir.ref<fir.box> creation. 3375 if (value.getType().isa<fir::BoxType>()) 3376 if (auto definingOp = value.getDefiningOp()) 3377 if (auto loadOp = mlir::dyn_cast<fir::LoadOp>(definingOp)) 3378 value = loadOp.getMemref(); 3379 // If this is a function argument, look in the argument attributes. 3380 if (auto blockArg = value.dyn_cast<mlir::BlockArgument>()) { 3381 if (blockArg.getOwner() && blockArg.getOwner()->isEntryBlock()) 3382 if (auto funcOp = 3383 mlir::dyn_cast<mlir::FuncOp>(blockArg.getOwner()->getParentOp())) 3384 if (funcOp.getArgAttr(blockArg.getArgNumber(), attributeName)) 3385 return true; 3386 return false; 3387 } 3388 3389 if (auto definingOp = value.getDefiningOp()) { 3390 // If this is an allocated value, look at the allocation attributes. 3391 if (mlir::isa<fir::AllocMemOp>(definingOp) || 3392 mlir::isa<AllocaOp>(definingOp)) 3393 return definingOp->hasAttr(attributeName); 3394 // If this is an imported global, look at AddrOfOp and GlobalOp attributes. 3395 // Both operations are looked at because use/host associated variable (the 3396 // AddrOfOp) can have ASYNCHRONOUS/VOLATILE attributes even if the ultimate 3397 // entity (the globalOp) does not have them. 3398 if (auto addressOfOp = mlir::dyn_cast<fir::AddrOfOp>(definingOp)) { 3399 if (addressOfOp->hasAttr(attributeName)) 3400 return true; 3401 if (auto module = definingOp->getParentOfType<mlir::ModuleOp>()) 3402 if (auto globalOp = 3403 module.lookupSymbol<fir::GlobalOp>(addressOfOp.getSymbol())) 3404 return globalOp->hasAttr(attributeName); 3405 } 3406 } 3407 // TODO: Construct associated entities attributes. Decide where the fir 3408 // attributes must be placed/looked for in this case. 3409 return false; 3410 } 3411 3412 bool fir::anyFuncArgsHaveAttr(mlir::FuncOp func, llvm::StringRef attr) { 3413 for (unsigned i = 0, end = func.getNumArguments(); i < end; ++i) 3414 if (func.getArgAttr(i, attr)) 3415 return true; 3416 return false; 3417 } 3418 3419 mlir::Type fir::applyPathToType(mlir::Type eleTy, mlir::ValueRange path) { 3420 for (auto i = path.begin(), end = path.end(); eleTy && i < end;) { 3421 eleTy = llvm::TypeSwitch<mlir::Type, mlir::Type>(eleTy) 3422 .Case<fir::RecordType>([&](fir::RecordType ty) { 3423 if (auto *op = (*i++).getDefiningOp()) { 3424 if (auto off = mlir::dyn_cast<fir::FieldIndexOp>(op)) 3425 return ty.getType(off.getFieldName()); 3426 if (auto off = mlir::dyn_cast<mlir::arith::ConstantOp>(op)) 3427 return ty.getType(fir::toInt(off)); 3428 } 3429 return mlir::Type{}; 3430 }) 3431 .Case<fir::SequenceType>([&](fir::SequenceType ty) { 3432 bool valid = true; 3433 const auto rank = ty.getDimension(); 3434 for (std::remove_const_t<decltype(rank)> ii = 0; 3435 valid && ii < rank; ++ii) 3436 valid = i < end && fir::isa_integer((*i++).getType()); 3437 return valid ? ty.getEleTy() : mlir::Type{}; 3438 }) 3439 .Case<mlir::TupleType>([&](mlir::TupleType ty) { 3440 if (auto *op = (*i++).getDefiningOp()) 3441 if (auto off = mlir::dyn_cast<mlir::arith::ConstantOp>(op)) 3442 return ty.getType(fir::toInt(off)); 3443 return mlir::Type{}; 3444 }) 3445 .Case<fir::ComplexType>([&](fir::ComplexType ty) { 3446 if (fir::isa_integer((*i++).getType())) 3447 return ty.getElementType(); 3448 return mlir::Type{}; 3449 }) 3450 .Case<mlir::ComplexType>([&](mlir::ComplexType ty) { 3451 if (fir::isa_integer((*i++).getType())) 3452 return ty.getElementType(); 3453 return mlir::Type{}; 3454 }) 3455 .Default([&](const auto &) { return mlir::Type{}; }); 3456 } 3457 return eleTy; 3458 } 3459 3460 // Tablegen operators 3461 3462 #define GET_OP_CLASSES 3463 #include "flang/Optimizer/Dialect/FIROps.cpp.inc" 3464