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