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