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