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