Debian Codegraph @

flang/lib/Optimizer/Dialect/FIROps.cpp

raw
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/FIRDialect.h"
16 #include "flang/Optimizer/Dialect/FIROpsSupport.h"
17 #include "flang/Optimizer/Dialect/FIRType.h"
18 #include "flang/Optimizer/Dialect/Support/FIRContext.h"
19 #include "flang/Optimizer/Dialect/Support/KindMapping.h"
20 #include "flang/Optimizer/Support/Utils.h"
21 #include "mlir/Dialect/CommonFolders.h"
22 #include "mlir/Dialect/Func/IR/FuncOps.h"
23 #include "mlir/Dialect/OpenACC/OpenACC.h"
24 #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
25 #include "mlir/IR/Attributes.h"
26 #include "mlir/IR/BuiltinAttributes.h"
27 #include "mlir/IR/BuiltinOps.h"
28 #include "mlir/IR/Diagnostics.h"
29 #include "mlir/IR/Matchers.h"
30 #include "mlir/IR/OpDefinition.h"
31 #include "mlir/IR/PatternMatch.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/TypeSwitch.h"
35
36 namespace {
37 #include "flang/Optimizer/Dialect/CanonicalizationPatterns.inc"
38 } // namespace
39
40 static void propagateAttributes(mlir::Operation *fromOp,
41 mlir::Operation *toOp) {
42 if (!fromOp || !toOp)
43 return;
44
45 for (mlir::NamedAttribute attr : fromOp->getAttrs()) {
46 if (attr.getName().getValue().starts_with(
47 mlir::acc::OpenACCDialect::getDialectNamespace()))
48 toOp->setAttr(attr.getName(), attr.getValue());
49 }
50 }
51
52 /// Return true if a sequence type is of some incomplete size or a record type
53 /// is malformed or contains an incomplete sequence type. An incomplete sequence
54 /// type is one with more unknown extents in the type than have been provided
55 /// via `dynamicExtents`. Sequence types with an unknown rank are incomplete by
56 /// definition.
57 static bool verifyInType(mlir::Type inType,
58 llvm::SmallVectorImpl<llvm::StringRef> &visited,
59 unsigned dynamicExtents = 0) {
60 if (auto st = mlir::dyn_cast<fir::SequenceType>(inType)) {
61 auto shape = st.getShape();
62 if (shape.size() == 0)
63 return true;
64 for (std::size_t i = 0, end = shape.size(); i < end; ++i) {
65 if (shape[i] != fir::SequenceType::getUnknownExtent())
66 continue;
67 if (dynamicExtents-- == 0)
68 return true;
69 }
70 } else if (auto rt = mlir::dyn_cast<fir::RecordType>(inType)) {
71 // don't recurse if we're already visiting this one
72 if (llvm::is_contained(visited, rt.getName()))
73 return false;
74 // keep track of record types currently being visited
75 visited.push_back(rt.getName());
76 for (auto &field : rt.getTypeList())
77 if (verifyInType(field.second, visited))
78 return true;
79 visited.pop_back();
80 }
81 return false;
82 }
83
84 static bool verifyTypeParamCount(mlir::Type inType, unsigned numParams) {
85 auto ty = fir::unwrapSequenceType(inType);
86 if (numParams > 0) {
87 if (auto recTy = mlir::dyn_cast<fir::RecordType>(ty))
88 return numParams != recTy.getNumLenParams();
89 if (auto chrTy = mlir::dyn_cast<fir::CharacterType>(ty))
90 return !(numParams == 1 && chrTy.hasDynamicLen());
91 return true;
92 }
93 if (auto chrTy = mlir::dyn_cast<fir::CharacterType>(ty))
94 return !chrTy.hasConstantLen();
95 return false;
96 }
97
98 /// Parser shared by Alloca and Allocmem
99 ///
100 /// operation ::= %res = (`fir.alloca` | `fir.allocmem`) $in_type
101 /// ( `(` $typeparams `)` )? ( `,` $shape )?
102 /// attr-dict-without-keyword
103 template <typename FN>
104 static mlir::ParseResult parseAllocatableOp(FN wrapResultType,
105 mlir::OpAsmParser &parser,
106 mlir::OperationState &result) {
107 mlir::Type intype;
108 if (parser.parseType(intype))
109 return mlir::failure();
110 auto &builder = parser.getBuilder();
111 result.addAttribute("in_type", mlir::TypeAttr::get(intype));
112 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> operands;
113 llvm::SmallVector<mlir::Type> typeVec;
114 bool hasOperands = false;
115 std::int32_t typeparamsSize = 0;
116 if (!parser.parseOptionalLParen()) {
117 // parse the LEN params of the derived type. (<params> : <types>)
118 if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::None) ||
119 parser.parseColonTypeList(typeVec) || parser.parseRParen())
120 return mlir::failure();
121 typeparamsSize = operands.size();
122 hasOperands = true;
123 }
124 std::int32_t shapeSize = 0;
125 if (!parser.parseOptionalComma()) {
126 // parse size to scale by, vector of n dimensions of type index
127 if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::None))
128 return mlir::failure();
129 shapeSize = operands.size() - typeparamsSize;
130 auto idxTy = builder.getIndexType();
131 for (std::int32_t i = typeparamsSize, end = operands.size(); i != end; ++i)
132 typeVec.push_back(idxTy);
133 hasOperands = true;
134 }
135 if (hasOperands &&
136 parser.resolveOperands(operands, typeVec, parser.getNameLoc(),
137 result.operands))
138 return mlir::failure();
139 mlir::Type restype = wrapResultType(intype);
140 if (!restype) {
141 parser.emitError(parser.getNameLoc(), "invalid allocate type: ") << intype;
142 return mlir::failure();
143 }
144 result.addAttribute("operandSegmentSizes", builder.getDenseI32ArrayAttr(
145 {typeparamsSize, shapeSize}));
146 if (parser.parseOptionalAttrDict(result.attributes) ||
147 parser.addTypeToList(restype, result.types))
148 return mlir::failure();
149 return mlir::success();
150 }
151
152 template <typename OP>
153 static void printAllocatableOp(mlir::OpAsmPrinter &p, OP &op) {
154 p << ' ' << op.getInType();
155 if (!op.getTypeparams().empty()) {
156 p << '(' << op.getTypeparams() << " : " << op.getTypeparams().getTypes()
157 << ')';
158 }
159 // print the shape of the allocation (if any); all must be index type
160 for (auto sh : op.getShape()) {
161 p << ", ";
162 p.printOperand(sh);
163 }
164 p.printOptionalAttrDict(op->getAttrs(), {"in_type", "operandSegmentSizes"});
165 }
166
167 //===----------------------------------------------------------------------===//
168 // AllocaOp
169 //===----------------------------------------------------------------------===//
170
171 /// Create a legal memory reference as return type
172 static mlir::Type wrapAllocaResultType(mlir::Type intype) {
173 // FIR semantics: memory references to memory references are disallowed
174 if (mlir::isa<fir::ReferenceType>(intype))
175 return {};
176 return fir::ReferenceType::get(intype);
177 }
178
179 mlir::Type fir::AllocaOp::getAllocatedType() {
180 return mlir::cast<fir::ReferenceType>(getType()).getEleTy();
181 }
182
183 mlir::Type fir::AllocaOp::getRefTy(mlir::Type ty) {
184 return fir::ReferenceType::get(ty);
185 }
186
187 void fir::AllocaOp::build(mlir::OpBuilder &builder,
188 mlir::OperationState &result, mlir::Type inType,
189 llvm::StringRef uniqName, mlir::ValueRange typeparams,
190 mlir::ValueRange shape,
191 llvm::ArrayRef<mlir::NamedAttribute> attributes) {
192 auto nameAttr = builder.getStringAttr(uniqName);
193 build(builder, result, wrapAllocaResultType(inType), inType, nameAttr, {},
194 /*pinned=*/false, typeparams, shape);
195 result.addAttributes(attributes);
196 }
197
198 void fir::AllocaOp::build(mlir::OpBuilder &builder,
199 mlir::OperationState &result, mlir::Type inType,
200 llvm::StringRef uniqName, bool pinned,
201 mlir::ValueRange typeparams, mlir::ValueRange shape,
202 llvm::ArrayRef<mlir::NamedAttribute> attributes) {
203 auto nameAttr = builder.getStringAttr(uniqName);
204 build(builder, result, wrapAllocaResultType(inType), inType, nameAttr, {},
205 pinned, typeparams, shape);
206 result.addAttributes(attributes);
207 }
208
209 void fir::AllocaOp::build(mlir::OpBuilder &builder,
210 mlir::OperationState &result, mlir::Type inType,
211 llvm::StringRef uniqName, llvm::StringRef bindcName,
212 mlir::ValueRange typeparams, 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=*/false, typeparams, shape);
220 result.addAttributes(attributes);
221 }
222
223 void fir::AllocaOp::build(mlir::OpBuilder &builder,
224 mlir::OperationState &result, mlir::Type inType,
225 llvm::StringRef uniqName, llvm::StringRef bindcName,
226 bool pinned, mlir::ValueRange typeparams,
227 mlir::ValueRange shape,
228 llvm::ArrayRef<mlir::NamedAttribute> attributes) {
229 auto nameAttr =
230 uniqName.empty() ? mlir::StringAttr{} : builder.getStringAttr(uniqName);
231 auto bindcAttr =
232 bindcName.empty() ? mlir::StringAttr{} : builder.getStringAttr(bindcName);
233 build(builder, result, wrapAllocaResultType(inType), inType, nameAttr,
234 bindcAttr, pinned, typeparams, shape);
235 result.addAttributes(attributes);
236 }
237
238 void fir::AllocaOp::build(mlir::OpBuilder &builder,
239 mlir::OperationState &result, mlir::Type inType,
240 mlir::ValueRange typeparams, mlir::ValueRange shape,
241 llvm::ArrayRef<mlir::NamedAttribute> attributes) {
242 build(builder, result, wrapAllocaResultType(inType), inType, {}, {},
243 /*pinned=*/false, typeparams, shape);
244 result.addAttributes(attributes);
245 }
246
247 void fir::AllocaOp::build(mlir::OpBuilder &builder,
248 mlir::OperationState &result, mlir::Type inType,
249 bool pinned, mlir::ValueRange typeparams,
250 mlir::ValueRange shape,
251 llvm::ArrayRef<mlir::NamedAttribute> attributes) {
252 build(builder, result, wrapAllocaResultType(inType), inType, {}, {}, pinned,
253 typeparams, shape);
254 result.addAttributes(attributes);
255 }
256
257 mlir::ParseResult fir::AllocaOp::parse(mlir::OpAsmParser &parser,
258 mlir::OperationState &result) {
259 return parseAllocatableOp(wrapAllocaResultType, parser, result);
260 }
261
262 void fir::AllocaOp::print(mlir::OpAsmPrinter &p) {
263 printAllocatableOp(p, *this);
264 }
265
266 llvm::LogicalResult fir::AllocaOp::verify() {
267 llvm::SmallVector<llvm::StringRef> visited;
268 if (verifyInType(getInType(), visited, numShapeOperands()))
269 return emitOpError("invalid type for allocation");
270 if (verifyTypeParamCount(getInType(), numLenParams()))
271 return emitOpError("LEN params do not correspond to type");
272 mlir::Type outType = getType();
273 if (!mlir::isa<fir::ReferenceType>(outType))
274 return emitOpError("must be a !fir.ref type");
275 return mlir::success();
276 }
277
278 bool fir::AllocaOp::ownsNestedAlloca(mlir::Operation *op) {
279 return op->hasTrait<mlir::OpTrait::IsIsolatedFromAbove>() ||
280 op->hasTrait<mlir::OpTrait::AutomaticAllocationScope>() ||
281 mlir::isa<mlir::LoopLikeOpInterface>(*op);
282 }
283
284 mlir::Region *fir::AllocaOp::getOwnerRegion() {
285 mlir::Operation *currentOp = getOperation();
286 while (mlir::Operation *parentOp = currentOp->getParentOp()) {
287 // If the operation was not registered, inquiries about its traits will be
288 // incorrect and it is not possible to reason about the operation. This
289 // should not happen in a normal Fortran compilation flow, but be foolproof.
290 if (!parentOp->isRegistered())
291 return nullptr;
292 if (fir::AllocaOp::ownsNestedAlloca(parentOp))
293 return currentOp->getParentRegion();
294 currentOp = parentOp;
295 }
296 return nullptr;
297 }
298
299 //===----------------------------------------------------------------------===//
300 // AllocMemOp
301 //===----------------------------------------------------------------------===//
302
303 /// Create a legal heap reference as return type
304 static mlir::Type wrapAllocMemResultType(mlir::Type intype) {
305 // Fortran semantics: C852 an entity cannot be both ALLOCATABLE and POINTER
306 // 8.5.3 note 1 prohibits ALLOCATABLE procedures as well
307 // FIR semantics: one may not allocate a memory reference value
308 if (mlir::isa<fir::ReferenceType, fir::HeapType, fir::PointerType,
309 mlir::FunctionType>(intype))
310 return {};
311 return fir::HeapType::get(intype);
312 }
313
314 mlir::Type fir::AllocMemOp::getAllocatedType() {
315 return mlir::cast<fir::HeapType>(getType()).getEleTy();
316 }
317
318 mlir::Type fir::AllocMemOp::getRefTy(mlir::Type ty) {
319 return fir::HeapType::get(ty);
320 }
321
322 void fir::AllocMemOp::build(mlir::OpBuilder &builder,
323 mlir::OperationState &result, mlir::Type inType,
324 llvm::StringRef uniqName,
325 mlir::ValueRange typeparams, mlir::ValueRange shape,
326 llvm::ArrayRef<mlir::NamedAttribute> attributes) {
327 auto nameAttr = builder.getStringAttr(uniqName);
328 build(builder, result, wrapAllocMemResultType(inType), inType, nameAttr, {},
329 typeparams, shape);
330 result.addAttributes(attributes);
331 }
332
333 void fir::AllocMemOp::build(mlir::OpBuilder &builder,
334 mlir::OperationState &result, mlir::Type inType,
335 llvm::StringRef uniqName, llvm::StringRef bindcName,
336 mlir::ValueRange typeparams, mlir::ValueRange shape,
337 llvm::ArrayRef<mlir::NamedAttribute> attributes) {
338 auto nameAttr = builder.getStringAttr(uniqName);
339 auto bindcAttr = builder.getStringAttr(bindcName);
340 build(builder, result, wrapAllocMemResultType(inType), inType, nameAttr,
341 bindcAttr, typeparams, shape);
342 result.addAttributes(attributes);
343 }
344
345 void fir::AllocMemOp::build(mlir::OpBuilder &builder,
346 mlir::OperationState &result, mlir::Type inType,
347 mlir::ValueRange typeparams, mlir::ValueRange shape,
348 llvm::ArrayRef<mlir::NamedAttribute> attributes) {
349 build(builder, result, wrapAllocMemResultType(inType), inType, {}, {},
350 typeparams, shape);
351 result.addAttributes(attributes);
352 }
353
354 mlir::ParseResult fir::AllocMemOp::parse(mlir::OpAsmParser &parser,
355 mlir::OperationState &result) {
356 return parseAllocatableOp(wrapAllocMemResultType, parser, result);
357 }
358
359 void fir::AllocMemOp::print(mlir::OpAsmPrinter &p) {
360 printAllocatableOp(p, *this);
361 }
362
363 llvm::LogicalResult fir::AllocMemOp::verify() {
364 llvm::SmallVector<llvm::StringRef> visited;
365 if (verifyInType(getInType(), visited, numShapeOperands()))
366 return emitOpError("invalid type for allocation");
367 if (verifyTypeParamCount(getInType(), numLenParams()))
368 return emitOpError("LEN params do not correspond to type");
369 mlir::Type outType = getType();
370 if (!mlir::dyn_cast<fir::HeapType>(outType))
371 return emitOpError("must be a !fir.heap type");
372 if (fir::isa_unknown_size_box(fir::dyn_cast_ptrEleTy(outType)))
373 return emitOpError("cannot allocate !fir.box of unknown rank or type");
374 return mlir::success();
375 }
376
377 //===----------------------------------------------------------------------===//
378 // ArrayCoorOp
379 //===----------------------------------------------------------------------===//
380
381 // CHARACTERs and derived types with LEN PARAMETERs are dependent types that
382 // require runtime values to fully define the type of an object.
383 static bool validTypeParams(mlir::Type dynTy, mlir::ValueRange typeParams) {
384 dynTy = fir::unwrapAllRefAndSeqType(dynTy);
385 // A box value will contain type parameter values itself.
386 if (mlir::isa<fir::BoxType>(dynTy))
387 return typeParams.size() == 0;
388 // Derived type must have all type parameters satisfied.
389 if (auto recTy = mlir::dyn_cast<fir::RecordType>(dynTy))
390 return typeParams.size() == recTy.getNumLenParams();
391 // Characters with non-constant LEN must have a type parameter value.
392 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(dynTy))
393 if (charTy.hasDynamicLen())
394 return typeParams.size() == 1;
395 // Otherwise, any type parameters are invalid.
396 return typeParams.size() == 0;
397 }
398
399 llvm::LogicalResult fir::ArrayCoorOp::verify() {
400 auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(getMemref().getType());
401 auto arrTy = mlir::dyn_cast<fir::SequenceType>(eleTy);
402 if (!arrTy)
403 return emitOpError("must be a reference to an array");
404 auto arrDim = arrTy.getDimension();
405
406 if (auto shapeOp = getShape()) {
407 auto shapeTy = shapeOp.getType();
408 unsigned shapeTyRank = 0;
409 if (auto s = mlir::dyn_cast<fir::ShapeType>(shapeTy)) {
410 shapeTyRank = s.getRank();
411 } else if (auto ss = mlir::dyn_cast<fir::ShapeShiftType>(shapeTy)) {
412 shapeTyRank = ss.getRank();
413 } else {
414 auto s = mlir::cast<fir::ShiftType>(shapeTy);
415 shapeTyRank = s.getRank();
416 // TODO: it looks like PreCGRewrite and CodeGen can support
417 // fir.shift with plain array reference, so we may consider
418 // removing this check.
419 if (!mlir::isa<fir::BaseBoxType>(getMemref().getType()))
420 return emitOpError("shift can only be provided with fir.box memref");
421 }
422 if (arrDim && arrDim != shapeTyRank)
423 return emitOpError("rank of dimension mismatched");
424 // TODO: support slicing with changing the number of dimensions,
425 // e.g. when array_coor represents an element access to array(:,1,:)
426 // slice: the shape is 3D and the number of indices is 2 in this case.
427 if (shapeTyRank != getIndices().size())
428 return emitOpError("number of indices do not match dim rank");
429 }
430
431 if (auto sliceOp = getSlice()) {
432 if (auto sl = mlir::dyn_cast_or_null<fir::SliceOp>(sliceOp.getDefiningOp()))
433 if (!sl.getSubstr().empty())
434 return emitOpError("array_coor cannot take a slice with substring");
435 if (auto sliceTy = mlir::dyn_cast<fir::SliceType>(sliceOp.getType()))
436 if (sliceTy.getRank() != arrDim)
437 return emitOpError("rank of dimension in slice mismatched");
438 }
439 if (!validTypeParams(getMemref().getType(), getTypeparams()))
440 return emitOpError("invalid type parameters");
441
442 return mlir::success();
443 }
444
445 // Pull in fir.embox and fir.rebox into fir.array_coor when possible.
446 struct SimplifyArrayCoorOp : public mlir::OpRewritePattern<fir::ArrayCoorOp> {
447 using mlir::OpRewritePattern<fir::ArrayCoorOp>::OpRewritePattern;
448 llvm::LogicalResult
449 matchAndRewrite(fir::ArrayCoorOp op,
450 mlir::PatternRewriter &rewriter) const override {
451 mlir::Value memref = op.getMemref();
452 if (!mlir::isa<fir::BaseBoxType>(memref.getType()))
453 return mlir::failure();
454
455 mlir::Value boxedMemref, boxedShape, boxedSlice;
456 if (auto emboxOp =
457 mlir::dyn_cast_or_null<fir::EmboxOp>(memref.getDefiningOp())) {
458 boxedMemref = emboxOp.getMemref();
459 boxedShape = emboxOp.getShape();
460 boxedSlice = emboxOp.getSlice();
461 // If any of operands, that are not currently supported for migration
462 // to ArrayCoorOp, is present, don't rewrite.
463 if (!emboxOp.getTypeparams().empty() || emboxOp.getSourceBox() ||
464 emboxOp.getAccessMap())
465 return mlir::failure();
466 } else if (auto reboxOp = mlir::dyn_cast_or_null<fir::ReboxOp>(
467 memref.getDefiningOp())) {
468 boxedMemref = reboxOp.getBox();
469 boxedShape = reboxOp.getShape();
470 // Avoid pulling in rebox that performs reshaping.
471 // There is no way to represent box reshaping with array_coor.
472 if (boxedShape && !mlir::isa<fir::ShiftType>(boxedShape.getType()))
473 return mlir::failure();
474 boxedSlice = reboxOp.getSlice();
475 } else {
476 return mlir::failure();
477 }
478
479 bool boxedShapeIsShift =
480 boxedShape && mlir::isa<fir::ShiftType>(boxedShape.getType());
481 bool boxedShapeIsShape =
482 boxedShape && mlir::isa<fir::ShapeType>(boxedShape.getType());
483 bool boxedShapeIsShapeShift =
484 boxedShape && mlir::isa<fir::ShapeShiftType>(boxedShape.getType());
485
486 // Slices changing the number of dimensions are not supported
487 // for array_coor yet.
488 unsigned origBoxRank;
489 if (mlir::isa<fir::BaseBoxType>(boxedMemref.getType()))
490 origBoxRank = fir::getBoxRank(boxedMemref.getType());
491 else if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(
492 fir::unwrapRefType(boxedMemref.getType())))
493 origBoxRank = arrTy.getDimension();
494 else
495 return mlir::failure();
496
497 if (fir::getBoxRank(memref.getType()) != origBoxRank)
498 return mlir::failure();
499
500 // Slices with substring are not supported by array_coor.
501 if (boxedSlice)
502 if (auto sliceOp =
503 mlir::dyn_cast_or_null<fir::SliceOp>(boxedSlice.getDefiningOp()))
504 if (!sliceOp.getSubstr().empty())
505 return mlir::failure();
506
507 // If embox/rebox and array_coor have conflicting shapes or slices,
508 // do nothing.
509 if (op.getShape() && boxedShape && boxedShape != op.getShape())
510 return mlir::failure();
511 if (op.getSlice() && boxedSlice && boxedSlice != op.getSlice())
512 return mlir::failure();
513
514 std::optional<IndicesVectorTy> shiftedIndices;
515 // The embox/rebox and array_coor either have compatible
516 // shape/slice at this point or shape/slice is null
517 // in one of them but not in the other.
518 // The compatibility means they are equal or both null.
519 if (!op.getShape()) {
520 if (boxedShape) {
521 if (op.getSlice()) {
522 if (!boxedSlice) {
523 if (boxedShapeIsShift) {
524 // %0 = fir.rebox %arg(%shift)
525 // %1 = fir.array_coor %0 [%slice] %idx
526 // Both the slice indices and %idx are 1-based, so the rebox
527 // may be pulled in as:
528 // %1 = fir.array_coor %arg [%slice] %idx
529 boxedShape = nullptr;
530 } else if (boxedShapeIsShape) {
531 // %0 = fir.embox %arg(%shape)
532 // %1 = fir.array_coor %0 [%slice] %idx
533 // Pull in as:
534 // %1 = fir.array_coor %arg(%shape) [%slice] %idx
535 } else if (boxedShapeIsShapeShift) {
536 // %0 = fir.embox %arg(%shapeshift)
537 // %1 = fir.array_coor %0 [%slice] %idx
538 // Pull in as:
539 // %shape = fir.shape <extents from the %shapeshift>
540 // %1 = fir.array_coor %arg(%shape) [%slice] %idx
541 boxedShape = getShapeFromShapeShift(boxedShape, rewriter);
542 if (!boxedShape)
543 return mlir::failure();
544 } else {
545 return mlir::failure();
546 }
547 } else {
548 if (boxedShapeIsShift) {
549 // %0 = fir.rebox %arg(%shift) [%slice]
550 // %1 = fir.array_coor %0 [%slice] %idx
551 // This FIR may only be valid if the shape specifies
552 // that all lower bounds are 1s and the slice's start indices
553 // and strides are all 1s.
554 // We could pull in the rebox as:
555 // %1 = fir.array_coor %arg [%slice] %idx
556 // Do not do anything for the time being.
557 return mlir::failure();
558 } else if (boxedShapeIsShape) {
559 // %0 = fir.embox %arg(%shape) [%slice]
560 // %1 = fir.array_coor %0 [%slice] %idx
561 // This FIR may only be valid if the slice's start indices
562 // and strides are all 1s.
563 // We could pull in the embox as:
564 // %1 = fir.array_coor %arg(%shape) [%slice] %idx
565 return mlir::failure();
566 } else if (boxedShapeIsShapeShift) {
567 // %0 = fir.embox %arg(%shapeshift) [%slice]
568 // %1 = fir.array_coor %0 [%slice] %idx
569 // This FIR may only be valid if the shape specifies
570 // that all lower bounds are 1s and the slice's start indices
571 // and strides are all 1s.
572 // We could pull in the embox as:
573 // %shape = fir.shape <extents from the %shapeshift>
574 // %1 = fir.array_coor %arg(%shape) [%slice] %idx
575 return mlir::failure();
576 } else {
577 return mlir::failure();
578 }
579 }
580 } else { // !op.getSlice()
581 if (!boxedSlice) {
582 if (boxedShapeIsShift) {
583 // %0 = fir.rebox %arg(%shift)
584 // %1 = fir.array_coor %0 %idx
585 // Pull in as:
586 // %1 = fir.array_coor %arg %idx
587 boxedShape = nullptr;
588 } else if (boxedShapeIsShape) {
589 // %0 = fir.embox %arg(%shape)
590 // %1 = fir.array_coor %0 %idx
591 // Pull in as:
592 // %1 = fir.array_coor %arg(%shape) %idx
593 } else if (boxedShapeIsShapeShift) {
594 // %0 = fir.embox %arg(%shapeshift)
595 // %1 = fir.array_coor %0 %idx
596 // Pull in as:
597 // %shape = fir.shape <extents from the %shapeshift>
598 // %1 = fir.array_coor %arg(%shape) %idx
599 boxedShape = getShapeFromShapeShift(boxedShape, rewriter);
600 if (!boxedShape)
601 return mlir::failure();
602 } else {
603 return mlir::failure();
604 }
605 } else {
606 if (boxedShapeIsShift) {
607 // %0 = fir.embox %arg(%shift) [%slice]
608 // %1 = fir.array_coor %0 %idx
609 // Pull in as:
610 // %tmp = arith.addi %idx, %shift.origin
611 // %idx_shifted = arith.subi %tmp, 1
612 // %1 = fir.array_coor %arg(%shift) %[slice] %idx_shifted
613 shiftedIndices =
614 getShiftedIndices(boxedShape, op.getIndices(), rewriter);
615 if (!shiftedIndices)
616 return mlir::failure();
617 } else if (boxedShapeIsShape) {
618 // %0 = fir.embox %arg(%shape) [%slice]
619 // %1 = fir.array_coor %0 %idx
620 // Pull in as:
621 // %1 = fir.array_coor %arg(%shape) %[slice] %idx
622 } else if (boxedShapeIsShapeShift) {
623 // %0 = fir.embox %arg(%shapeshift) [%slice]
624 // %1 = fir.array_coor %0 %idx
625 // Pull in as:
626 // %tmp = arith.addi %idx, %shapeshift.lb
627 // %idx_shifted = arith.subi %tmp, 1
628 // %1 = fir.array_coor %arg(%shapeshift) %[slice] %idx_shifted
629 shiftedIndices =
630 getShiftedIndices(boxedShape, op.getIndices(), rewriter);
631 if (!shiftedIndices)
632 return mlir::failure();
633 } else {
634 return mlir::failure();
635 }
636 }
637 }
638 } else { // !boxedShape
639 if (op.getSlice()) {
640 if (!boxedSlice) {
641 // %0 = fir.rebox %arg
642 // %1 = fir.array_coor %0 [%slice] %idx
643 // Pull in as:
644 // %1 = fir.array_coor %arg [%slice] %idx
645 } else {
646 // %0 = fir.rebox %arg [%slice]
647 // %1 = fir.array_coor %0 [%slice] %idx
648 // This is a valid FIR iff the slice's lower bounds
649 // and strides are all 1s.
650 // Pull in as:
651 // %1 = fir.array_coor %arg [%slice] %idx
652 }
653 } else { // !op.getSlice()
654 if (!boxedSlice) {
655 // %0 = fir.rebox %arg
656 // %1 = fir.array_coor %0 %idx
657 // Pull in as:
658 // %1 = fir.array_coor %arg %idx
659 } else {
660 // %0 = fir.rebox %arg [%slice]
661 // %1 = fir.array_coor %0 %idx
662 // Pull in as:
663 // %1 = fir.array_coor %arg [%slice] %idx
664 }
665 }
666 }
667 } else { // op.getShape()
668 if (boxedShape) {
669 // Check if pulling in non-default shape is correct.
670 if (op.getSlice()) {
671 if (!boxedSlice) {
672 // %0 = fir.embox %arg(%shape)
673 // %1 = fir.array_coor %0(%shape) [%slice] %idx
674 // Pull in as:
675 // %1 = fir.array_coor %arg(%shape) [%slice] %idx
676 } else {
677 // %0 = fir.embox %arg(%shape) [%slice]
678 // %1 = fir.array_coor %0(%shape) [%slice] %idx
679 // Pull in as:
680 // %1 = fir.array_coor %arg(%shape) [%slice] %idx
681 }
682 } else { // !op.getSlice()
683 if (!boxedSlice) {
684 // %0 = fir.embox %arg(%shape)
685 // %1 = fir.array_coor %0(%shape) %idx
686 // Pull in as:
687 // %1 = fir.array_coor %arg(%shape) %idx
688 } else {
689 // %0 = fir.embox %arg(%shape) [%slice]
690 // %1 = fir.array_coor %0(%shape) %idx
691 // Pull in as:
692 // %1 = fir.array_coor %arg(%shape) [%slice] %idx
693 }
694 }
695 } else { // !boxedShape
696 if (op.getSlice()) {
697 if (!boxedSlice) {
698 // %0 = fir.rebox %arg
699 // %1 = fir.array_coor %0(%shape) [%slice] %idx
700 // Pull in as:
701 // %1 = fir.array_coor %arg(%shape) [%slice] %idx
702 } else {
703 // %0 = fir.rebox %arg [%slice]
704 // %1 = fir.array_coor %0(%shape) [%slice] %idx
705 return mlir::failure();
706 }
707 } else { // !op.getSlice()
708 if (!boxedSlice) {
709 // %0 = fir.rebox %arg
710 // %1 = fir.array_coor %0(%shape) %idx
711 // Pull in as:
712 // %1 = fir.array_coor %arg(%shape) %idx
713 } else {
714 // %0 = fir.rebox %arg [%slice]
715 // %1 = fir.array_coor %0(%shape) %idx
716 // Cannot pull in without adjusting the slice indices.
717 return mlir::failure();
718 }
719 }
720 }
721 }
722
723 // TODO: temporarily avoid producing array_coor with the shape shift
724 // and plain array reference (it seems to be a limitation of
725 // ArrayCoorOp verifier).
726 if (!mlir::isa<fir::BaseBoxType>(boxedMemref.getType())) {
727 if (boxedShape) {
728 if (mlir::isa<fir::ShiftType>(boxedShape.getType()))
729 return mlir::failure();
730 } else if (op.getShape() &&
731 mlir::isa<fir::ShiftType>(op.getShape().getType())) {
732 return mlir::failure();
733 }
734 }
735
736 rewriter.modifyOpInPlace(op, [&]() {
737 op.getMemrefMutable().assign(boxedMemref);
738 if (boxedShape)
739 op.getShapeMutable().assign(boxedShape);
740 if (boxedSlice)
741 op.getSliceMutable().assign(boxedSlice);
742 if (shiftedIndices)
743 op.getIndicesMutable().assign(*shiftedIndices);
744 });
745 return mlir::success();
746 }
747
748 private:
749 using IndicesVectorTy = std::vector<mlir::Value>;
750
751 // If v is a shape_shift operation:
752 // fir.shape_shift %l1, %e1, %l2, %e2, ...
753 // create:
754 // fir.shape %e1, %e2, ...
755 static mlir::Value getShapeFromShapeShift(mlir::Value v,
756 mlir::PatternRewriter &rewriter) {
757 auto shapeShiftOp =
758 mlir::dyn_cast_or_null<fir::ShapeShiftOp>(v.getDefiningOp());
759 if (!shapeShiftOp)
760 return nullptr;
761 mlir::OpBuilder::InsertionGuard guard(rewriter);
762 rewriter.setInsertionPoint(shapeShiftOp);
763 return rewriter.create<fir::ShapeOp>(shapeShiftOp.getLoc(),
764 shapeShiftOp.getExtents());
765 }
766
767 static std::optional<IndicesVectorTy>
768 getShiftedIndices(mlir::Value v, mlir::ValueRange indices,
769 mlir::PatternRewriter &rewriter) {
770 auto insertAdjustments = [&](mlir::Operation *op, mlir::ValueRange lbs) {
771 // Compute the shifted indices using the extended type.
772 // Note that this can probably result in less efficient
773 // MLIR and further LLVM IR due to the extra conversions.
774 mlir::OpBuilder::InsertPoint savedIP = rewriter.saveInsertionPoint();
775 rewriter.setInsertionPoint(op);
776 mlir::Location loc = op->getLoc();
777 mlir::Type idxTy = rewriter.getIndexType();
778 mlir::Value one = rewriter.create<mlir::arith::ConstantOp>(
779 loc, idxTy, rewriter.getIndexAttr(1));
780 rewriter.restoreInsertionPoint(savedIP);
781 auto nsw = mlir::arith::IntegerOverflowFlags::nsw;
782
783 IndicesVectorTy shiftedIndices;
784 for (auto [lb, idx] : llvm::zip(lbs, indices)) {
785 mlir::Value extLb = rewriter.create<fir::ConvertOp>(loc, idxTy, lb);
786 mlir::Value extIdx = rewriter.create<fir::ConvertOp>(loc, idxTy, idx);
787 mlir::Value add =
788 rewriter.create<mlir::arith::AddIOp>(loc, extIdx, extLb, nsw);
789 mlir::Value sub =
790 rewriter.create<mlir::arith::SubIOp>(loc, add, one, nsw);
791 shiftedIndices.push_back(sub);
792 }
793
794 return shiftedIndices;
795 };
796
797 if (auto shiftOp =
798 mlir::dyn_cast_or_null<fir::ShiftOp>(v.getDefiningOp())) {
799 return insertAdjustments(shiftOp.getOperation(), shiftOp.getOrigins());
800 } else if (auto shapeShiftOp = mlir::dyn_cast_or_null<fir::ShapeShiftOp>(
801 v.getDefiningOp())) {
802 return insertAdjustments(shapeShiftOp.getOperation(),
803 shapeShiftOp.getOrigins());
804 }
805
806 return std::nullopt;
807 }
808 };
809
810 void fir::ArrayCoorOp::getCanonicalizationPatterns(
811 mlir::RewritePatternSet &patterns, mlir::MLIRContext *context) {
812 // TODO: !fir.shape<1> operand may be removed from array_coor always.
813 patterns.add<SimplifyArrayCoorOp>(context);
814 }
815
816 //===----------------------------------------------------------------------===//
817 // ArrayLoadOp
818 //===----------------------------------------------------------------------===//
819
820 static mlir::Type adjustedElementType(mlir::Type t) {
821 if (auto ty = mlir::dyn_cast<fir::ReferenceType>(t)) {
822 auto eleTy = ty.getEleTy();
823 if (fir::isa_char(eleTy))
824 return eleTy;
825 if (fir::isa_derived(eleTy))
826 return eleTy;
827 if (mlir::isa<fir::SequenceType>(eleTy))
828 return eleTy;
829 }
830 return t;
831 }
832
833 std::vector<mlir::Value> fir::ArrayLoadOp::getExtents() {
834 if (auto sh = getShape())
835 if (auto *op = sh.getDefiningOp()) {
836 if (auto shOp = mlir::dyn_cast<fir::ShapeOp>(op)) {
837 auto extents = shOp.getExtents();
838 return {extents.begin(), extents.end()};
839 }
840 return mlir::cast<fir::ShapeShiftOp>(op).getExtents();
841 }
842 return {};
843 }
844
845 llvm::LogicalResult fir::ArrayLoadOp::verify() {
846 auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(getMemref().getType());
847 auto arrTy = mlir::dyn_cast<fir::SequenceType>(eleTy);
848 if (!arrTy)
849 return emitOpError("must be a reference to an array");
850 auto arrDim = arrTy.getDimension();
851
852 if (auto shapeOp = getShape()) {
853 auto shapeTy = shapeOp.getType();
854 unsigned shapeTyRank = 0u;
855 if (auto s = mlir::dyn_cast<fir::ShapeType>(shapeTy)) {
856 shapeTyRank = s.getRank();
857 } else if (auto ss = mlir::dyn_cast<fir::ShapeShiftType>(shapeTy)) {
858 shapeTyRank = ss.getRank();
859 } else {
860 auto s = mlir::cast<fir::ShiftType>(shapeTy);
861 shapeTyRank = s.getRank();
862 if (!mlir::isa<fir::BaseBoxType>(getMemref().getType()))
863 return emitOpError("shift can only be provided with fir.box memref");
864 }
865 if (arrDim && arrDim != shapeTyRank)
866 return emitOpError("rank of dimension mismatched");
867 }
868
869 if (auto sliceOp = getSlice()) {
870 if (auto sl = mlir::dyn_cast_or_null<fir::SliceOp>(sliceOp.getDefiningOp()))
871 if (!sl.getSubstr().empty())
872 return emitOpError("array_load cannot take a slice with substring");
873 if (auto sliceTy = mlir::dyn_cast<fir::SliceType>(sliceOp.getType()))
874 if (sliceTy.getRank() != arrDim)
875 return emitOpError("rank of dimension in slice mismatched");
876 }
877
878 if (!validTypeParams(getMemref().getType(), getTypeparams()))
879 return emitOpError("invalid type parameters");
880
881 return mlir::success();
882 }
883
884 //===----------------------------------------------------------------------===//
885 // ArrayMergeStoreOp
886 //===----------------------------------------------------------------------===//
887
888 llvm::LogicalResult fir::ArrayMergeStoreOp::verify() {
889 if (!mlir::isa<fir::ArrayLoadOp>(getOriginal().getDefiningOp()))
890 return emitOpError("operand #0 must be result of a fir.array_load op");
891 if (auto sl = getSlice()) {
892 if (auto sliceOp =
893 mlir::dyn_cast_or_null<fir::SliceOp>(sl.getDefiningOp())) {
894 if (!sliceOp.getSubstr().empty())
895 return emitOpError(
896 "array_merge_store cannot take a slice with substring");
897 if (!sliceOp.getFields().empty()) {
898 // This is an intra-object merge, where the slice is projecting the
899 // subfields that are to be overwritten by the merge operation.
900 auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(getMemref().getType());
901 if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(eleTy)) {
902 auto projTy =
903 fir::applyPathToType(seqTy.getEleTy(), sliceOp.getFields());
904 if (fir::unwrapSequenceType(getOriginal().getType()) != projTy)
905 return emitOpError(
906 "type of origin does not match sliced memref type");
907 if (fir::unwrapSequenceType(getSequence().getType()) != projTy)
908 return emitOpError(
909 "type of sequence does not match sliced memref type");
910 return mlir::success();
911 }
912 return emitOpError("referenced type is not an array");
913 }
914 }
915 return mlir::success();
916 }
917 auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(getMemref().getType());
918 if (getOriginal().getType() != eleTy)
919 return emitOpError("type of origin does not match memref element type");
920 if (getSequence().getType() != eleTy)
921 return emitOpError("type of sequence does not match memref element type");
922 if (!validTypeParams(getMemref().getType(), getTypeparams()))
923 return emitOpError("invalid type parameters");
924 return mlir::success();
925 }
926
927 //===----------------------------------------------------------------------===//
928 // ArrayFetchOp
929 //===----------------------------------------------------------------------===//
930
931 // Template function used for both array_fetch and array_update verification.
932 template <typename A>
933 mlir::Type validArraySubobject(A op) {
934 auto ty = op.getSequence().getType();
935 return fir::applyPathToType(ty, op.getIndices());
936 }
937
938 llvm::LogicalResult fir::ArrayFetchOp::verify() {
939 auto arrTy = mlir::cast<fir::SequenceType>(getSequence().getType());
940 auto indSize = getIndices().size();
941 if (indSize < arrTy.getDimension())
942 return emitOpError("number of indices != dimension of array");
943 if (indSize == arrTy.getDimension() &&
944 ::adjustedElementType(getElement().getType()) != arrTy.getEleTy())
945 return emitOpError("return type does not match array");
946 auto ty = validArraySubobject(*this);
947 if (!ty || ty != ::adjustedElementType(getType()))
948 return emitOpError("return type and/or indices do not type check");
949 if (!mlir::isa<fir::ArrayLoadOp>(getSequence().getDefiningOp()))
950 return emitOpError("argument #0 must be result of fir.array_load");
951 if (!validTypeParams(arrTy, getTypeparams()))
952 return emitOpError("invalid type parameters");
953 return mlir::success();
954 }
955
956 //===----------------------------------------------------------------------===//
957 // ArrayAccessOp
958 //===----------------------------------------------------------------------===//
959
960 llvm::LogicalResult fir::ArrayAccessOp::verify() {
961 auto arrTy = mlir::cast<fir::SequenceType>(getSequence().getType());
962 std::size_t indSize = getIndices().size();
963 if (indSize < arrTy.getDimension())
964 return emitOpError("number of indices != dimension of array");
965 if (indSize == arrTy.getDimension() &&
966 getElement().getType() != fir::ReferenceType::get(arrTy.getEleTy()))
967 return emitOpError("return type does not match array");
968 mlir::Type ty = validArraySubobject(*this);
969 if (!ty || fir::ReferenceType::get(ty) != getType())
970 return emitOpError("return type and/or indices do not type check");
971 if (!validTypeParams(arrTy, getTypeparams()))
972 return emitOpError("invalid type parameters");
973 return mlir::success();
974 }
975
976 //===----------------------------------------------------------------------===//
977 // ArrayUpdateOp
978 //===----------------------------------------------------------------------===//
979
980 llvm::LogicalResult fir::ArrayUpdateOp::verify() {
981 if (fir::isa_ref_type(getMerge().getType()))
982 return emitOpError("does not support reference type for merge");
983 auto arrTy = mlir::cast<fir::SequenceType>(getSequence().getType());
984 auto indSize = getIndices().size();
985 if (indSize < arrTy.getDimension())
986 return emitOpError("number of indices != dimension of array");
987 if (indSize == arrTy.getDimension() &&
988 ::adjustedElementType(getMerge().getType()) != arrTy.getEleTy())
989 return emitOpError("merged value does not have element type");
990 auto ty = validArraySubobject(*this);
991 if (!ty || ty != ::adjustedElementType(getMerge().getType()))
992 return emitOpError("merged value and/or indices do not type check");
993 if (!validTypeParams(arrTy, getTypeparams()))
994 return emitOpError("invalid type parameters");
995 return mlir::success();
996 }
997
998 //===----------------------------------------------------------------------===//
999 // ArrayModifyOp
1000 //===----------------------------------------------------------------------===//
1001
1002 llvm::LogicalResult fir::ArrayModifyOp::verify() {
1003 auto arrTy = mlir::cast<fir::SequenceType>(getSequence().getType());
1004 auto indSize = getIndices().size();
1005 if (indSize < arrTy.getDimension())
1006 return emitOpError("number of indices must match array dimension");
1007 return mlir::success();
1008 }
1009
1010 //===----------------------------------------------------------------------===//
1011 // BoxAddrOp
1012 //===----------------------------------------------------------------------===//
1013
1014 void fir::BoxAddrOp::build(mlir::OpBuilder &builder,
1015 mlir::OperationState &result, mlir::Value val) {
1016 mlir::Type type =
1017 llvm::TypeSwitch<mlir::Type, mlir::Type>(val.getType())
1018 .Case<fir::BaseBoxType>([&](fir::BaseBoxType ty) -> mlir::Type {
1019 mlir::Type eleTy = ty.getEleTy();
1020 if (fir::isa_ref_type(eleTy))
1021 return eleTy;
1022 return fir::ReferenceType::get(eleTy);
1023 })
1024 .Case<fir::BoxCharType>([&](fir::BoxCharType ty) -> mlir::Type {
1025 return fir::ReferenceType::get(ty.getEleTy());
1026 })
1027 .Case<fir::BoxProcType>(
1028 [&](fir::BoxProcType ty) { return ty.getEleTy(); })
1029 .Default([&](const auto &) { return mlir::Type{}; });
1030 assert(type && "bad val type");
1031 build(builder, result, type, val);
1032 }
1033
1034 mlir::OpFoldResult fir::BoxAddrOp::fold(FoldAdaptor adaptor) {
1035 if (auto *v = getVal().getDefiningOp()) {
1036 if (auto box = mlir::dyn_cast<fir::EmboxOp>(v)) {
1037 // Fold only if not sliced
1038 if (!box.getSlice() && box.getMemref().getType() == getType()) {
1039 propagateAttributes(getOperation(), box.getMemref().getDefiningOp());
1040 return box.getMemref();
1041 }
1042 }
1043 if (auto box = mlir::dyn_cast<fir::EmboxCharOp>(v))
1044 if (box.getMemref().getType() == getType())
1045 return box.getMemref();
1046 }
1047 return {};
1048 }
1049
1050 //===----------------------------------------------------------------------===//
1051 // BoxCharLenOp
1052 //===----------------------------------------------------------------------===//
1053
1054 mlir::OpFoldResult fir::BoxCharLenOp::fold(FoldAdaptor adaptor) {
1055 if (auto v = getVal().getDefiningOp()) {
1056 if (auto box = mlir::dyn_cast<fir::EmboxCharOp>(v))
1057 return box.getLen();
1058 }
1059 return {};
1060 }
1061
1062 //===----------------------------------------------------------------------===//
1063 // BoxDimsOp
1064 //===----------------------------------------------------------------------===//
1065
1066 /// Get the result types packed in a tuple tuple
1067 mlir::Type fir::BoxDimsOp::getTupleType() {
1068 // note: triple, but 4 is nearest power of 2
1069 llvm::SmallVector<mlir::Type> triple{
1070 getResult(0).getType(), getResult(1).getType(), getResult(2).getType()};
1071 return mlir::TupleType::get(getContext(), triple);
1072 }
1073
1074 //===----------------------------------------------------------------------===//
1075 // BoxRankOp
1076 //===----------------------------------------------------------------------===//
1077
1078 void fir::BoxRankOp::getEffects(
1079 llvm::SmallVectorImpl<
1080 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
1081 &effects) {
1082 mlir::OpOperand &inputBox = getBoxMutable();
1083 if (fir::isBoxAddress(inputBox.get().getType()))
1084 effects.emplace_back(mlir::MemoryEffects::Read::get(), &inputBox,
1085 mlir::SideEffects::DefaultResource::get());
1086 }
1087
1088 //===----------------------------------------------------------------------===//
1089 // CallOp
1090 //===----------------------------------------------------------------------===//
1091
1092 mlir::FunctionType fir::CallOp::getFunctionType() {
1093 return mlir::FunctionType::get(getContext(), getOperandTypes(),
1094 getResultTypes());
1095 }
1096
1097 void fir::CallOp::print(mlir::OpAsmPrinter &p) {
1098 bool isDirect = getCallee().has_value();
1099 p << ' ';
1100 if (isDirect)
1101 p << *getCallee();
1102 else
1103 p << getOperand(0);
1104 p << '(' << (*this)->getOperands().drop_front(isDirect ? 0 : 1) << ')';
1105
1106 // Print 'fastmath<...>' (if it has non-default value) before
1107 // any other attributes.
1108 mlir::arith::FastMathFlagsAttr fmfAttr = getFastmathAttr();
1109 if (fmfAttr.getValue() != mlir::arith::FastMathFlags::none) {
1110 p << ' ' << mlir::arith::FastMathFlagsAttr::getMnemonic();
1111 p.printStrippedAttrOrType(fmfAttr);
1112 }
1113
1114 p.printOptionalAttrDict(
1115 (*this)->getAttrs(),
1116 {fir::CallOp::getCalleeAttrNameStr(), getFastmathAttrName()});
1117 auto resultTypes{getResultTypes()};
1118 llvm::SmallVector<mlir::Type> argTypes(
1119 llvm::drop_begin(getOperandTypes(), isDirect ? 0 : 1));
1120 p << " : " << mlir::FunctionType::get(getContext(), argTypes, resultTypes);
1121 }
1122
1123 mlir::ParseResult fir::CallOp::parse(mlir::OpAsmParser &parser,
1124 mlir::OperationState &result) {
1125 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> operands;
1126 if (parser.parseOperandList(operands))
1127 return mlir::failure();
1128
1129 mlir::NamedAttrList attrs;
1130 mlir::SymbolRefAttr funcAttr;
1131 bool isDirect = operands.empty();
1132 if (isDirect)
1133 if (parser.parseAttribute(funcAttr, fir::CallOp::getCalleeAttrNameStr(),
1134 attrs))
1135 return mlir::failure();
1136
1137 mlir::Type type;
1138 if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::Paren))
1139 return mlir::failure();
1140
1141 // Parse 'fastmath<...>', if present.
1142 mlir::arith::FastMathFlagsAttr fmfAttr;
1143 llvm::StringRef fmfAttrName = getFastmathAttrName(result.name);
1144 if (mlir::succeeded(parser.parseOptionalKeyword(fmfAttrName)))
1145 if (parser.parseCustomAttributeWithFallback(fmfAttr, mlir::Type{},
1146 fmfAttrName, attrs))
1147 return mlir::failure();
1148
1149 if (parser.parseOptionalAttrDict(attrs) || parser.parseColon() ||
1150 parser.parseType(type))
1151 return mlir::failure();
1152
1153 auto funcType = mlir::dyn_cast<mlir::FunctionType>(type);
1154 if (!funcType)
1155 return parser.emitError(parser.getNameLoc(), "expected function type");
1156 if (isDirect) {
1157 if (parser.resolveOperands(operands, funcType.getInputs(),
1158 parser.getNameLoc(), result.operands))
1159 return mlir::failure();
1160 } else {
1161 auto funcArgs =
1162 llvm::ArrayRef<mlir::OpAsmParser::UnresolvedOperand>(operands)
1163 .drop_front();
1164 if (parser.resolveOperand(operands[0], funcType, result.operands) ||
1165 parser.resolveOperands(funcArgs, funcType.getInputs(),
1166 parser.getNameLoc(), result.operands))
1167 return mlir::failure();
1168 }
1169 result.addTypes(funcType.getResults());
1170 result.attributes = attrs;
1171 return mlir::success();
1172 }
1173
1174 void fir::CallOp::build(mlir::OpBuilder &builder, mlir::OperationState &result,
1175 mlir::func::FuncOp callee, mlir::ValueRange operands) {
1176 result.addOperands(operands);
1177 result.addAttribute(getCalleeAttrNameStr(), mlir::SymbolRefAttr::get(callee));
1178 result.addTypes(callee.getFunctionType().getResults());
1179 }
1180
1181 void fir::CallOp::build(mlir::OpBuilder &builder, mlir::OperationState &result,
1182 mlir::SymbolRefAttr callee,
1183 llvm::ArrayRef<mlir::Type> results,
1184 mlir::ValueRange operands) {
1185 result.addOperands(operands);
1186 if (callee)
1187 result.addAttribute(getCalleeAttrNameStr(), callee);
1188 result.addTypes(results);
1189 }
1190
1191 //===----------------------------------------------------------------------===//
1192 // CharConvertOp
1193 //===----------------------------------------------------------------------===//
1194
1195 llvm::LogicalResult fir::CharConvertOp::verify() {
1196 auto unwrap = [&](mlir::Type t) {
1197 t = fir::unwrapSequenceType(fir::dyn_cast_ptrEleTy(t));
1198 return mlir::dyn_cast<fir::CharacterType>(t);
1199 };
1200 auto inTy = unwrap(getFrom().getType());
1201 auto outTy = unwrap(getTo().getType());
1202 if (!(inTy && outTy))
1203 return emitOpError("not a reference to a character");
1204 if (inTy.getFKind() == outTy.getFKind())
1205 return emitOpError("buffers must have different KIND values");
1206 return mlir::success();
1207 }
1208
1209 //===----------------------------------------------------------------------===//
1210 // CmpOp
1211 //===----------------------------------------------------------------------===//
1212
1213 template <typename OPTY>
1214 static void printCmpOp(mlir::OpAsmPrinter &p, OPTY op) {
1215 p << ' ';
1216 auto predSym = mlir::arith::symbolizeCmpFPredicate(
1217 op->template getAttrOfType<mlir::IntegerAttr>(
1218 OPTY::getPredicateAttrName())
1219 .getInt());
1220 assert(predSym.has_value() && "invalid symbol value for predicate");
1221 p << '"' << mlir::arith::stringifyCmpFPredicate(predSym.value()) << '"'
1222 << ", ";
1223 p.printOperand(op.getLhs());
1224 p << ", ";
1225 p.printOperand(op.getRhs());
1226 p.printOptionalAttrDict(op->getAttrs(),
1227 /*elidedAttrs=*/{OPTY::getPredicateAttrName()});
1228 p << " : " << op.getLhs().getType();
1229 }
1230
1231 template <typename OPTY>
1232 static mlir::ParseResult parseCmpOp(mlir::OpAsmParser &parser,
1233 mlir::OperationState &result) {
1234 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> ops;
1235 mlir::NamedAttrList attrs;
1236 mlir::Attribute predicateNameAttr;
1237 mlir::Type type;
1238 if (parser.parseAttribute(predicateNameAttr, OPTY::getPredicateAttrName(),
1239 attrs) ||
1240 parser.parseComma() || parser.parseOperandList(ops, 2) ||
1241 parser.parseOptionalAttrDict(attrs) || parser.parseColonType(type) ||
1242 parser.resolveOperands(ops, type, result.operands))
1243 return mlir::failure();
1244
1245 if (!mlir::isa<mlir::StringAttr>(predicateNameAttr))
1246 return parser.emitError(parser.getNameLoc(),
1247 "expected string comparison predicate attribute");
1248
1249 // Rewrite string attribute to an enum value.
1250 llvm::StringRef predicateName =
1251 mlir::cast<mlir::StringAttr>(predicateNameAttr).getValue();
1252 auto predicate = fir::CmpcOp::getPredicateByName(predicateName);
1253 auto builder = parser.getBuilder();
1254 mlir::Type i1Type = builder.getI1Type();
1255 attrs.set(OPTY::getPredicateAttrName(),
1256 builder.getI64IntegerAttr(static_cast<std::int64_t>(predicate)));
1257 result.attributes = attrs;
1258 result.addTypes({i1Type});
1259 return mlir::success();
1260 }
1261
1262 //===----------------------------------------------------------------------===//
1263 // CmpcOp
1264 //===----------------------------------------------------------------------===//
1265
1266 void fir::buildCmpCOp(mlir::OpBuilder &builder, mlir::OperationState &result,
1267 mlir::arith::CmpFPredicate predicate, mlir::Value lhs,
1268 mlir::Value rhs) {
1269 result.addOperands({lhs, rhs});
1270 result.types.push_back(builder.getI1Type());
1271 result.addAttribute(
1272 fir::CmpcOp::getPredicateAttrName(),
1273 builder.getI64IntegerAttr(static_cast<std::int64_t>(predicate)));
1274 }
1275
1276 mlir::arith::CmpFPredicate
1277 fir::CmpcOp::getPredicateByName(llvm::StringRef name) {
1278 auto pred = mlir::arith::symbolizeCmpFPredicate(name);
1279 assert(pred.has_value() && "invalid predicate name");
1280 return pred.value();
1281 }
1282
1283 void fir::CmpcOp::print(mlir::OpAsmPrinter &p) { printCmpOp(p, *this); }
1284
1285 mlir::ParseResult fir::CmpcOp::parse(mlir::OpAsmParser &parser,
1286 mlir::OperationState &result) {
1287 return parseCmpOp<fir::CmpcOp>(parser, result);
1288 }
1289
1290 //===----------------------------------------------------------------------===//
1291 // ConstcOp
1292 //===----------------------------------------------------------------------===//
1293
1294 mlir::ParseResult fir::ConstcOp::parse(mlir::OpAsmParser &parser,
1295 mlir::OperationState &result) {
1296 fir::RealAttr realp;
1297 fir::RealAttr imagp;
1298 mlir::Type type;
1299 if (parser.parseLParen() ||
1300 parser.parseAttribute(realp, fir::ConstcOp::getRealAttrName(),
1301 result.attributes) ||
1302 parser.parseComma() ||
1303 parser.parseAttribute(imagp, fir::ConstcOp::getImagAttrName(),
1304 result.attributes) ||
1305 parser.parseRParen() || parser.parseColonType(type) ||
1306 parser.addTypesToList(type, result.types))
1307 return mlir::failure();
1308 return mlir::success();
1309 }
1310
1311 void fir::ConstcOp::print(mlir::OpAsmPrinter &p) {
1312 p << '(';
1313 p << getOperation()->getAttr(fir::ConstcOp::getRealAttrName()) << ", ";
1314 p << getOperation()->getAttr(fir::ConstcOp::getImagAttrName()) << ") : ";
1315 p.printType(getType());
1316 }
1317
1318 llvm::LogicalResult fir::ConstcOp::verify() {
1319 if (!mlir::isa<fir::ComplexType>(getType()))
1320 return emitOpError("must be a !fir.complex type");
1321 return mlir::success();
1322 }
1323
1324 //===----------------------------------------------------------------------===//
1325 // ConvertOp
1326 //===----------------------------------------------------------------------===//
1327
1328 void fir::ConvertOp::getCanonicalizationPatterns(
1329 mlir::RewritePatternSet &results, mlir::MLIRContext *context) {
1330 results.insert<ConvertConvertOptPattern, ConvertAscendingIndexOptPattern,
1331 ConvertDescendingIndexOptPattern, RedundantConvertOptPattern,
1332 CombineConvertOptPattern, CombineConvertTruncOptPattern,
1333 ForwardConstantConvertPattern>(context);
1334 }
1335
1336 mlir::OpFoldResult fir::ConvertOp::fold(FoldAdaptor adaptor) {
1337 if (getValue().getType() == getType())
1338 return getValue();
1339 if (matchPattern(getValue(), mlir::m_Op<fir::ConvertOp>())) {
1340 auto inner = mlir::cast<fir::ConvertOp>(getValue().getDefiningOp());
1341 // (convert (convert 'a : logical -> i1) : i1 -> logical) ==> forward 'a
1342 if (auto toTy = mlir::dyn_cast<fir::LogicalType>(getType()))
1343 if (auto fromTy =
1344 mlir::dyn_cast<fir::LogicalType>(inner.getValue().getType()))
1345 if (mlir::isa<mlir::IntegerType>(inner.getType()) && (toTy == fromTy))
1346 return inner.getValue();
1347 // (convert (convert 'a : i1 -> logical) : logical -> i1) ==> forward 'a
1348 if (auto toTy = mlir::dyn_cast<mlir::IntegerType>(getType()))
1349 if (auto fromTy =
1350 mlir::dyn_cast<mlir::IntegerType>(inner.getValue().getType()))
1351 if (mlir::isa<fir::LogicalType>(inner.getType()) && (toTy == fromTy) &&
1352 (fromTy.getWidth() == 1))
1353 return inner.getValue();
1354 }
1355 return {};
1356 }
1357
1358 bool fir::ConvertOp::isInteger(mlir::Type ty) {
1359 return mlir::isa<mlir::IntegerType, mlir::IndexType, fir::IntegerType>(ty);
1360 }
1361
1362 bool fir::ConvertOp::isIntegerCompatible(mlir::Type ty) {
1363 return isInteger(ty) || mlir::isa<fir::LogicalType>(ty);
1364 }
1365
1366 bool fir::ConvertOp::isFloatCompatible(mlir::Type ty) {
1367 return mlir::isa<mlir::FloatType, fir::RealType>(ty);
1368 }
1369
1370 bool fir::ConvertOp::isPointerCompatible(mlir::Type ty) {
1371 return mlir::isa<fir::ReferenceType, fir::PointerType, fir::HeapType,
1372 fir::LLVMPointerType, mlir::MemRefType, mlir::FunctionType,
1373 fir::TypeDescType>(ty);
1374 }
1375
1376 static std::optional<mlir::Type> getVectorElementType(mlir::Type ty) {
1377 mlir::Type elemTy;
1378 if (mlir::isa<fir::VectorType>(ty))
1379 elemTy = mlir::dyn_cast<fir::VectorType>(ty).getEleTy();
1380 else if (mlir::isa<mlir::VectorType>(ty))
1381 elemTy = mlir::dyn_cast<mlir::VectorType>(ty).getElementType();
1382 else
1383 return std::nullopt;
1384
1385 // e.g. fir.vector<4:ui32> => mlir.vector<4xi32>
1386 // e.g. mlir.vector<4xui32> => mlir.vector<4xi32>
1387 if (elemTy.isUnsignedInteger()) {
1388 elemTy = mlir::IntegerType::get(
1389 ty.getContext(), mlir::dyn_cast<mlir::IntegerType>(elemTy).getWidth());
1390 }
1391 return elemTy;
1392 }
1393
1394 static std::optional<uint64_t> getVectorLen(mlir::Type ty) {
1395 if (mlir::isa<fir::VectorType>(ty))
1396 return mlir::dyn_cast<fir::VectorType>(ty).getLen();
1397 else if (mlir::isa<mlir::VectorType>(ty)) {
1398 // fir.vector only supports 1-D vector
1399 if (!(mlir::dyn_cast<mlir::VectorType>(ty).isScalable()))
1400 return mlir::dyn_cast<mlir::VectorType>(ty).getShape()[0];
1401 }
1402
1403 return std::nullopt;
1404 }
1405
1406 bool fir::ConvertOp::areVectorsCompatible(mlir::Type inTy, mlir::Type outTy) {
1407 if (!(mlir::isa<fir::VectorType>(inTy) &&
1408 mlir::isa<mlir::VectorType>(outTy)) &&
1409 !(mlir::isa<mlir::VectorType>(inTy) && mlir::isa<fir::VectorType>(outTy)))
1410 return false;
1411
1412 // Only support integer, unsigned and real vector
1413 // Both vectors must have the same element type
1414 std::optional<mlir::Type> inElemTy = getVectorElementType(inTy);
1415 std::optional<mlir::Type> outElemTy = getVectorElementType(outTy);
1416 if (!inElemTy.has_value() || !outElemTy.has_value() ||
1417 inElemTy.value() != outElemTy.value())
1418 return false;
1419
1420 // Both vectors must have the same number of elements
1421 std::optional<uint64_t> inLen = getVectorLen(inTy);
1422 std::optional<uint64_t> outLen = getVectorLen(outTy);
1423 if (!inLen.has_value() || !outLen.has_value() ||
1424 inLen.value() != outLen.value())
1425 return false;
1426
1427 return true;
1428 }
1429
1430 bool fir::ConvertOp::canBeConverted(mlir::Type inType, mlir::Type outType) {
1431 if (inType == outType)
1432 return true;
1433 return (isPointerCompatible(inType) && isPointerCompatible(outType)) ||
1434 (isIntegerCompatible(inType) && isIntegerCompatible(outType)) ||
1435 (isInteger(inType) && isFloatCompatible(outType)) ||
1436 (isFloatCompatible(inType) && isInteger(outType)) ||
1437 (isFloatCompatible(inType) && isFloatCompatible(outType)) ||
1438 (isIntegerCompatible(inType) && isPointerCompatible(outType)) ||
1439 (isPointerCompatible(inType) && isIntegerCompatible(outType)) ||
1440 (mlir::isa<fir::BoxType>(inType) &&
1441 mlir::isa<fir::BoxType>(outType)) ||
1442 (mlir::isa<fir::BoxProcType>(inType) &&
1443 mlir::isa<fir::BoxProcType>(outType)) ||
1444 (fir::isa_complex(inType) && fir::isa_complex(outType)) ||
1445 (fir::isBoxedRecordType(inType) && fir::isPolymorphicType(outType)) ||
1446 (fir::isPolymorphicType(inType) && fir::isPolymorphicType(outType)) ||
1447 (fir::isPolymorphicType(inType) && mlir::isa<BoxType>(outType)) ||
1448 areVectorsCompatible(inType, outType);
1449 }
1450
1451 llvm::LogicalResult fir::ConvertOp::verify() {
1452 if (canBeConverted(getValue().getType(), getType()))
1453 return mlir::success();
1454 return emitOpError("invalid type conversion")
1455 << getValue().getType() << " / " << getType();
1456 }
1457
1458 //===----------------------------------------------------------------------===//
1459 // CoordinateOp
1460 //===----------------------------------------------------------------------===//
1461
1462 void fir::CoordinateOp::print(mlir::OpAsmPrinter &p) {
1463 p << ' ' << getRef() << ", " << getCoor();
1464 p.printOptionalAttrDict((*this)->getAttrs(), /*elideAttrs=*/{"baseType"});
1465 p << " : ";
1466 p.printFunctionalType(getOperandTypes(), (*this)->getResultTypes());
1467 }
1468
1469 mlir::ParseResult fir::CoordinateOp::parse(mlir::OpAsmParser &parser,
1470 mlir::OperationState &result) {
1471 mlir::OpAsmParser::UnresolvedOperand memref;
1472 if (parser.parseOperand(memref) || parser.parseComma())
1473 return mlir::failure();
1474 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> coorOperands;
1475 if (parser.parseOperandList(coorOperands))
1476 return mlir::failure();
1477 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> allOperands;
1478 allOperands.push_back(memref);
1479 allOperands.append(coorOperands.begin(), coorOperands.end());
1480 mlir::FunctionType funcTy;
1481 auto loc = parser.getCurrentLocation();
1482 if (parser.parseOptionalAttrDict(result.attributes) ||
1483 parser.parseColonType(funcTy) ||
1484 parser.resolveOperands(allOperands, funcTy.getInputs(), loc,
1485 result.operands) ||
1486 parser.addTypesToList(funcTy.getResults(), result.types))
1487 return mlir::failure();
1488 result.addAttribute("baseType", mlir::TypeAttr::get(funcTy.getInput(0)));
1489 return mlir::success();
1490 }
1491
1492 llvm::LogicalResult fir::CoordinateOp::verify() {
1493 const mlir::Type refTy = getRef().getType();
1494 if (fir::isa_ref_type(refTy)) {
1495 auto eleTy = fir::dyn_cast_ptrEleTy(refTy);
1496 if (auto arrTy = mlir::dyn_cast<fir::SequenceType>(eleTy)) {
1497 if (arrTy.hasUnknownShape())
1498 return emitOpError("cannot find coordinate in unknown shape");
1499 if (arrTy.getConstantRows() < arrTy.getDimension() - 1)
1500 return emitOpError("cannot find coordinate with unknown extents");
1501 }
1502 if (!(fir::isa_aggregate(eleTy) || fir::isa_complex(eleTy) ||
1503 fir::isa_char_string(eleTy)))
1504 return emitOpError("cannot apply to this element type");
1505 }
1506 auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(refTy);
1507 unsigned dimension = 0;
1508 const unsigned numCoors = getCoor().size();
1509 for (auto coorOperand : llvm::enumerate(getCoor())) {
1510 auto co = coorOperand.value();
1511 if (dimension == 0 && mlir::isa<fir::SequenceType>(eleTy)) {
1512 dimension = mlir::cast<fir::SequenceType>(eleTy).getDimension();
1513 if (dimension == 0)
1514 return emitOpError("cannot apply to array of unknown rank");
1515 }
1516 if (auto *defOp = co.getDefiningOp()) {
1517 if (auto index = mlir::dyn_cast<fir::LenParamIndexOp>(defOp)) {
1518 // Recovering a LEN type parameter only makes sense from a boxed
1519 // value. For a bare reference, the LEN type parameters must be
1520 // passed as additional arguments to `index`.
1521 if (mlir::isa<fir::BoxType>(refTy)) {
1522 if (coorOperand.index() != numCoors - 1)
1523 return emitOpError("len_param_index must be last argument");
1524 if (getNumOperands() != 2)
1525 return emitOpError("too many operands for len_param_index case");
1526 }
1527 if (eleTy != index.getOnType())
1528 emitOpError(
1529 "len_param_index type not compatible with reference type");
1530 return mlir::success();
1531 } else if (auto index = mlir::dyn_cast<fir::FieldIndexOp>(defOp)) {
1532 if (eleTy != index.getOnType())
1533 emitOpError("field_index type not compatible with reference type");
1534 if (auto recTy = mlir::dyn_cast<fir::RecordType>(eleTy)) {
1535 eleTy = recTy.getType(index.getFieldName());
1536 continue;
1537 }
1538 return emitOpError("field_index not applied to !fir.type");
1539 }
1540 }
1541 if (dimension) {
1542 if (--dimension == 0)
1543 eleTy = mlir::cast<fir::SequenceType>(eleTy).getEleTy();
1544 } else {
1545 if (auto t = mlir::dyn_cast<mlir::TupleType>(eleTy)) {
1546 // FIXME: Generally, we don't know which field of the tuple is being
1547 // referred to unless the operand is a constant. Just assume everything
1548 // is good in the tuple case for now.
1549 return mlir::success();
1550 } else if (auto t = mlir::dyn_cast<fir::RecordType>(eleTy)) {
1551 // FIXME: This is the same as the tuple case.
1552 return mlir::success();
1553 } else if (auto t = mlir::dyn_cast<fir::ComplexType>(eleTy)) {
1554 eleTy = t.getElementType();
1555 } else if (auto t = mlir::dyn_cast<mlir::ComplexType>(eleTy)) {
1556 eleTy = t.getElementType();
1557 } else if (auto t = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
1558 if (t.getLen() == fir::CharacterType::singleton())
1559 return emitOpError("cannot apply to character singleton");
1560 eleTy = fir::CharacterType::getSingleton(t.getContext(), t.getFKind());
1561 if (fir::unwrapRefType(getType()) != eleTy)
1562 return emitOpError("character type mismatch");
1563 } else {
1564 return emitOpError("invalid parameters (too many)");
1565 }
1566 }
1567 }
1568 return mlir::success();
1569 }
1570
1571 //===----------------------------------------------------------------------===//
1572 // DispatchOp
1573 //===----------------------------------------------------------------------===//
1574
1575 llvm::LogicalResult fir::DispatchOp::verify() {
1576 // Check that pass_arg_pos is in range of actual operands. pass_arg_pos is
1577 // unsigned so check for less than zero is not needed.
1578 if (getPassArgPos() && *getPassArgPos() > (getArgOperands().size() - 1))
1579 return emitOpError(
1580 "pass_arg_pos must be smaller than the number of operands");
1581
1582 // Operand pointed by pass_arg_pos must have polymorphic type.
1583 if (getPassArgPos() &&
1584 !fir::isPolymorphicType(getArgOperands()[*getPassArgPos()].getType()))
1585 return emitOpError("pass_arg_pos must be a polymorphic operand");
1586 return mlir::success();
1587 }
1588
1589 mlir::FunctionType fir::DispatchOp::getFunctionType() {
1590 return mlir::FunctionType::get(getContext(), getOperandTypes(),
1591 getResultTypes());
1592 }
1593
1594 //===----------------------------------------------------------------------===//
1595 // TypeInfoOp
1596 //===----------------------------------------------------------------------===//
1597
1598 void fir::TypeInfoOp::build(mlir::OpBuilder &builder,
1599 mlir::OperationState &result, fir::RecordType type,
1600 fir::RecordType parentType,
1601 llvm::ArrayRef<mlir::NamedAttribute> attrs) {
1602 result.addRegion();
1603 result.addRegion();
1604 result.addAttribute(mlir::SymbolTable::getSymbolAttrName(),
1605 builder.getStringAttr(type.getName()));
1606 result.addAttribute(getTypeAttrName(result.name), mlir::TypeAttr::get(type));
1607 if (parentType)
1608 result.addAttribute(getParentTypeAttrName(result.name),
1609 mlir::TypeAttr::get(parentType));
1610 result.addAttributes(attrs);
1611 }
1612
1613 llvm::LogicalResult fir::TypeInfoOp::verify() {
1614 if (!getDispatchTable().empty())
1615 for (auto &op : getDispatchTable().front().without_terminator())
1616 if (!mlir::isa<fir::DTEntryOp>(op))
1617 return op.emitOpError("dispatch table must contain dt_entry");
1618
1619 if (!mlir::isa<fir::RecordType>(getType()))
1620 return emitOpError("type must be a fir.type");
1621
1622 if (getParentType() && !mlir::isa<fir::RecordType>(*getParentType()))
1623 return emitOpError("parent_type must be a fir.type");
1624 return mlir::success();
1625 }
1626
1627 //===----------------------------------------------------------------------===//
1628 // EmboxOp
1629 //===----------------------------------------------------------------------===//
1630
1631 llvm::LogicalResult fir::EmboxOp::verify() {
1632 auto eleTy = fir::dyn_cast_ptrEleTy(getMemref().getType());
1633 bool isArray = false;
1634 if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(eleTy)) {
1635 eleTy = seqTy.getEleTy();
1636 isArray = true;
1637 }
1638 if (hasLenParams()) {
1639 auto lenPs = numLenParams();
1640 if (auto rt = mlir::dyn_cast<fir::RecordType>(eleTy)) {
1641 if (lenPs != rt.getNumLenParams())
1642 return emitOpError("number of LEN params does not correspond"
1643 " to the !fir.type type");
1644 } else if (auto strTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
1645 if (strTy.getLen() != fir::CharacterType::unknownLen())
1646 return emitOpError("CHARACTER already has static LEN");
1647 } else {
1648 return emitOpError("LEN parameters require CHARACTER or derived type");
1649 }
1650 for (auto lp : getTypeparams())
1651 if (!fir::isa_integer(lp.getType()))
1652 return emitOpError("LEN parameters must be integral type");
1653 }
1654 if (getShape() && !isArray)
1655 return emitOpError("shape must not be provided for a scalar");
1656 if (getSlice() && !isArray)
1657 return emitOpError("slice must not be provided for a scalar");
1658 if (getSourceBox() && !mlir::isa<fir::ClassType>(getResult().getType()))
1659 return emitOpError("source_box must be used with fir.class result type");
1660 return mlir::success();
1661 }
1662
1663 //===----------------------------------------------------------------------===//
1664 // EmboxCharOp
1665 //===----------------------------------------------------------------------===//
1666
1667 llvm::LogicalResult fir::EmboxCharOp::verify() {
1668 auto eleTy = fir::dyn_cast_ptrEleTy(getMemref().getType());
1669 if (!mlir::dyn_cast_or_null<fir::CharacterType>(eleTy))
1670 return mlir::failure();
1671 return mlir::success();
1672 }
1673
1674 //===----------------------------------------------------------------------===//
1675 // EmboxProcOp
1676 //===----------------------------------------------------------------------===//
1677
1678 llvm::LogicalResult fir::EmboxProcOp::verify() {
1679 // host bindings (optional) must be a reference to a tuple
1680 if (auto h = getHost()) {
1681 if (auto r = mlir::dyn_cast<fir::ReferenceType>(h.getType()))
1682 if (mlir::isa<mlir::TupleType>(r.getEleTy()))
1683 return mlir::success();
1684 return mlir::failure();
1685 }
1686 return mlir::success();
1687 }
1688
1689 //===----------------------------------------------------------------------===//
1690 // TypeDescOp
1691 //===----------------------------------------------------------------------===//
1692
1693 void fir::TypeDescOp::build(mlir::OpBuilder &, mlir::OperationState &result,
1694 mlir::TypeAttr inty) {
1695 result.addAttribute("in_type", inty);
1696 result.addTypes(TypeDescType::get(inty.getValue()));
1697 }
1698
1699 mlir::ParseResult fir::TypeDescOp::parse(mlir::OpAsmParser &parser,
1700 mlir::OperationState &result) {
1701 mlir::Type intype;
1702 if (parser.parseType(intype))
1703 return mlir::failure();
1704 result.addAttribute("in_type", mlir::TypeAttr::get(intype));
1705 mlir::Type restype = fir::TypeDescType::get(intype);
1706 if (parser.addTypeToList(restype, result.types))
1707 return mlir::failure();
1708 return mlir::success();
1709 }
1710
1711 void fir::TypeDescOp::print(mlir::OpAsmPrinter &p) {
1712 p << ' ' << getOperation()->getAttr("in_type");
1713 p.printOptionalAttrDict(getOperation()->getAttrs(), {"in_type"});
1714 }
1715
1716 llvm::LogicalResult fir::TypeDescOp::verify() {
1717 mlir::Type resultTy = getType();
1718 if (auto tdesc = mlir::dyn_cast<fir::TypeDescType>(resultTy)) {
1719 if (tdesc.getOfTy() != getInType())
1720 return emitOpError("wrapped type mismatched");
1721 return mlir::success();
1722 }
1723 return emitOpError("must be !fir.tdesc type");
1724 }
1725
1726 //===----------------------------------------------------------------------===//
1727 // GlobalOp
1728 //===----------------------------------------------------------------------===//
1729
1730 mlir::Type fir::GlobalOp::resultType() {
1731 return wrapAllocaResultType(getType());
1732 }
1733
1734 mlir::ParseResult fir::GlobalOp::parse(mlir::OpAsmParser &parser,
1735 mlir::OperationState &result) {
1736 // Parse the optional linkage
1737 llvm::StringRef linkage;
1738 auto &builder = parser.getBuilder();
1739 if (mlir::succeeded(parser.parseOptionalKeyword(&linkage))) {
1740 if (fir::GlobalOp::verifyValidLinkage(linkage))
1741 return mlir::failure();
1742 mlir::StringAttr linkAttr = builder.getStringAttr(linkage);
1743 result.addAttribute(fir::GlobalOp::getLinkNameAttrName(result.name),
1744 linkAttr);
1745 }
1746
1747 // Parse the name as a symbol reference attribute.
1748 mlir::SymbolRefAttr nameAttr;
1749 if (parser.parseAttribute(nameAttr,
1750 fir::GlobalOp::getSymrefAttrName(result.name),
1751 result.attributes))
1752 return mlir::failure();
1753 result.addAttribute(mlir::SymbolTable::getSymbolAttrName(),
1754 nameAttr.getRootReference());
1755
1756 bool simpleInitializer = false;
1757 if (mlir::succeeded(parser.parseOptionalLParen())) {
1758 mlir::Attribute attr;
1759 if (parser.parseAttribute(attr, getInitValAttrName(result.name),
1760 result.attributes) ||
1761 parser.parseRParen())
1762 return mlir::failure();
1763 simpleInitializer = true;
1764 }
1765
1766 if (parser.parseOptionalAttrDict(result.attributes))
1767 return mlir::failure();
1768
1769 if (succeeded(
1770 parser.parseOptionalKeyword(getConstantAttrName(result.name)))) {
1771 // if "constant" keyword then mark this as a constant, not a variable
1772 result.addAttribute(getConstantAttrName(result.name),
1773 builder.getUnitAttr());
1774 }
1775
1776 if (succeeded(parser.parseOptionalKeyword(getTargetAttrName(result.name))))
1777 result.addAttribute(getTargetAttrName(result.name), builder.getUnitAttr());
1778
1779 mlir::Type globalType;
1780 if (parser.parseColonType(globalType))
1781 return mlir::failure();
1782
1783 result.addAttribute(fir::GlobalOp::getTypeAttrName(result.name),
1784 mlir::TypeAttr::get(globalType));
1785
1786 if (simpleInitializer) {
1787 result.addRegion();
1788 } else {
1789 // Parse the optional initializer body.
1790 auto parseResult =
1791 parser.parseOptionalRegion(*result.addRegion(), /*arguments=*/{});
1792 if (parseResult.has_value() && mlir::failed(*parseResult))
1793 return mlir::failure();
1794 }
1795 return mlir::success();
1796 }
1797
1798 void fir::GlobalOp::print(mlir::OpAsmPrinter &p) {
1799 if (getLinkName())
1800 p << ' ' << *getLinkName();
1801 p << ' ';
1802 p.printAttributeWithoutType(getSymrefAttr());
1803 if (auto val = getValueOrNull())
1804 p << '(' << val << ')';
1805 // Print all other attributes that are not pretty printed here.
1806 p.printOptionalAttrDict((*this)->getAttrs(), /*elideAttrs=*/{
1807 getSymNameAttrName(), getSymrefAttrName(),
1808 getTypeAttrName(), getConstantAttrName(),
1809 getTargetAttrName(), getLinkNameAttrName(),
1810 getInitValAttrName()});
1811 if (getOperation()->getAttr(getConstantAttrName()))
1812 p << " " << getConstantAttrName().strref();
1813 if (getOperation()->getAttr(getTargetAttrName()))
1814 p << " " << getTargetAttrName().strref();
1815 p << " : ";
1816 p.printType(getType());
1817 if (hasInitializationBody()) {
1818 p << ' ';
1819 p.printRegion(getOperation()->getRegion(0),
1820 /*printEntryBlockArgs=*/false,
1821 /*printBlockTerminators=*/true);
1822 }
1823 }
1824
1825 void fir::GlobalOp::appendInitialValue(mlir::Operation *op) {
1826 getBlock().getOperations().push_back(op);
1827 }
1828
1829 void fir::GlobalOp::build(mlir::OpBuilder &builder,
1830 mlir::OperationState &result, llvm::StringRef name,
1831 bool isConstant, bool isTarget, mlir::Type type,
1832 mlir::Attribute initialVal, mlir::StringAttr linkage,
1833 llvm::ArrayRef<mlir::NamedAttribute> attrs) {
1834 result.addRegion();
1835 result.addAttribute(getTypeAttrName(result.name), mlir::TypeAttr::get(type));
1836 result.addAttribute(mlir::SymbolTable::getSymbolAttrName(),
1837 builder.getStringAttr(name));
1838 result.addAttribute(getSymrefAttrName(result.name),
1839 mlir::SymbolRefAttr::get(builder.getContext(), name));
1840 if (isConstant)
1841 result.addAttribute(getConstantAttrName(result.name),
1842 builder.getUnitAttr());
1843 if (isTarget)
1844 result.addAttribute(getTargetAttrName(result.name), builder.getUnitAttr());
1845 if (initialVal)
1846 result.addAttribute(getInitValAttrName(result.name), initialVal);
1847 if (linkage)
1848 result.addAttribute(getLinkNameAttrName(result.name), linkage);
1849 result.attributes.append(attrs.begin(), attrs.end());
1850 }
1851
1852 void fir::GlobalOp::build(mlir::OpBuilder &builder,
1853 mlir::OperationState &result, llvm::StringRef name,
1854 mlir::Type type, mlir::Attribute initialVal,
1855 mlir::StringAttr linkage,
1856 llvm::ArrayRef<mlir::NamedAttribute> attrs) {
1857 build(builder, result, name, /*isConstant=*/false, /*isTarget=*/false, type,
1858 {}, linkage, attrs);
1859 }
1860
1861 void fir::GlobalOp::build(mlir::OpBuilder &builder,
1862 mlir::OperationState &result, llvm::StringRef name,
1863 bool isConstant, bool isTarget, mlir::Type type,
1864 mlir::StringAttr linkage,
1865 llvm::ArrayRef<mlir::NamedAttribute> attrs) {
1866 build(builder, result, name, isConstant, isTarget, type, {}, linkage, attrs);
1867 }
1868
1869 void fir::GlobalOp::build(mlir::OpBuilder &builder,
1870 mlir::OperationState &result, llvm::StringRef name,
1871 mlir::Type type, mlir::StringAttr linkage,
1872 llvm::ArrayRef<mlir::NamedAttribute> attrs) {
1873 build(builder, result, name, /*isConstant=*/false, /*isTarget=*/false, type,
1874 {}, linkage, attrs);
1875 }
1876
1877 void fir::GlobalOp::build(mlir::OpBuilder &builder,
1878 mlir::OperationState &result, llvm::StringRef name,
1879 bool isConstant, bool isTarget, mlir::Type type,
1880 llvm::ArrayRef<mlir::NamedAttribute> attrs) {
1881 build(builder, result, name, isConstant, isTarget, type, mlir::StringAttr{},
1882 attrs);
1883 }
1884
1885 void fir::GlobalOp::build(mlir::OpBuilder &builder,
1886 mlir::OperationState &result, llvm::StringRef name,
1887 mlir::Type type,
1888 llvm::ArrayRef<mlir::NamedAttribute> attrs) {
1889 build(builder, result, name, /*isConstant=*/false, /*isTarget=*/false, type,
1890 attrs);
1891 }
1892
1893 mlir::ParseResult fir::GlobalOp::verifyValidLinkage(llvm::StringRef linkage) {
1894 // Supporting only a subset of the LLVM linkage types for now
1895 static const char *validNames[] = {"common", "internal", "linkonce",
1896 "linkonce_odr", "weak"};
1897 return mlir::success(llvm::is_contained(validNames, linkage));
1898 }
1899
1900 //===----------------------------------------------------------------------===//
1901 // GlobalLenOp
1902 //===----------------------------------------------------------------------===//
1903
1904 mlir::ParseResult fir::GlobalLenOp::parse(mlir::OpAsmParser &parser,
1905 mlir::OperationState &result) {
1906 llvm::StringRef fieldName;
1907 if (failed(parser.parseOptionalKeyword(&fieldName))) {
1908 mlir::StringAttr fieldAttr;
1909 if (parser.parseAttribute(fieldAttr,
1910 fir::GlobalLenOp::getLenParamAttrName(),
1911 result.attributes))
1912 return mlir::failure();
1913 } else {
1914 result.addAttribute(fir::GlobalLenOp::getLenParamAttrName(),
1915 parser.getBuilder().getStringAttr(fieldName));
1916 }
1917 mlir::IntegerAttr constant;
1918 if (parser.parseComma() ||
1919 parser.parseAttribute(constant, fir::GlobalLenOp::getIntAttrName(),
1920 result.attributes))
1921 return mlir::failure();
1922 return mlir::success();
1923 }
1924
1925 void fir::GlobalLenOp::print(mlir::OpAsmPrinter &p) {
1926 p << ' ' << getOperation()->getAttr(fir::GlobalLenOp::getLenParamAttrName())
1927 << ", " << getOperation()->getAttr(fir::GlobalLenOp::getIntAttrName());
1928 }
1929
1930 //===----------------------------------------------------------------------===//
1931 // FieldIndexOp
1932 //===----------------------------------------------------------------------===//
1933
1934 template <typename TY>
1935 mlir::ParseResult parseFieldLikeOp(mlir::OpAsmParser &parser,
1936 mlir::OperationState &result) {
1937 llvm::StringRef fieldName;
1938 auto &builder = parser.getBuilder();
1939 mlir::Type recty;
1940 if (parser.parseOptionalKeyword(&fieldName) || parser.parseComma() ||
1941 parser.parseType(recty))
1942 return mlir::failure();
1943 result.addAttribute(fir::FieldIndexOp::getFieldAttrName(),
1944 builder.getStringAttr(fieldName));
1945 if (!mlir::dyn_cast<fir::RecordType>(recty))
1946 return mlir::failure();
1947 result.addAttribute(fir::FieldIndexOp::getTypeAttrName(),
1948 mlir::TypeAttr::get(recty));
1949 if (!parser.parseOptionalLParen()) {
1950 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> operands;
1951 llvm::SmallVector<mlir::Type> types;
1952 auto loc = parser.getNameLoc();
1953 if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::None) ||
1954 parser.parseColonTypeList(types) || parser.parseRParen() ||
1955 parser.resolveOperands(operands, types, loc, result.operands))
1956 return mlir::failure();
1957 }
1958 mlir::Type fieldType = TY::get(builder.getContext());
1959 if (parser.addTypeToList(fieldType, result.types))
1960 return mlir::failure();
1961 return mlir::success();
1962 }
1963
1964 mlir::ParseResult fir::FieldIndexOp::parse(mlir::OpAsmParser &parser,
1965 mlir::OperationState &result) {
1966 return parseFieldLikeOp<fir::FieldType>(parser, result);
1967 }
1968
1969 template <typename OP>
1970 void printFieldLikeOp(mlir::OpAsmPrinter &p, OP &op) {
1971 p << ' '
1972 << op.getOperation()
1973 ->template getAttrOfType<mlir::StringAttr>(
1974 fir::FieldIndexOp::getFieldAttrName())
1975 .getValue()
1976 << ", " << op.getOperation()->getAttr(fir::FieldIndexOp::getTypeAttrName());
1977 if (op.getNumOperands()) {
1978 p << '(';
1979 p.printOperands(op.getTypeparams());
1980 auto sep = ") : ";
1981 for (auto op : op.getTypeparams()) {
1982 p << sep;
1983 if (op)
1984 p.printType(op.getType());
1985 else
1986 p << "()";
1987 sep = ", ";
1988 }
1989 }
1990 }
1991
1992 void fir::FieldIndexOp::print(mlir::OpAsmPrinter &p) {
1993 printFieldLikeOp(p, *this);
1994 }
1995
1996 void fir::FieldIndexOp::build(mlir::OpBuilder &builder,
1997 mlir::OperationState &result,
1998 llvm::StringRef fieldName, mlir::Type recTy,
1999 mlir::ValueRange operands) {
2000 result.addAttribute(getFieldAttrName(), builder.getStringAttr(fieldName));
2001 result.addAttribute(getTypeAttrName(), mlir::TypeAttr::get(recTy));
2002 result.addOperands(operands);
2003 }
2004
2005 llvm::SmallVector<mlir::Attribute> fir::FieldIndexOp::getAttributes() {
2006 llvm::SmallVector<mlir::Attribute> attrs;
2007 attrs.push_back(getFieldIdAttr());
2008 attrs.push_back(getOnTypeAttr());
2009 return attrs;
2010 }
2011
2012 //===----------------------------------------------------------------------===//
2013 // InsertOnRangeOp
2014 //===----------------------------------------------------------------------===//
2015
2016 static mlir::ParseResult
2017 parseCustomRangeSubscript(mlir::OpAsmParser &parser,
2018 mlir::DenseIntElementsAttr &coord) {
2019 llvm::SmallVector<std::int64_t> lbounds;
2020 llvm::SmallVector<std::int64_t> ubounds;
2021 if (parser.parseKeyword("from") ||
2022 parser.parseCommaSeparatedList(
2023 mlir::AsmParser::Delimiter::Paren,
2024 [&] { return parser.parseInteger(lbounds.emplace_back(0)); }) ||
2025 parser.parseKeyword("to") ||
2026 parser.parseCommaSeparatedList(mlir::AsmParser::Delimiter::Paren, [&] {
2027 return parser.parseInteger(ubounds.emplace_back(0));
2028 }))
2029 return mlir::failure();
2030 llvm::SmallVector<std::int64_t> zippedBounds;
2031 for (auto zip : llvm::zip(lbounds, ubounds)) {
2032 zippedBounds.push_back(std::get<0>(zip));
2033 zippedBounds.push_back(std::get<1>(zip));
2034 }
2035 coord = mlir::Builder(parser.getContext()).getIndexTensorAttr(zippedBounds);
2036 return mlir::success();
2037 }
2038
2039 static void printCustomRangeSubscript(mlir::OpAsmPrinter &printer,
2040 fir::InsertOnRangeOp op,
2041 mlir::DenseIntElementsAttr coord) {
2042 printer << "from (";
2043 auto enumerate = llvm::enumerate(coord.getValues<std::int64_t>());
2044 // Even entries are the lower bounds.
2045 llvm::interleaveComma(
2046 make_filter_range(
2047 enumerate,
2048 [](auto indexed_value) { return indexed_value.index() % 2 == 0; }),
2049 printer, [&](auto indexed_value) { printer << indexed_value.value(); });
2050 printer << ") to (";
2051 // Odd entries are the upper bounds.
2052 llvm::interleaveComma(
2053 make_filter_range(
2054 enumerate,
2055 [](auto indexed_value) { return indexed_value.index() % 2 != 0; }),
2056 printer, [&](auto indexed_value) { printer << indexed_value.value(); });
2057 printer << ")";
2058 }
2059
2060 /// Range bounds must be nonnegative, and the range must not be empty.
2061 llvm::LogicalResult fir::InsertOnRangeOp::verify() {
2062 if (fir::hasDynamicSize(getSeq().getType()))
2063 return emitOpError("must have constant shape and size");
2064 mlir::DenseIntElementsAttr coorAttr = getCoor();
2065 if (coorAttr.size() < 2 || coorAttr.size() % 2 != 0)
2066 return emitOpError("has uneven number of values in ranges");
2067 bool rangeIsKnownToBeNonempty = false;
2068 for (auto i = coorAttr.getValues<std::int64_t>().end(),
2069 b = coorAttr.getValues<std::int64_t>().begin();
2070 i != b;) {
2071 int64_t ub = (*--i);
2072 int64_t lb = (*--i);
2073 if (lb < 0 || ub < 0)
2074 return emitOpError("negative range bound");
2075 if (rangeIsKnownToBeNonempty)
2076 continue;
2077 if (lb > ub)
2078 return emitOpError("empty range");
2079 rangeIsKnownToBeNonempty = lb < ub;
2080 }
2081 return mlir::success();
2082 }
2083
2084 //===----------------------------------------------------------------------===//
2085 // InsertValueOp
2086 //===----------------------------------------------------------------------===//
2087
2088 static bool checkIsIntegerConstant(mlir::Attribute attr, std::int64_t conVal) {
2089 if (auto iattr = mlir::dyn_cast<mlir::IntegerAttr>(attr))
2090 return iattr.getInt() == conVal;
2091 return false;
2092 }
2093
2094 static bool isZero(mlir::Attribute a) { return checkIsIntegerConstant(a, 0); }
2095 static bool isOne(mlir::Attribute a) { return checkIsIntegerConstant(a, 1); }
2096
2097 // Undo some complex patterns created in the front-end and turn them back into
2098 // complex ops.
2099 template <typename FltOp, typename CpxOp>
2100 struct UndoComplexPattern : public mlir::RewritePattern {
2101 UndoComplexPattern(mlir::MLIRContext *ctx)
2102 : mlir::RewritePattern("fir.insert_value", 2, ctx) {}
2103
2104 llvm::LogicalResult
2105 matchAndRewrite(mlir::Operation *op,
2106 mlir::PatternRewriter &rewriter) const override {
2107 auto insval = mlir::dyn_cast_or_null<fir::InsertValueOp>(op);
2108 if (!insval || !mlir::isa<fir::ComplexType>(insval.getType()))
2109 return mlir::failure();
2110 auto insval2 = mlir::dyn_cast_or_null<fir::InsertValueOp>(
2111 insval.getAdt().getDefiningOp());
2112 if (!insval2)
2113 return mlir::failure();
2114 auto binf = mlir::dyn_cast_or_null<FltOp>(insval.getVal().getDefiningOp());
2115 auto binf2 =
2116 mlir::dyn_cast_or_null<FltOp>(insval2.getVal().getDefiningOp());
2117 if (!binf || !binf2 || insval.getCoor().size() != 1 ||
2118 !isOne(insval.getCoor()[0]) || insval2.getCoor().size() != 1 ||
2119 !isZero(insval2.getCoor()[0]))
2120 return mlir::failure();
2121 auto eai = mlir::dyn_cast_or_null<fir::ExtractValueOp>(
2122 binf.getLhs().getDefiningOp());
2123 auto ebi = mlir::dyn_cast_or_null<fir::ExtractValueOp>(
2124 binf.getRhs().getDefiningOp());
2125 auto ear = mlir::dyn_cast_or_null<fir::ExtractValueOp>(
2126 binf2.getLhs().getDefiningOp());
2127 auto ebr = mlir::dyn_cast_or_null<fir::ExtractValueOp>(
2128 binf2.getRhs().getDefiningOp());
2129 if (!eai || !ebi || !ear || !ebr || ear.getAdt() != eai.getAdt() ||
2130 ebr.getAdt() != ebi.getAdt() || eai.getCoor().size() != 1 ||
2131 !isOne(eai.getCoor()[0]) || ebi.getCoor().size() != 1 ||
2132 !isOne(ebi.getCoor()[0]) || ear.getCoor().size() != 1 ||
2133 !isZero(ear.getCoor()[0]) || ebr.getCoor().size() != 1 ||
2134 !isZero(ebr.getCoor()[0]))
2135 return mlir::failure();
2136 rewriter.replaceOpWithNewOp<CpxOp>(op, ear.getAdt(), ebr.getAdt());
2137 return mlir::success();
2138 }
2139 };
2140
2141 void fir::InsertValueOp::getCanonicalizationPatterns(
2142 mlir::RewritePatternSet &results, mlir::MLIRContext *context) {
2143 results.insert<UndoComplexPattern<mlir::arith::AddFOp, fir::AddcOp>,
2144 UndoComplexPattern<mlir::arith::SubFOp, fir::SubcOp>>(context);
2145 }
2146
2147 //===----------------------------------------------------------------------===//
2148 // IterWhileOp
2149 //===----------------------------------------------------------------------===//
2150
2151 void fir::IterWhileOp::build(mlir::OpBuilder &builder,
2152 mlir::OperationState &result, mlir::Value lb,
2153 mlir::Value ub, mlir::Value step,
2154 mlir::Value iterate, bool finalCountValue,
2155 mlir::ValueRange iterArgs,
2156 llvm::ArrayRef<mlir::NamedAttribute> attributes) {
2157 result.addOperands({lb, ub, step, iterate});
2158 if (finalCountValue) {
2159 result.addTypes(builder.getIndexType());
2160 result.addAttribute(getFinalValueAttrNameStr(), builder.getUnitAttr());
2161 }
2162 result.addTypes(iterate.getType());
2163 result.addOperands(iterArgs);
2164 for (auto v : iterArgs)
2165 result.addTypes(v.getType());
2166 mlir::Region *bodyRegion = result.addRegion();
2167 bodyRegion->push_back(new mlir::Block{});
2168 bodyRegion->front().addArgument(builder.getIndexType(), result.location);
2169 bodyRegion->front().addArgument(iterate.getType(), result.location);
2170 bodyRegion->front().addArguments(
2171 iterArgs.getTypes(),
2172 llvm::SmallVector<mlir::Location>(iterArgs.size(), result.location));
2173 result.addAttributes(attributes);
2174 }
2175
2176 mlir::ParseResult fir::IterWhileOp::parse(mlir::OpAsmParser &parser,
2177 mlir::OperationState &result) {
2178 auto &builder = parser.getBuilder();
2179 mlir::OpAsmParser::Argument inductionVariable, iterateVar;
2180 mlir::OpAsmParser::UnresolvedOperand lb, ub, step, iterateInput;
2181 if (parser.parseLParen() || parser.parseArgument(inductionVariable) ||
2182 parser.parseEqual())
2183 return mlir::failure();
2184
2185 // Parse loop bounds.
2186 auto indexType = builder.getIndexType();
2187 auto i1Type = builder.getIntegerType(1);
2188 if (parser.parseOperand(lb) ||
2189 parser.resolveOperand(lb, indexType, result.operands) ||
2190 parser.parseKeyword("to") || parser.parseOperand(ub) ||
2191 parser.resolveOperand(ub, indexType, result.operands) ||
2192 parser.parseKeyword("step") || parser.parseOperand(step) ||
2193 parser.parseRParen() ||
2194 parser.resolveOperand(step, indexType, result.operands) ||
2195 parser.parseKeyword("and") || parser.parseLParen() ||
2196 parser.parseArgument(iterateVar) || parser.parseEqual() ||
2197 parser.parseOperand(iterateInput) || parser.parseRParen() ||
2198 parser.resolveOperand(iterateInput, i1Type, result.operands))
2199 return mlir::failure();
2200
2201 // Parse the initial iteration arguments.
2202 auto prependCount = false;
2203
2204 // Induction variable.
2205 llvm::SmallVector<mlir::OpAsmParser::Argument> regionArgs;
2206 regionArgs.push_back(inductionVariable);
2207 regionArgs.push_back(iterateVar);
2208
2209 if (succeeded(parser.parseOptionalKeyword("iter_args"))) {
2210 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> operands;
2211 llvm::SmallVector<mlir::Type> regionTypes;
2212 // Parse assignment list and results type list.
2213 if (parser.parseAssignmentList(regionArgs, operands) ||
2214 parser.parseArrowTypeList(regionTypes))
2215 return mlir::failure();
2216 if (regionTypes.size() == operands.size() + 2)
2217 prependCount = true;
2218 llvm::ArrayRef<mlir::Type> resTypes = regionTypes;
2219 resTypes = prependCount ? resTypes.drop_front(2) : resTypes;
2220 // Resolve input operands.
2221 for (auto operandType : llvm::zip(operands, resTypes))
2222 if (parser.resolveOperand(std::get<0>(operandType),
2223 std::get<1>(operandType), result.operands))
2224 return mlir::failure();
2225 if (prependCount) {
2226 result.addTypes(regionTypes);
2227 } else {
2228 result.addTypes(i1Type);
2229 result.addTypes(resTypes);
2230 }
2231 } else if (succeeded(parser.parseOptionalArrow())) {
2232 llvm::SmallVector<mlir::Type> typeList;
2233 if (parser.parseLParen() || parser.parseTypeList(typeList) ||
2234 parser.parseRParen())
2235 return mlir::failure();
2236 // Type list must be "(index, i1)".
2237 if (typeList.size() != 2 || !mlir::isa<mlir::IndexType>(typeList[0]) ||
2238 !typeList[1].isSignlessInteger(1))
2239 return mlir::failure();
2240 result.addTypes(typeList);
2241 prependCount = true;
2242 } else {
2243 result.addTypes(i1Type);
2244 }
2245
2246 if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
2247 return mlir::failure();
2248
2249 llvm::SmallVector<mlir::Type> argTypes;
2250 // Induction variable (hidden)
2251 if (prependCount)
2252 result.addAttribute(IterWhileOp::getFinalValueAttrNameStr(),
2253 builder.getUnitAttr());
2254 else
2255 argTypes.push_back(indexType);
2256 // Loop carried variables (including iterate)
2257 argTypes.append(result.types.begin(), result.types.end());
2258 // Parse the body region.
2259 auto *body = result.addRegion();
2260 if (regionArgs.size() != argTypes.size())
2261 return parser.emitError(
2262 parser.getNameLoc(),
2263 "mismatch in number of loop-carried values and defined values");
2264
2265 for (size_t i = 0, e = regionArgs.size(); i != e; ++i)
2266 regionArgs[i].type = argTypes[i];
2267
2268 if (parser.parseRegion(*body, regionArgs))
2269 return mlir::failure();
2270
2271 fir::IterWhileOp::ensureTerminator(*body, builder, result.location);
2272 return mlir::success();
2273 }
2274
2275 llvm::LogicalResult fir::IterWhileOp::verify() {
2276 // Check that the body defines as single block argument for the induction
2277 // variable.
2278 auto *body = getBody();
2279 if (!body->getArgument(1).getType().isInteger(1))
2280 return emitOpError(
2281 "expected body second argument to be an index argument for "
2282 "the induction variable");
2283 if (!body->getArgument(0).getType().isIndex())
2284 return emitOpError(
2285 "expected body first argument to be an index argument for "
2286 "the induction variable");
2287
2288 auto opNumResults = getNumResults();
2289 if (getFinalValue()) {
2290 // Result type must be "(index, i1, ...)".
2291 if (!mlir::isa<mlir::IndexType>(getResult(0).getType()))
2292 return emitOpError("result #0 expected to be index");
2293 if (!getResult(1).getType().isSignlessInteger(1))
2294 return emitOpError("result #1 expected to be i1");
2295 opNumResults--;
2296 } else {
2297 // iterate_while always returns the early exit induction value.
2298 // Result type must be "(i1, ...)"
2299 if (!getResult(0).getType().isSignlessInteger(1))
2300 return emitOpError("result #0 expected to be i1");
2301 }
2302 if (opNumResults == 0)
2303 return mlir::failure();
2304 if (getNumIterOperands() != opNumResults)
2305 return emitOpError(
2306 "mismatch in number of loop-carried values and defined values");
2307 if (getNumRegionIterArgs() != opNumResults)
2308 return emitOpError(
2309 "mismatch in number of basic block args and defined values");
2310 auto iterOperands = getIterOperands();
2311 auto iterArgs = getRegionIterArgs();
2312 auto opResults = getFinalValue() ? getResults().drop_front() : getResults();
2313 unsigned i = 0u;
2314 for (auto e : llvm::zip(iterOperands, iterArgs, opResults)) {
2315 if (std::get<0>(e).getType() != std::get<2>(e).getType())
2316 return emitOpError() << "types mismatch between " << i
2317 << "th iter operand and defined value";
2318 if (std::get<1>(e).getType() != std::get<2>(e).getType())
2319 return emitOpError() << "types mismatch between " << i
2320 << "th iter region arg and defined value";
2321
2322 i++;
2323 }
2324 return mlir::success();
2325 }
2326
2327 void fir::IterWhileOp::print(mlir::OpAsmPrinter &p) {
2328 p << " (" << getInductionVar() << " = " << getLowerBound() << " to "
2329 << getUpperBound() << " step " << getStep() << ") and (";
2330 assert(hasIterOperands());
2331 auto regionArgs = getRegionIterArgs();
2332 auto operands = getIterOperands();
2333 p << regionArgs.front() << " = " << *operands.begin() << ")";
2334 if (regionArgs.size() > 1) {
2335 p << " iter_args(";
2336 llvm::interleaveComma(
2337 llvm::zip(regionArgs.drop_front(), operands.drop_front()), p,
2338 [&](auto it) { p << std::get<0>(it) << " = " << std::get<1>(it); });
2339 p << ") -> (";
2340 llvm::interleaveComma(
2341 llvm::drop_begin(getResultTypes(), getFinalValue() ? 0 : 1), p);
2342 p << ")";
2343 } else if (getFinalValue()) {
2344 p << " -> (" << getResultTypes() << ')';
2345 }
2346 p.printOptionalAttrDictWithKeyword((*this)->getAttrs(),
2347 {getFinalValueAttrNameStr()});
2348 p << ' ';
2349 p.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
2350 /*printBlockTerminators=*/true);
2351 }
2352
2353 llvm::SmallVector<mlir::Region *> fir::IterWhileOp::getLoopRegions() {
2354 return {&getRegion()};
2355 }
2356
2357 mlir::BlockArgument fir::IterWhileOp::iterArgToBlockArg(mlir::Value iterArg) {
2358 for (auto i : llvm::enumerate(getInitArgs()))
2359 if (iterArg == i.value())
2360 return getRegion().front().getArgument(i.index() + 1);
2361 return {};
2362 }
2363
2364 void fir::IterWhileOp::resultToSourceOps(
2365 llvm::SmallVectorImpl<mlir::Value> &results, unsigned resultNum) {
2366 auto oper = getFinalValue() ? resultNum + 1 : resultNum;
2367 auto *term = getRegion().front().getTerminator();
2368 if (oper < term->getNumOperands())
2369 results.push_back(term->getOperand(oper));
2370 }
2371
2372 mlir::Value fir::IterWhileOp::blockArgToSourceOp(unsigned blockArgNum) {
2373 if (blockArgNum > 0 && blockArgNum <= getInitArgs().size())
2374 return getInitArgs()[blockArgNum - 1];
2375 return {};
2376 }
2377
2378 std::optional<llvm::MutableArrayRef<mlir::OpOperand>>
2379 fir::IterWhileOp::getYieldedValuesMutable() {
2380 auto *term = getRegion().front().getTerminator();
2381 return getFinalValue() ? term->getOpOperands().drop_front()
2382 : term->getOpOperands();
2383 }
2384
2385 //===----------------------------------------------------------------------===//
2386 // LenParamIndexOp
2387 //===----------------------------------------------------------------------===//
2388
2389 mlir::ParseResult fir::LenParamIndexOp::parse(mlir::OpAsmParser &parser,
2390 mlir::OperationState &result) {
2391 return parseFieldLikeOp<fir::LenType>(parser, result);
2392 }
2393
2394 void fir::LenParamIndexOp::print(mlir::OpAsmPrinter &p) {
2395 printFieldLikeOp(p, *this);
2396 }
2397
2398 void fir::LenParamIndexOp::build(mlir::OpBuilder &builder,
2399 mlir::OperationState &result,
2400 llvm::StringRef fieldName, mlir::Type recTy,
2401 mlir::ValueRange operands) {
2402 result.addAttribute(getFieldAttrName(), builder.getStringAttr(fieldName));
2403 result.addAttribute(getTypeAttrName(), mlir::TypeAttr::get(recTy));
2404 result.addOperands(operands);
2405 }
2406
2407 llvm::SmallVector<mlir::Attribute> fir::LenParamIndexOp::getAttributes() {
2408 llvm::SmallVector<mlir::Attribute> attrs;
2409 attrs.push_back(getFieldIdAttr());
2410 attrs.push_back(getOnTypeAttr());
2411 return attrs;
2412 }
2413
2414 //===----------------------------------------------------------------------===//
2415 // LoadOp
2416 //===----------------------------------------------------------------------===//
2417
2418 void fir::LoadOp::build(mlir::OpBuilder &builder, mlir::OperationState &result,
2419 mlir::Value refVal) {
2420 if (!refVal) {
2421 mlir::emitError(result.location, "LoadOp has null argument");
2422 return;
2423 }
2424 auto eleTy = fir::dyn_cast_ptrEleTy(refVal.getType());
2425 if (!eleTy) {
2426 mlir::emitError(result.location, "not a memory reference type");
2427 return;
2428 }
2429 build(builder, result, eleTy, refVal);
2430 }
2431
2432 void fir::LoadOp::build(mlir::OpBuilder &builder, mlir::OperationState &result,
2433 mlir::Type resTy, mlir::Value refVal) {
2434
2435 if (!refVal) {
2436 mlir::emitError(result.location, "LoadOp has null argument");
2437 return;
2438 }
2439 result.addOperands(refVal);
2440 result.addTypes(resTy);
2441 }
2442
2443 mlir::ParseResult fir::LoadOp::getElementOf(mlir::Type &ele, mlir::Type ref) {
2444 if ((ele = fir::dyn_cast_ptrEleTy(ref)))
2445 return mlir::success();
2446 return mlir::failure();
2447 }
2448
2449 mlir::ParseResult fir::LoadOp::parse(mlir::OpAsmParser &parser,
2450 mlir::OperationState &result) {
2451 mlir::Type type;
2452 mlir::OpAsmParser::UnresolvedOperand oper;
2453 if (parser.parseOperand(oper) ||
2454 parser.parseOptionalAttrDict(result.attributes) ||
2455 parser.parseColonType(type) ||
2456 parser.resolveOperand(oper, type, result.operands))
2457 return mlir::failure();
2458 mlir::Type eleTy;
2459 if (fir::LoadOp::getElementOf(eleTy, type) ||
2460 parser.addTypeToList(eleTy, result.types))
2461 return mlir::failure();
2462 return mlir::success();
2463 }
2464
2465 void fir::LoadOp::print(mlir::OpAsmPrinter &p) {
2466 p << ' ';
2467 p.printOperand(getMemref());
2468 p.printOptionalAttrDict(getOperation()->getAttrs(), {});
2469 p << " : " << getMemref().getType();
2470 }
2471
2472 //===----------------------------------------------------------------------===//
2473 // DoLoopOp
2474 //===----------------------------------------------------------------------===//
2475
2476 void fir::DoLoopOp::build(mlir::OpBuilder &builder,
2477 mlir::OperationState &result, mlir::Value lb,
2478 mlir::Value ub, mlir::Value step, bool unordered,
2479 bool finalCountValue, mlir::ValueRange iterArgs,
2480 mlir::ValueRange reduceOperands,
2481 llvm::ArrayRef<mlir::Attribute> reduceAttrs,
2482 llvm::ArrayRef<mlir::NamedAttribute> attributes) {
2483 result.addOperands({lb, ub, step});
2484 result.addOperands(reduceOperands);
2485 result.addOperands(iterArgs);
2486 result.addAttribute(getOperandSegmentSizeAttr(),
2487 builder.getDenseI32ArrayAttr(
2488 {1, 1, 1, static_cast<int32_t>(reduceOperands.size()),
2489 static_cast<int32_t>(iterArgs.size())}));
2490 if (finalCountValue) {
2491 result.addTypes(builder.getIndexType());
2492 result.addAttribute(getFinalValueAttrName(result.name),
2493 builder.getUnitAttr());
2494 }
2495 for (auto v : iterArgs)
2496 result.addTypes(v.getType());
2497 mlir::Region *bodyRegion = result.addRegion();
2498 bodyRegion->push_back(new mlir::Block{});
2499 if (iterArgs.empty() && !finalCountValue)
2500 fir::DoLoopOp::ensureTerminator(*bodyRegion, builder, result.location);
2501 bodyRegion->front().addArgument(builder.getIndexType(), result.location);
2502 bodyRegion->front().addArguments(
2503 iterArgs.getTypes(),
2504 llvm::SmallVector<mlir::Location>(iterArgs.size(), result.location));
2505 if (unordered)
2506 result.addAttribute(getUnorderedAttrName(result.name),
2507 builder.getUnitAttr());
2508 if (!reduceAttrs.empty())
2509 result.addAttribute(getReduceAttrsAttrName(result.name),
2510 builder.getArrayAttr(reduceAttrs));
2511 result.addAttributes(attributes);
2512 }
2513
2514 mlir::ParseResult fir::DoLoopOp::parse(mlir::OpAsmParser &parser,
2515 mlir::OperationState &result) {
2516 auto &builder = parser.getBuilder();
2517 mlir::OpAsmParser::Argument inductionVariable;
2518 mlir::OpAsmParser::UnresolvedOperand lb, ub, step;
2519 // Parse the induction variable followed by '='.
2520 if (parser.parseArgument(inductionVariable) || parser.parseEqual())
2521 return mlir::failure();
2522
2523 // Parse loop bounds.
2524 auto indexType = builder.getIndexType();
2525 if (parser.parseOperand(lb) ||
2526 parser.resolveOperand(lb, indexType, result.operands) ||
2527 parser.parseKeyword("to") || parser.parseOperand(ub) ||
2528 parser.resolveOperand(ub, indexType, result.operands) ||
2529 parser.parseKeyword("step") || parser.parseOperand(step) ||
2530 parser.resolveOperand(step, indexType, result.operands))
2531 return mlir::failure();
2532
2533 if (mlir::succeeded(parser.parseOptionalKeyword("unordered")))
2534 result.addAttribute("unordered", builder.getUnitAttr());
2535
2536 // Parse the reduction arguments.
2537 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> reduceOperands;
2538 llvm::SmallVector<mlir::Type> reduceArgTypes;
2539 if (succeeded(parser.parseOptionalKeyword("reduce"))) {
2540 // Parse reduction attributes and variables.
2541 llvm::SmallVector<ReduceAttr> attributes;
2542 if (failed(parser.parseCommaSeparatedList(
2543 mlir::AsmParser::Delimiter::Paren, [&]() {
2544 if (parser.parseAttribute(attributes.emplace_back()) ||
2545 parser.parseArrow() ||
2546 parser.parseOperand(reduceOperands.emplace_back()) ||
2547 parser.parseColonType(reduceArgTypes.emplace_back()))
2548 return mlir::failure();
2549 return mlir::success();
2550 })))
2551 return mlir::failure();
2552 // Resolve input operands.
2553 for (auto operand_type : llvm::zip(reduceOperands, reduceArgTypes))
2554 if (parser.resolveOperand(std::get<0>(operand_type),
2555 std::get<1>(operand_type), result.operands))
2556 return mlir::failure();
2557 llvm::SmallVector<mlir::Attribute> arrayAttr(attributes.begin(),
2558 attributes.end());
2559 result.addAttribute(getReduceAttrsAttrName(result.name),
2560 builder.getArrayAttr(arrayAttr));
2561 }
2562
2563 // Parse the optional initial iteration arguments.
2564 llvm::SmallVector<mlir::OpAsmParser::Argument> regionArgs;
2565 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> iterOperands;
2566 llvm::SmallVector<mlir::Type> argTypes;
2567 bool prependCount = false;
2568 regionArgs.push_back(inductionVariable);
2569
2570 if (succeeded(parser.parseOptionalKeyword("iter_args"))) {
2571 // Parse assignment list and results type list.
2572 if (parser.parseAssignmentList(regionArgs, iterOperands) ||
2573 parser.parseArrowTypeList(result.types))
2574 return mlir::failure();
2575 if (result.types.size() == iterOperands.size() + 1)
2576 prependCount = true;
2577 // Resolve input operands.
2578 llvm::ArrayRef<mlir::Type> resTypes = result.types;
2579 for (auto operand_type : llvm::zip(
2580 iterOperands, prependCount ? resTypes.drop_front() : resTypes))
2581 if (parser.resolveOperand(std::get<0>(operand_type),
2582 std::get<1>(operand_type), result.operands))
2583 return mlir::failure();
2584 } else if (succeeded(parser.parseOptionalArrow())) {
2585 if (parser.parseKeyword("index"))
2586 return mlir::failure();
2587 result.types.push_back(indexType);
2588 prependCount = true;
2589 }
2590
2591 // Set the operandSegmentSizes attribute
2592 result.addAttribute(getOperandSegmentSizeAttr(),
2593 builder.getDenseI32ArrayAttr(
2594 {1, 1, 1, static_cast<int32_t>(reduceOperands.size()),
2595 static_cast<int32_t>(iterOperands.size())}));
2596
2597 if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
2598 return mlir::failure();
2599
2600 // Induction variable.
2601 if (prependCount)
2602 result.addAttribute(DoLoopOp::getFinalValueAttrName(result.name),
2603 builder.getUnitAttr());
2604 else
2605 argTypes.push_back(indexType);
2606 // Loop carried variables
2607 argTypes.append(result.types.begin(), result.types.end());
2608 // Parse the body region.
2609 auto *body = result.addRegion();
2610 if (regionArgs.size() != argTypes.size())
2611 return parser.emitError(
2612 parser.getNameLoc(),
2613 "mismatch in number of loop-carried values and defined values");
2614 for (size_t i = 0, e = regionArgs.size(); i != e; ++i)
2615 regionArgs[i].type = argTypes[i];
2616
2617 if (parser.parseRegion(*body, regionArgs))
2618 return mlir::failure();
2619
2620 DoLoopOp::ensureTerminator(*body, builder, result.location);
2621
2622 return mlir::success();
2623 }
2624
2625 fir::DoLoopOp fir::getForInductionVarOwner(mlir::Value val) {
2626 auto ivArg = mlir::dyn_cast<mlir::BlockArgument>(val);
2627 if (!ivArg)
2628 return {};
2629 assert(ivArg.getOwner() && "unlinked block argument");
2630 auto *containingInst = ivArg.getOwner()->getParentOp();
2631 return mlir::dyn_cast_or_null<fir::DoLoopOp>(containingInst);
2632 }
2633
2634 // Lifted from loop.loop
2635 llvm::LogicalResult fir::DoLoopOp::verify() {
2636 // Check that the body defines as single block argument for the induction
2637 // variable.
2638 auto *body = getBody();
2639 if (!body->getArgument(0).getType().isIndex())
2640 return emitOpError(
2641 "expected body first argument to be an index argument for "
2642 "the induction variable");
2643
2644 auto opNumResults = getNumResults();
2645 if (opNumResults == 0)
2646 return mlir::success();
2647
2648 if (getFinalValue()) {
2649 if (getUnordered())
2650 return emitOpError("unordered loop has no final value");
2651 opNumResults--;
2652 }
2653 if (getNumIterOperands() != opNumResults)
2654 return emitOpError(
2655 "mismatch in number of loop-carried values and defined values");
2656 if (getNumRegionIterArgs() != opNumResults)
2657 return emitOpError(
2658 "mismatch in number of basic block args and defined values");
2659 auto iterOperands = getIterOperands();
2660 auto iterArgs = getRegionIterArgs();
2661 auto opResults = getFinalValue() ? getResults().drop_front() : getResults();
2662 unsigned i = 0u;
2663 for (auto e : llvm::zip(iterOperands, iterArgs, opResults)) {
2664 if (std::get<0>(e).getType() != std::get<2>(e).getType())
2665 return emitOpError() << "types mismatch between " << i
2666 << "th iter operand and defined value";
2667 if (std::get<1>(e).getType() != std::get<2>(e).getType())
2668 return emitOpError() << "types mismatch between " << i
2669 << "th iter region arg and defined value";
2670
2671 i++;
2672 }
2673 auto reduceAttrs = getReduceAttrsAttr();
2674 if (getNumReduceOperands() != (reduceAttrs ? reduceAttrs.size() : 0))
2675 return emitOpError(
2676 "mismatch in number of reduction variables and reduction attributes");
2677 return mlir::success();
2678 }
2679
2680 void fir::DoLoopOp::print(mlir::OpAsmPrinter &p) {
2681 bool printBlockTerminators = false;
2682 p << ' ' << getInductionVar() << " = " << getLowerBound() << " to "
2683 << getUpperBound() << " step " << getStep();
2684 if (getUnordered())
2685 p << " unordered";
2686 if (hasReduceOperands()) {
2687 p << " reduce(";
2688 auto attrs = getReduceAttrsAttr();
2689 auto operands = getReduceOperands();
2690 llvm::interleaveComma(llvm::zip(attrs, operands), p, [&](auto it) {
2691 p << std::get<0>(it) << " -> " << std::get<1>(it) << " : "
2692 << std::get<1>(it).getType();
2693 });
2694 p << ')';
2695 printBlockTerminators = true;
2696 }
2697 if (hasIterOperands()) {
2698 p << " iter_args(";
2699 auto regionArgs = getRegionIterArgs();
2700 auto operands = getIterOperands();
2701 llvm::interleaveComma(llvm::zip(regionArgs, operands), p, [&](auto it) {
2702 p << std::get<0>(it) << " = " << std::get<1>(it);
2703 });
2704 p << ") -> (" << getResultTypes() << ')';
2705 printBlockTerminators = true;
2706 } else if (getFinalValue()) {
2707 p << " -> " << getResultTypes();
2708 printBlockTerminators = true;
2709 }
2710 p.printOptionalAttrDictWithKeyword(
2711 (*this)->getAttrs(),
2712 {"unordered", "finalValue", "reduceAttrs", "operandSegmentSizes"});
2713 p << ' ';
2714 p.printRegion(getRegion(), /*printEntryBlockArgs=*/false,
2715 printBlockTerminators);
2716 }
2717
2718 llvm::SmallVector<mlir::Region *> fir::DoLoopOp::getLoopRegions() {
2719 return {&getRegion()};
2720 }
2721
2722 /// Translate a value passed as an iter_arg to the corresponding block
2723 /// argument in the body of the loop.
2724 mlir::BlockArgument fir::DoLoopOp::iterArgToBlockArg(mlir::Value iterArg) {
2725 for (auto i : llvm::enumerate(getInitArgs()))
2726 if (iterArg == i.value())
2727 return getRegion().front().getArgument(i.index() + 1);
2728 return {};
2729 }
2730
2731 /// Translate the result vector (by index number) to the corresponding value
2732 /// to the `fir.result` Op.
2733 void fir::DoLoopOp::resultToSourceOps(
2734 llvm::SmallVectorImpl<mlir::Value> &results, unsigned resultNum) {
2735 auto oper = getFinalValue() ? resultNum + 1 : resultNum;
2736 auto *term = getRegion().front().getTerminator();
2737 if (oper < term->getNumOperands())
2738 results.push_back(term->getOperand(oper));
2739 }
2740
2741 /// Translate the block argument (by index number) to the corresponding value
2742 /// passed as an iter_arg to the parent DoLoopOp.
2743 mlir::Value fir::DoLoopOp::blockArgToSourceOp(unsigned blockArgNum) {
2744 if (blockArgNum > 0 && blockArgNum <= getInitArgs().size())
2745 return getInitArgs()[blockArgNum - 1];
2746 return {};
2747 }
2748
2749 std::optional<llvm::MutableArrayRef<mlir::OpOperand>>
2750 fir::DoLoopOp::getYieldedValuesMutable() {
2751 auto *term = getRegion().front().getTerminator();
2752 return getFinalValue() ? term->getOpOperands().drop_front()
2753 : term->getOpOperands();
2754 }
2755
2756 //===----------------------------------------------------------------------===//
2757 // DTEntryOp
2758 //===----------------------------------------------------------------------===//
2759
2760 mlir::ParseResult fir::DTEntryOp::parse(mlir::OpAsmParser &parser,
2761 mlir::OperationState &result) {
2762 llvm::StringRef methodName;
2763 // allow `methodName` or `"methodName"`
2764 if (failed(parser.parseOptionalKeyword(&methodName))) {
2765 mlir::StringAttr methodAttr;
2766 if (parser.parseAttribute(methodAttr, getMethodAttrName(result.name),
2767 result.attributes))
2768 return mlir::failure();
2769 } else {
2770 result.addAttribute(getMethodAttrName(result.name),
2771 parser.getBuilder().getStringAttr(methodName));
2772 }
2773 mlir::SymbolRefAttr calleeAttr;
2774 if (parser.parseComma() ||
2775 parser.parseAttribute(calleeAttr, fir::DTEntryOp::getProcAttrNameStr(),
2776 result.attributes))
2777 return mlir::failure();
2778 return mlir::success();
2779 }
2780
2781 void fir::DTEntryOp::print(mlir::OpAsmPrinter &p) {
2782 p << ' ' << getMethodAttr() << ", " << getProcAttr();
2783 }
2784
2785 //===----------------------------------------------------------------------===//
2786 // ReboxOp
2787 //===----------------------------------------------------------------------===//
2788
2789 /// Get the scalar type related to a fir.box type.
2790 /// Example: return f32 for !fir.box<!fir.heap<!fir.array<?x?xf32>>.
2791 static mlir::Type getBoxScalarEleTy(mlir::Type boxTy) {
2792 auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy);
2793 if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(eleTy))
2794 return seqTy.getEleTy();
2795 return eleTy;
2796 }
2797
2798 /// Test if \p t1 and \p t2 are compatible character types (if they can
2799 /// represent the same type at runtime).
2800 static bool areCompatibleCharacterTypes(mlir::Type t1, mlir::Type t2) {
2801 auto c1 = mlir::dyn_cast<fir::CharacterType>(t1);
2802 auto c2 = mlir::dyn_cast<fir::CharacterType>(t2);
2803 if (!c1 || !c2)
2804 return false;
2805 if (c1.hasDynamicLen() || c2.hasDynamicLen())
2806 return true;
2807 return c1.getLen() == c2.getLen();
2808 }
2809
2810 llvm::LogicalResult fir::ReboxOp::verify() {
2811 auto inputBoxTy = getBox().getType();
2812 if (fir::isa_unknown_size_box(inputBoxTy))
2813 return emitOpError("box operand must not have unknown rank or type");
2814 auto outBoxTy = getType();
2815 if (fir::isa_unknown_size_box(outBoxTy))
2816 return emitOpError("result type must not have unknown rank or type");
2817 auto inputRank = fir::getBoxRank(inputBoxTy);
2818 auto inputEleTy = getBoxScalarEleTy(inputBoxTy);
2819 auto outRank = fir::getBoxRank(outBoxTy);
2820 auto outEleTy = getBoxScalarEleTy(outBoxTy);
2821
2822 if (auto sliceVal = getSlice()) {
2823 // Slicing case
2824 if (mlir::cast<fir::SliceType>(sliceVal.getType()).getRank() != inputRank)
2825 return emitOpError("slice operand rank must match box operand rank");
2826 if (auto shapeVal = getShape()) {
2827 if (auto shiftTy = mlir::dyn_cast<fir::ShiftType>(shapeVal.getType())) {
2828 if (shiftTy.getRank() != inputRank)
2829 return emitOpError("shape operand and input box ranks must match "
2830 "when there is a slice");
2831 } else {
2832 return emitOpError("shape operand must absent or be a fir.shift "
2833 "when there is a slice");
2834 }
2835 }
2836 if (auto sliceOp = sliceVal.getDefiningOp()) {
2837 auto slicedRank = mlir::cast<fir::SliceOp>(sliceOp).getOutRank();
2838 if (slicedRank != outRank)
2839 return emitOpError("result type rank and rank after applying slice "
2840 "operand must match");
2841 }
2842 } else {
2843 // Reshaping case
2844 unsigned shapeRank = inputRank;
2845 if (auto shapeVal = getShape()) {
2846 auto ty = shapeVal.getType();
2847 if (auto shapeTy = mlir::dyn_cast<fir::ShapeType>(ty)) {
2848 shapeRank = shapeTy.getRank();
2849 } else if (auto shapeShiftTy = mlir::dyn_cast<fir::ShapeShiftType>(ty)) {
2850 shapeRank = shapeShiftTy.getRank();
2851 } else {
2852 auto shiftTy = mlir::cast<fir::ShiftType>(ty);
2853 shapeRank = shiftTy.getRank();
2854 if (shapeRank != inputRank)
2855 return emitOpError("shape operand and input box ranks must match "
2856 "when the shape is a fir.shift");
2857 }
2858 }
2859 if (shapeRank != outRank)
2860 return emitOpError("result type and shape operand ranks must match");
2861 }
2862
2863 if (inputEleTy != outEleTy) {
2864 // TODO: check that outBoxTy is a parent type of inputBoxTy for derived
2865 // types.
2866 // Character input and output types with constant length may be different if
2867 // there is a substring in the slice, otherwise, they must match. If any of
2868 // the types is a character with dynamic length, the other type can be any
2869 // character type.
2870 const bool typeCanMismatch =
2871 mlir::isa<fir::RecordType>(inputEleTy) ||
2872 mlir::isa<mlir::NoneType>(outEleTy) ||
2873 (mlir::isa<mlir::NoneType>(inputEleTy) &&
2874 mlir::isa<fir::RecordType>(outEleTy)) ||
2875 (getSlice() && mlir::isa<fir::CharacterType>(inputEleTy)) ||
2876 (getSlice() && fir::isa_complex(inputEleTy) &&
2877 mlir::isa<mlir::FloatType>(outEleTy)) ||
2878 areCompatibleCharacterTypes(inputEleTy, outEleTy);
2879 if (!typeCanMismatch)
2880 return emitOpError(
2881 "op input and output element types must match for intrinsic types");
2882 }
2883 return mlir::success();
2884 }
2885
2886 //===----------------------------------------------------------------------===//
2887 // ReboxAssumedRankOp
2888 //===----------------------------------------------------------------------===//
2889
2890 static bool areCompatibleAssumedRankElementType(mlir::Type inputEleTy,
2891 mlir::Type outEleTy) {
2892 if (inputEleTy == outEleTy)
2893 return true;
2894 // Output is unlimited polymorphic -> output dynamic type is the same as input
2895 // type.
2896 if (mlir::isa<mlir::NoneType>(outEleTy))
2897 return true;
2898 // Output/Input are derived types. Assuming input extends output type, output
2899 // dynamic type is the output static type, unless output is polymorphic.
2900 if (mlir::isa<fir::RecordType>(inputEleTy) &&
2901 mlir::isa<fir::RecordType>(outEleTy))
2902 return true;
2903 if (areCompatibleCharacterTypes(inputEleTy, outEleTy))
2904 return true;
2905 return false;
2906 }
2907
2908 llvm::LogicalResult fir::ReboxAssumedRankOp::verify() {
2909 mlir::Type inputType = getBox().getType();
2910 if (!mlir::isa<fir::BaseBoxType>(inputType) && !fir::isBoxAddress(inputType))
2911 return emitOpError("input must be a box or box address");
2912 mlir::Type inputEleTy =
2913 mlir::cast<fir::BaseBoxType>(fir::unwrapRefType(inputType))
2914 .unwrapInnerType();
2915 mlir::Type outEleTy =
2916 mlir::cast<fir::BaseBoxType>(getType()).unwrapInnerType();
2917 if (!areCompatibleAssumedRankElementType(inputEleTy, outEleTy))
2918 return emitOpError("input and output element types are incompatible");
2919 return mlir::success();
2920 }
2921
2922 void fir::ReboxAssumedRankOp::getEffects(
2923 llvm::SmallVectorImpl<
2924 mlir::SideEffects::EffectInstance<mlir::MemoryEffects::Effect>>
2925 &effects) {
2926 mlir::OpOperand &inputBox = getBoxMutable();
2927 if (fir::isBoxAddress(inputBox.get().getType()))
2928 effects.emplace_back(mlir::MemoryEffects::Read::get(), &inputBox,
2929 mlir::SideEffects::DefaultResource::get());
2930 }
2931
2932 //===----------------------------------------------------------------------===//
2933 // ResultOp
2934 //===----------------------------------------------------------------------===//
2935
2936 llvm::LogicalResult fir::ResultOp::verify() {
2937 auto *parentOp = (*this)->getParentOp();
2938 auto results = parentOp->getResults();
2939 auto operands = (*this)->getOperands();
2940
2941 if (parentOp->getNumResults() != getNumOperands())
2942 return emitOpError() << "parent of result must have same arity";
2943 for (auto e : llvm::zip(results, operands))
2944 if (std::get<0>(e).getType() != std::get<1>(e).getType())
2945 return emitOpError() << "types mismatch between result op and its parent";
2946 return mlir::success();
2947 }
2948
2949 //===----------------------------------------------------------------------===//
2950 // SaveResultOp
2951 //===----------------------------------------------------------------------===//
2952
2953 llvm::LogicalResult fir::SaveResultOp::verify() {
2954 auto resultType = getValue().getType();
2955 if (resultType != fir::dyn_cast_ptrEleTy(getMemref().getType()))
2956 return emitOpError("value type must match memory reference type");
2957 if (fir::isa_unknown_size_box(resultType))
2958 return emitOpError("cannot save !fir.box of unknown rank or type");
2959
2960 if (mlir::isa<fir::BoxType>(resultType)) {
2961 if (getShape() || !getTypeparams().empty())
2962 return emitOpError(
2963 "must not have shape or length operands if the value is a fir.box");
2964 return mlir::success();
2965 }
2966
2967 // fir.record or fir.array case.
2968 unsigned shapeTyRank = 0;
2969 if (auto shapeVal = getShape()) {
2970 auto shapeTy = shapeVal.getType();
2971 if (auto s = mlir::dyn_cast<fir::ShapeType>(shapeTy))
2972 shapeTyRank = s.getRank();
2973 else
2974 shapeTyRank = mlir::cast<fir::ShapeShiftType>(shapeTy).getRank();
2975 }
2976
2977 auto eleTy = resultType;
2978 if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(resultType)) {
2979 if (seqTy.getDimension() != shapeTyRank)
2980 emitOpError("shape operand must be provided and have the value rank "
2981 "when the value is a fir.array");
2982 eleTy = seqTy.getEleTy();
2983 } else {
2984 if (shapeTyRank != 0)
2985 emitOpError(
2986 "shape operand should only be provided if the value is a fir.array");
2987 }
2988
2989 if (auto recTy = mlir::dyn_cast<fir::RecordType>(eleTy)) {
2990 if (recTy.getNumLenParams() != getTypeparams().size())
2991 emitOpError("length parameters number must match with the value type "
2992 "length parameters");
2993 } else if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
2994 if (getTypeparams().size() > 1)
2995 emitOpError("no more than one length parameter must be provided for "
2996 "character value");
2997 } else {
2998 if (!getTypeparams().empty())
2999 emitOpError("length parameters must not be provided for this value type");
3000 }
3001
3002 return mlir::success();
3003 }
3004
3005 //===----------------------------------------------------------------------===//
3006 // IntegralSwitchTerminator
3007 //===----------------------------------------------------------------------===//
3008 static constexpr llvm::StringRef getCompareOffsetAttr() {
3009 return "compare_operand_offsets";
3010 }
3011
3012 static constexpr llvm::StringRef getTargetOffsetAttr() {
3013 return "target_operand_offsets";
3014 }
3015
3016 template <typename OpT>
3017 static llvm::LogicalResult verifyIntegralSwitchTerminator(OpT op) {
3018 if (!mlir::isa<mlir::IntegerType, mlir::IndexType, fir::IntegerType>(
3019 op.getSelector().getType()))
3020 return op.emitOpError("must be an integer");
3021 auto cases =
3022 op->template getAttrOfType<mlir::ArrayAttr>(op.getCasesAttr()).getValue();
3023 auto count = op.getNumDest();
3024 if (count == 0)
3025 return op.emitOpError("must have at least one successor");
3026 if (op.getNumConditions() != count)
3027 return op.emitOpError("number of cases and targets don't match");
3028 if (op.targetOffsetSize() != count)
3029 return op.emitOpError("incorrect number of successor operand groups");
3030 for (decltype(count) i = 0; i != count; ++i) {
3031 if (!mlir::isa<mlir::IntegerAttr, mlir::UnitAttr>(cases[i]))
3032 return op.emitOpError("invalid case alternative");
3033 }
3034 return mlir::success();
3035 }
3036
3037 static mlir::ParseResult parseIntegralSwitchTerminator(
3038 mlir::OpAsmParser &parser, mlir::OperationState &result,
3039 llvm::StringRef casesAttr, llvm::StringRef operandSegmentAttr) {
3040 mlir::OpAsmParser::UnresolvedOperand selector;
3041 mlir::Type type;
3042 if (fir::parseSelector(parser, result, selector, type))
3043 return mlir::failure();
3044
3045 llvm::SmallVector<mlir::Attribute> ivalues;
3046 llvm::SmallVector<mlir::Block *> dests;
3047 llvm::SmallVector<llvm::SmallVector<mlir::Value>> destArgs;
3048 while (true) {
3049 mlir::Attribute ivalue; // Integer or Unit
3050 mlir::Block *dest;
3051 llvm::SmallVector<mlir::Value> destArg;
3052 mlir::NamedAttrList temp;
3053 if (parser.parseAttribute(ivalue, "i", temp) || parser.parseComma() ||
3054 parser.parseSuccessorAndUseList(dest, destArg))
3055 return mlir::failure();
3056 ivalues.push_back(ivalue);
3057 dests.push_back(dest);
3058 destArgs.push_back(destArg);
3059 if (!parser.parseOptionalRSquare())
3060 break;
3061 if (parser.parseComma())
3062 return mlir::failure();
3063 }
3064 auto &bld = parser.getBuilder();
3065 result.addAttribute(casesAttr, bld.getArrayAttr(ivalues));
3066 llvm::SmallVector<int32_t> argOffs;
3067 int32_t sumArgs = 0;
3068 const auto count = dests.size();
3069 for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
3070 result.addSuccessors(dests[i]);
3071 result.addOperands(destArgs[i]);
3072 auto argSize = destArgs[i].size();
3073 argOffs.push_back(argSize);
3074 sumArgs += argSize;
3075 }
3076 result.addAttribute(operandSegmentAttr,
3077 bld.getDenseI32ArrayAttr({1, 0, sumArgs}));
3078 result.addAttribute(getTargetOffsetAttr(), bld.getDenseI32ArrayAttr(argOffs));
3079 return mlir::success();
3080 }
3081
3082 template <typename OpT>
3083 static void printIntegralSwitchTerminator(OpT op, mlir::OpAsmPrinter &p) {
3084 p << ' ';
3085 p.printOperand(op.getSelector());
3086 p << " : " << op.getSelector().getType() << " [";
3087 auto cases =
3088 op->template getAttrOfType<mlir::ArrayAttr>(op.getCasesAttr()).getValue();
3089 auto count = op.getNumConditions();
3090 for (decltype(count) i = 0; i != count; ++i) {
3091 if (i)
3092 p << ", ";
3093 auto &attr = cases[i];
3094 if (auto intAttr = mlir::dyn_cast_or_null<mlir::IntegerAttr>(attr))
3095 p << intAttr.getValue();
3096 else
3097 p.printAttribute(attr);
3098 p << ", ";
3099 op.printSuccessorAtIndex(p, i);
3100 }
3101 p << ']';
3102 p.printOptionalAttrDict(
3103 op->getAttrs(), {op.getCasesAttr(), getCompareOffsetAttr(),
3104 getTargetOffsetAttr(), op.getOperandSegmentSizeAttr()});
3105 }
3106
3107 //===----------------------------------------------------------------------===//
3108 // SelectOp
3109 //===----------------------------------------------------------------------===//
3110
3111 llvm::LogicalResult fir::SelectOp::verify() {
3112 return verifyIntegralSwitchTerminator(*this);
3113 }
3114
3115 mlir::ParseResult fir::SelectOp::parse(mlir::OpAsmParser &parser,
3116 mlir::OperationState &result) {
3117 return parseIntegralSwitchTerminator(parser, result, getCasesAttr(),
3118 getOperandSegmentSizeAttr());
3119 }
3120
3121 void fir::SelectOp::print(mlir::OpAsmPrinter &p) {
3122 printIntegralSwitchTerminator(*this, p);
3123 }
3124
3125 template <typename A, typename... AdditionalArgs>
3126 static A getSubOperands(unsigned pos, A allArgs, mlir::DenseI32ArrayAttr ranges,
3127 AdditionalArgs &&...additionalArgs) {
3128 unsigned start = 0;
3129 for (unsigned i = 0; i < pos; ++i)
3130 start += ranges[i];
3131 return allArgs.slice(start, ranges[pos],
3132 std::forward<AdditionalArgs>(additionalArgs)...);
3133 }
3134
3135 static mlir::MutableOperandRange
3136 getMutableSuccessorOperands(unsigned pos, mlir::MutableOperandRange operands,
3137 llvm::StringRef offsetAttr) {
3138 mlir::Operation *owner = operands.getOwner();
3139 mlir::NamedAttribute targetOffsetAttr =
3140 *owner->getAttrDictionary().getNamed(offsetAttr);
3141 return getSubOperands(
3142 pos, operands,
3143 mlir::cast<mlir::DenseI32ArrayAttr>(targetOffsetAttr.getValue()),
3144 mlir::MutableOperandRange::OperandSegment(pos, targetOffsetAttr));
3145 }
3146
3147 std::optional<mlir::OperandRange> fir::SelectOp::getCompareOperands(unsigned) {
3148 return {};
3149 }
3150
3151 std::optional<llvm::ArrayRef<mlir::Value>>
3152 fir::SelectOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) {
3153 return {};
3154 }
3155
3156 mlir::SuccessorOperands fir::SelectOp::getSuccessorOperands(unsigned oper) {
3157 return mlir::SuccessorOperands(::getMutableSuccessorOperands(
3158 oper, getTargetArgsMutable(), getTargetOffsetAttr()));
3159 }
3160
3161 std::optional<llvm::ArrayRef<mlir::Value>>
3162 fir::SelectOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
3163 unsigned oper) {
3164 auto a =
3165 (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(getTargetOffsetAttr());
3166 auto segments = (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(
3167 getOperandSegmentSizeAttr());
3168 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
3169 }
3170
3171 std::optional<mlir::ValueRange>
3172 fir::SelectOp::getSuccessorOperands(mlir::ValueRange operands, unsigned oper) {
3173 auto a =
3174 (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(getTargetOffsetAttr());
3175 auto segments = (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(
3176 getOperandSegmentSizeAttr());
3177 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
3178 }
3179
3180 unsigned fir::SelectOp::targetOffsetSize() {
3181 return (*this)
3182 ->getAttrOfType<mlir::DenseI32ArrayAttr>(getTargetOffsetAttr())
3183 .size();
3184 }
3185
3186 //===----------------------------------------------------------------------===//
3187 // SelectCaseOp
3188 //===----------------------------------------------------------------------===//
3189
3190 std::optional<mlir::OperandRange>
3191 fir::SelectCaseOp::getCompareOperands(unsigned cond) {
3192 auto a =
3193 (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(getCompareOffsetAttr());
3194 return {getSubOperands(cond, getCompareArgs(), a)};
3195 }
3196
3197 std::optional<llvm::ArrayRef<mlir::Value>>
3198 fir::SelectCaseOp::getCompareOperands(llvm::ArrayRef<mlir::Value> operands,
3199 unsigned cond) {
3200 auto a =
3201 (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(getCompareOffsetAttr());
3202 auto segments = (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(
3203 getOperandSegmentSizeAttr());
3204 return {getSubOperands(cond, getSubOperands(1, operands, segments), a)};
3205 }
3206
3207 std::optional<mlir::ValueRange>
3208 fir::SelectCaseOp::getCompareOperands(mlir::ValueRange operands,
3209 unsigned cond) {
3210 auto a =
3211 (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(getCompareOffsetAttr());
3212 auto segments = (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(
3213 getOperandSegmentSizeAttr());
3214 return {getSubOperands(cond, getSubOperands(1, operands, segments), a)};
3215 }
3216
3217 mlir::SuccessorOperands fir::SelectCaseOp::getSuccessorOperands(unsigned oper) {
3218 return mlir::SuccessorOperands(::getMutableSuccessorOperands(
3219 oper, getTargetArgsMutable(), getTargetOffsetAttr()));
3220 }
3221
3222 std::optional<llvm::ArrayRef<mlir::Value>>
3223 fir::SelectCaseOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
3224 unsigned oper) {
3225 auto a =
3226 (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(getTargetOffsetAttr());
3227 auto segments = (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(
3228 getOperandSegmentSizeAttr());
3229 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
3230 }
3231
3232 std::optional<mlir::ValueRange>
3233 fir::SelectCaseOp::getSuccessorOperands(mlir::ValueRange operands,
3234 unsigned oper) {
3235 auto a =
3236 (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(getTargetOffsetAttr());
3237 auto segments = (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(
3238 getOperandSegmentSizeAttr());
3239 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
3240 }
3241
3242 // parser for fir.select_case Op
3243 mlir::ParseResult fir::SelectCaseOp::parse(mlir::OpAsmParser &parser,
3244 mlir::OperationState &result) {
3245 mlir::OpAsmParser::UnresolvedOperand selector;
3246 mlir::Type type;
3247 if (fir::parseSelector(parser, result, selector, type))
3248 return mlir::failure();
3249
3250 llvm::SmallVector<mlir::Attribute> attrs;
3251 llvm::SmallVector<mlir::OpAsmParser::UnresolvedOperand> opers;
3252 llvm::SmallVector<mlir::Block *> dests;
3253 llvm::SmallVector<llvm::SmallVector<mlir::Value>> destArgs;
3254 llvm::SmallVector<std::int32_t> argOffs;
3255 std::int32_t offSize = 0;
3256 while (true) {
3257 mlir::Attribute attr;
3258 mlir::Block *dest;
3259 llvm::SmallVector<mlir::Value> destArg;
3260 mlir::NamedAttrList temp;
3261 if (parser.parseAttribute(attr, "a", temp) || isValidCaseAttr(attr) ||
3262 parser.parseComma())
3263 return mlir::failure();
3264 attrs.push_back(attr);
3265 if (mlir::dyn_cast_or_null<mlir::UnitAttr>(attr)) {
3266 argOffs.push_back(0);
3267 } else if (mlir::dyn_cast_or_null<fir::ClosedIntervalAttr>(attr)) {
3268 mlir::OpAsmParser::UnresolvedOperand oper1;
3269 mlir::OpAsmParser::UnresolvedOperand oper2;
3270 if (parser.parseOperand(oper1) || parser.parseComma() ||
3271 parser.parseOperand(oper2) || parser.parseComma())
3272 return mlir::failure();
3273 opers.push_back(oper1);
3274 opers.push_back(oper2);
3275 argOffs.push_back(2);
3276 offSize += 2;
3277 } else {
3278 mlir::OpAsmParser::UnresolvedOperand oper;
3279 if (parser.parseOperand(oper) || parser.parseComma())
3280 return mlir::failure();
3281 opers.push_back(oper);
3282 argOffs.push_back(1);
3283 ++offSize;
3284 }
3285 if (parser.parseSuccessorAndUseList(dest, destArg))
3286 return mlir::failure();
3287 dests.push_back(dest);
3288 destArgs.push_back(destArg);
3289 if (mlir::succeeded(parser.parseOptionalRSquare()))
3290 break;
3291 if (parser.parseComma())
3292 return mlir::failure();
3293 }
3294 result.addAttribute(fir::SelectCaseOp::getCasesAttr(),
3295 parser.getBuilder().getArrayAttr(attrs));
3296 if (parser.resolveOperands(opers, type, result.operands))
3297 return mlir::failure();
3298 llvm::SmallVector<int32_t> targOffs;
3299 int32_t toffSize = 0;
3300 const auto count = dests.size();
3301 for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
3302 result.addSuccessors(dests[i]);
3303 result.addOperands(destArgs[i]);
3304 auto argSize = destArgs[i].size();
3305 targOffs.push_back(argSize);
3306 toffSize += argSize;
3307 }
3308 auto &bld = parser.getBuilder();
3309 result.addAttribute(fir::SelectCaseOp::getOperandSegmentSizeAttr(),
3310 bld.getDenseI32ArrayAttr({1, offSize, toffSize}));
3311 result.addAttribute(getCompareOffsetAttr(),
3312 bld.getDenseI32ArrayAttr(argOffs));
3313 result.addAttribute(getTargetOffsetAttr(),
3314 bld.getDenseI32ArrayAttr(targOffs));
3315 return mlir::success();
3316 }
3317
3318 void fir::SelectCaseOp::print(mlir::OpAsmPrinter &p) {
3319 p << ' ';
3320 p.printOperand(getSelector());
3321 p << " : " << getSelector().getType() << " [";
3322 auto cases =
3323 getOperation()->getAttrOfType<mlir::ArrayAttr>(getCasesAttr()).getValue();
3324 auto count = getNumConditions();
3325 for (decltype(count) i = 0; i != count; ++i) {
3326 if (i)
3327 p << ", ";
3328 p << cases[i] << ", ";
3329 if (!mlir::isa<mlir::UnitAttr>(cases[i])) {
3330 auto caseArgs = *getCompareOperands(i);
3331 p.printOperand(*caseArgs.begin());
3332 p << ", ";
3333 if (mlir::isa<fir::ClosedIntervalAttr>(cases[i])) {
3334 p.printOperand(*(++caseArgs.begin()));
3335 p << ", ";
3336 }
3337 }
3338 printSuccessorAtIndex(p, i);
3339 }
3340 p << ']';
3341 p.printOptionalAttrDict(getOperation()->getAttrs(),
3342 {getCasesAttr(), getCompareOffsetAttr(),
3343 getTargetOffsetAttr(), getOperandSegmentSizeAttr()});
3344 }
3345
3346 unsigned fir::SelectCaseOp::compareOffsetSize() {
3347 return (*this)
3348 ->getAttrOfType<mlir::DenseI32ArrayAttr>(getCompareOffsetAttr())
3349 .size();
3350 }
3351
3352 unsigned fir::SelectCaseOp::targetOffsetSize() {
3353 return (*this)
3354 ->getAttrOfType<mlir::DenseI32ArrayAttr>(getTargetOffsetAttr())
3355 .size();
3356 }
3357
3358 void fir::SelectCaseOp::build(mlir::OpBuilder &builder,
3359 mlir::OperationState &result,
3360 mlir::Value selector,
3361 llvm::ArrayRef<mlir::Attribute> compareAttrs,
3362 llvm::ArrayRef<mlir::ValueRange> cmpOperands,
3363 llvm::ArrayRef<mlir::Block *> destinations,
3364 llvm::ArrayRef<mlir::ValueRange> destOperands,
3365 llvm::ArrayRef<mlir::NamedAttribute> attributes) {
3366 result.addOperands(selector);
3367 result.addAttribute(getCasesAttr(), builder.getArrayAttr(compareAttrs));
3368 llvm::SmallVector<int32_t> operOffs;
3369 int32_t operSize = 0;
3370 for (auto attr : compareAttrs) {
3371 if (mlir::isa<fir::ClosedIntervalAttr>(attr)) {
3372 operOffs.push_back(2);
3373 operSize += 2;
3374 } else if (mlir::isa<mlir::UnitAttr>(attr)) {
3375 operOffs.push_back(0);
3376 } else {
3377 operOffs.push_back(1);
3378 ++operSize;
3379 }
3380 }
3381 for (auto ops : cmpOperands)
3382 result.addOperands(ops);
3383 result.addAttribute(getCompareOffsetAttr(),
3384 builder.getDenseI32ArrayAttr(operOffs));
3385 const auto count = destinations.size();
3386 for (auto d : destinations)
3387 result.addSuccessors(d);
3388 const auto opCount = destOperands.size();
3389 llvm::SmallVector<std::int32_t> argOffs;
3390 std::int32_t sumArgs = 0;
3391 for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
3392 if (i < opCount) {
3393 result.addOperands(destOperands[i]);
3394 const auto argSz = destOperands[i].size();
3395 argOffs.push_back(argSz);
3396 sumArgs += argSz;
3397 } else {
3398 argOffs.push_back(0);
3399 }
3400 }
3401 result.addAttribute(getOperandSegmentSizeAttr(),
3402 builder.getDenseI32ArrayAttr({1, operSize, sumArgs}));
3403 result.addAttribute(getTargetOffsetAttr(),
3404 builder.getDenseI32ArrayAttr(argOffs));
3405 result.addAttributes(attributes);
3406 }
3407
3408 /// This builder has a slightly simplified interface in that the list of
3409 /// operands need not be partitioned by the builder. Instead the operands are
3410 /// partitioned here, before being passed to the default builder. This
3411 /// partitioning is unchecked, so can go awry on bad input.
3412 void fir::SelectCaseOp::build(mlir::OpBuilder &builder,
3413 mlir::OperationState &result,
3414 mlir::Value selector,
3415 llvm::ArrayRef<mlir::Attribute> compareAttrs,
3416 llvm::ArrayRef<mlir::Value> cmpOpList,
3417 llvm::ArrayRef<mlir::Block *> destinations,
3418 llvm::ArrayRef<mlir::ValueRange> destOperands,
3419 llvm::ArrayRef<mlir::NamedAttribute> attributes) {
3420 llvm::SmallVector<mlir::ValueRange> cmpOpers;
3421 auto iter = cmpOpList.begin();
3422 for (auto &attr : compareAttrs) {
3423 if (mlir::isa<fir::ClosedIntervalAttr>(attr)) {
3424 cmpOpers.push_back(mlir::ValueRange({iter, iter + 2}));
3425 iter += 2;
3426 } else if (mlir::isa<mlir::UnitAttr>(attr)) {
3427 cmpOpers.push_back(mlir::ValueRange{});
3428 } else {
3429 cmpOpers.push_back(mlir::ValueRange({iter, iter + 1}));
3430 ++iter;
3431 }
3432 }
3433 build(builder, result, selector, compareAttrs, cmpOpers, destinations,
3434 destOperands, attributes);
3435 }
3436
3437 llvm::LogicalResult fir::SelectCaseOp::verify() {
3438 if (!mlir::isa<mlir::IntegerType, mlir::IndexType, fir::IntegerType,
3439 fir::LogicalType, fir::CharacterType>(getSelector().getType()))
3440 return emitOpError("must be an integer, character, or logical");
3441 auto cases =
3442 getOperation()->getAttrOfType<mlir::ArrayAttr>(getCasesAttr()).getValue();
3443 auto count = getNumDest();
3444 if (count == 0)
3445 return emitOpError("must have at least one successor");
3446 if (getNumConditions() != count)
3447 return emitOpError("number of conditions and successors don't match");
3448 if (compareOffsetSize() != count)
3449 return emitOpError("incorrect number of compare operand groups");
3450 if (targetOffsetSize() != count)
3451 return emitOpError("incorrect number of successor operand groups");
3452 for (decltype(count) i = 0; i != count; ++i) {
3453 auto &attr = cases[i];
3454 if (!(mlir::isa<fir::PointIntervalAttr>(attr) ||
3455 mlir::isa<fir::LowerBoundAttr>(attr) ||
3456 mlir::isa<fir::UpperBoundAttr>(attr) ||
3457 mlir::isa<fir::ClosedIntervalAttr>(attr) ||
3458 mlir::isa<mlir::UnitAttr>(attr)))
3459 return emitOpError("incorrect select case attribute type");
3460 }
3461 return mlir::success();
3462 }
3463
3464 //===----------------------------------------------------------------------===//
3465 // SelectRankOp
3466 //===----------------------------------------------------------------------===//
3467
3468 llvm::LogicalResult fir::SelectRankOp::verify() {
3469 return verifyIntegralSwitchTerminator(*this);
3470 }
3471
3472 mlir::ParseResult fir::SelectRankOp::parse(mlir::OpAsmParser &parser,
3473 mlir::OperationState &result) {
3474 return parseIntegralSwitchTerminator(parser, result, getCasesAttr(),
3475 getOperandSegmentSizeAttr());
3476 }
3477
3478 void fir::SelectRankOp::print(mlir::OpAsmPrinter &p) {
3479 printIntegralSwitchTerminator(*this, p);
3480 }
3481
3482 std::optional<mlir::OperandRange>
3483 fir::SelectRankOp::getCompareOperands(unsigned) {
3484 return {};
3485 }
3486
3487 std::optional<llvm::ArrayRef<mlir::Value>>
3488 fir::SelectRankOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) {
3489 return {};
3490 }
3491
3492 mlir::SuccessorOperands fir::SelectRankOp::getSuccessorOperands(unsigned oper) {
3493 return mlir::SuccessorOperands(::getMutableSuccessorOperands(
3494 oper, getTargetArgsMutable(), getTargetOffsetAttr()));
3495 }
3496
3497 std::optional<llvm::ArrayRef<mlir::Value>>
3498 fir::SelectRankOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
3499 unsigned oper) {
3500 auto a =
3501 (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(getTargetOffsetAttr());
3502 auto segments = (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(
3503 getOperandSegmentSizeAttr());
3504 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
3505 }
3506
3507 std::optional<mlir::ValueRange>
3508 fir::SelectRankOp::getSuccessorOperands(mlir::ValueRange operands,
3509 unsigned oper) {
3510 auto a =
3511 (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(getTargetOffsetAttr());
3512 auto segments = (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(
3513 getOperandSegmentSizeAttr());
3514 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
3515 }
3516
3517 unsigned fir::SelectRankOp::targetOffsetSize() {
3518 return (*this)
3519 ->getAttrOfType<mlir::DenseI32ArrayAttr>(getTargetOffsetAttr())
3520 .size();
3521 }
3522
3523 //===----------------------------------------------------------------------===//
3524 // SelectTypeOp
3525 //===----------------------------------------------------------------------===//
3526
3527 std::optional<mlir::OperandRange>
3528 fir::SelectTypeOp::getCompareOperands(unsigned) {
3529 return {};
3530 }
3531
3532 std::optional<llvm::ArrayRef<mlir::Value>>
3533 fir::SelectTypeOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) {
3534 return {};
3535 }
3536
3537 mlir::SuccessorOperands fir::SelectTypeOp::getSuccessorOperands(unsigned oper) {
3538 return mlir::SuccessorOperands(::getMutableSuccessorOperands(
3539 oper, getTargetArgsMutable(), getTargetOffsetAttr()));
3540 }
3541
3542 std::optional<llvm::ArrayRef<mlir::Value>>
3543 fir::SelectTypeOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
3544 unsigned oper) {
3545 auto a =
3546 (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(getTargetOffsetAttr());
3547 auto segments = (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(
3548 getOperandSegmentSizeAttr());
3549 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
3550 }
3551
3552 std::optional<mlir::ValueRange>
3553 fir::SelectTypeOp::getSuccessorOperands(mlir::ValueRange operands,
3554 unsigned oper) {
3555 auto a =
3556 (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(getTargetOffsetAttr());
3557 auto segments = (*this)->getAttrOfType<mlir::DenseI32ArrayAttr>(
3558 getOperandSegmentSizeAttr());
3559 return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
3560 }
3561
3562 mlir::ParseResult fir::SelectTypeOp::parse(mlir::OpAsmParser &parser,
3563 mlir::OperationState &result) {
3564 mlir::OpAsmParser::UnresolvedOperand selector;
3565 mlir::Type type;
3566 if (fir::parseSelector(parser, result, selector, type))
3567 return mlir::failure();
3568
3569 llvm::SmallVector<mlir::Attribute> attrs;
3570 llvm::SmallVector<mlir::Block *> dests;
3571 llvm::SmallVector<llvm::SmallVector<mlir::Value>> destArgs;
3572 while (true) {
3573 mlir::Attribute attr;
3574 mlir::Block *dest;
3575 llvm::SmallVector<mlir::Value> destArg;
3576 mlir::NamedAttrList temp;
3577 if (parser.parseAttribute(attr, "a", temp) || parser.parseComma() ||
3578 parser.parseSuccessorAndUseList(dest, destArg))
3579 return mlir::failure();
3580 attrs.push_back(attr);
3581 dests.push_back(dest);
3582 destArgs.push_back(destArg);
3583 if (mlir::succeeded(parser.parseOptionalRSquare()))
3584 break;
3585 if (parser.parseComma())
3586 return mlir::failure();
3587 }
3588 auto &bld = parser.getBuilder();
3589 result.addAttribute(fir::SelectTypeOp::getCasesAttr(),
3590 bld.getArrayAttr(attrs));
3591 llvm::SmallVector<int32_t> argOffs;
3592 int32_t offSize = 0;
3593 const auto count = dests.size();
3594 for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
3595 result.addSuccessors(dests[i]);
3596 result.addOperands(destArgs[i]);
3597 auto argSize = destArgs[i].size();
3598 argOffs.push_back(argSize);
3599 offSize += argSize;
3600 }
3601 result.addAttribute(fir::SelectTypeOp::getOperandSegmentSizeAttr(),
3602 bld.getDenseI32ArrayAttr({1, 0, offSize}));
3603 result.addAttribute(getTargetOffsetAttr(), bld.getDenseI32ArrayAttr(argOffs));
3604 return mlir::success();
3605 }
3606
3607 unsigned fir::SelectTypeOp::targetOffsetSize() {
3608 return (*this)
3609 ->getAttrOfType<mlir::DenseI32ArrayAttr>(getTargetOffsetAttr())
3610 .size();
3611 }
3612
3613 void fir::SelectTypeOp::print(mlir::OpAsmPrinter &p) {
3614 p << ' ';
3615 p.printOperand(getSelector());
3616 p << " : " << getSelector().getType() << " [";
3617 auto cases =
3618 getOperation()->getAttrOfType<mlir::ArrayAttr>(getCasesAttr()).getValue();
3619 auto count = getNumConditions();
3620 for (decltype(count) i = 0; i != count; ++i) {
3621 if (i)
3622 p << ", ";
3623 p << cases[i] << ", ";
3624 printSuccessorAtIndex(p, i);
3625 }
3626 p << ']';
3627 p.printOptionalAttrDict(getOperation()->getAttrs(),
3628 {getCasesAttr(), getCompareOffsetAttr(),
3629 getTargetOffsetAttr(),
3630 fir::SelectTypeOp::getOperandSegmentSizeAttr()});
3631 }
3632
3633 llvm::LogicalResult fir::SelectTypeOp::verify() {
3634 if (!mlir::isa<fir::BaseBoxType>(getSelector().getType()))
3635 return emitOpError("must be a fir.class or fir.box type");
3636 if (auto boxType = mlir::dyn_cast<fir::BoxType>(getSelector().getType()))
3637 if (!mlir::isa<mlir::NoneType>(boxType.getEleTy()))
3638 return emitOpError("selector must be polymorphic");
3639 auto typeGuardAttr = getCases();
3640 for (unsigned idx = 0; idx < typeGuardAttr.size(); ++idx)
3641 if (mlir::isa<mlir::UnitAttr>(typeGuardAttr[idx]) &&
3642 idx != typeGuardAttr.size() - 1)
3643 return emitOpError("default must be the last attribute");
3644 auto count = getNumDest();
3645 if (count == 0)
3646 return emitOpError("must have at least one successor");
3647 if (getNumConditions() != count)
3648 return emitOpError("number of conditions and successors don't match");
3649 if (targetOffsetSize() != count)
3650 return emitOpError("incorrect number of successor operand groups");
3651 for (unsigned i = 0; i != count; ++i) {
3652 if (!mlir::isa<fir::ExactTypeAttr, fir::SubclassAttr, mlir::UnitAttr>(
3653 typeGuardAttr[i]))
3654 return emitOpError("invalid type-case alternative");
3655 }
3656 return mlir::success();
3657 }
3658
3659 void fir::SelectTypeOp::build(mlir::OpBuilder &builder,
3660 mlir::OperationState &result,
3661 mlir::Value selector,
3662 llvm::ArrayRef<mlir::Attribute> typeOperands,
3663 llvm::ArrayRef<mlir::Block *> destinations,
3664 llvm::ArrayRef<mlir::ValueRange> destOperands,
3665 llvm::ArrayRef<mlir::NamedAttribute> attributes) {
3666 result.addOperands(selector);
3667 result.addAttribute(getCasesAttr(), builder.getArrayAttr(typeOperands));
3668 const auto count = destinations.size();
3669 for (mlir::Block *dest : destinations)
3670 result.addSuccessors(dest);
3671 const auto opCount = destOperands.size();
3672 llvm::SmallVector<int32_t> argOffs;
3673 int32_t sumArgs = 0;
3674 for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
3675 if (i < opCount) {
3676 result.addOperands(destOperands[i]);
3677 const auto argSz = destOperands[i].size();
3678 argOffs.push_back(argSz);
3679 sumArgs += argSz;
3680 } else {
3681 argOffs.push_back(0);
3682 }
3683 }
3684 result.addAttribute(getOperandSegmentSizeAttr(),
3685 builder.getDenseI32ArrayAttr({1, 0, sumArgs}));
3686 result.addAttribute(getTargetOffsetAttr(),
3687 builder.getDenseI32ArrayAttr(argOffs));
3688 result.addAttributes(attributes);
3689 }
3690
3691 //===----------------------------------------------------------------------===//
3692 // ShapeOp
3693 //===----------------------------------------------------------------------===//
3694
3695 llvm::LogicalResult fir::ShapeOp::verify() {
3696 auto size = getExtents().size();
3697 auto shapeTy = mlir::dyn_cast<fir::ShapeType>(getType());
3698 assert(shapeTy && "must be a shape type");
3699 if (shapeTy.getRank() != size)
3700 return emitOpError("shape type rank mismatch");
3701 return mlir::success();
3702 }
3703
3704 void fir::ShapeOp::build(mlir::OpBuilder &builder, mlir::OperationState &result,
3705 mlir::ValueRange extents) {
3706 auto type = fir::ShapeType::get(builder.getContext(), extents.size());
3707 build(builder, result, type, extents);
3708 }
3709
3710 //===----------------------------------------------------------------------===//
3711 // ShapeShiftOp
3712 //===----------------------------------------------------------------------===//
3713
3714 llvm::LogicalResult fir::ShapeShiftOp::verify() {
3715 auto size = getPairs().size();
3716 if (size < 2 || size > 16 * 2)
3717 return emitOpError("incorrect number of args");
3718 if (size % 2 != 0)
3719 return emitOpError("requires a multiple of 2 args");
3720 auto shapeTy = mlir::dyn_cast<fir::ShapeShiftType>(getType());
3721 assert(shapeTy && "must be a shape shift type");
3722 if (shapeTy.getRank() * 2 != size)
3723 return emitOpError("shape type rank mismatch");
3724 return mlir::success();
3725 }
3726
3727 //===----------------------------------------------------------------------===//
3728 // ShiftOp
3729 //===----------------------------------------------------------------------===//
3730
3731 llvm::LogicalResult fir::ShiftOp::verify() {
3732 auto size = getOrigins().size();
3733 auto shiftTy = mlir::dyn_cast<fir::ShiftType>(getType());
3734 assert(shiftTy && "must be a shift type");
3735 if (shiftTy.getRank() != size)
3736 return emitOpError("shift type rank mismatch");
3737 return mlir::success();
3738 }
3739
3740 //===----------------------------------------------------------------------===//
3741 // SliceOp
3742 //===----------------------------------------------------------------------===//
3743
3744 void fir::SliceOp::build(mlir::OpBuilder &builder, mlir::OperationState &result,
3745 mlir::ValueRange trips, mlir::ValueRange path,
3746 mlir::ValueRange substr) {
3747 const auto rank = trips.size() / 3;
3748 auto sliceTy = fir::SliceType::get(builder.getContext(), rank);
3749 build(builder, result, sliceTy, trips, path, substr);
3750 }
3751
3752 /// Return the output rank of a slice op. The output rank must be between 1 and
3753 /// the rank of the array being sliced (inclusive).
3754 unsigned fir::SliceOp::getOutputRank(mlir::ValueRange triples) {
3755 unsigned rank = 0;
3756 if (!triples.empty()) {
3757 for (unsigned i = 1, end = triples.size(); i < end; i += 3) {
3758 auto *op = triples[i].getDefiningOp();
3759 if (!mlir::isa_and_nonnull<fir::UndefOp>(op))
3760 ++rank;
3761 }
3762 assert(rank > 0);
3763 }
3764 return rank;
3765 }
3766
3767 llvm::LogicalResult fir::SliceOp::verify() {
3768 auto size = getTriples().size();
3769 if (size < 3 || size > 16 * 3)
3770 return emitOpError("incorrect number of args for triple");
3771 if (size % 3 != 0)
3772 return emitOpError("requires a multiple of 3 args");
3773 auto sliceTy = mlir::dyn_cast<fir::SliceType>(getType());
3774 assert(sliceTy && "must be a slice type");
3775 if (sliceTy.getRank() * 3 != size)
3776 return emitOpError("slice type rank mismatch");
3777 return mlir::success();
3778 }
3779
3780 //===----------------------------------------------------------------------===//
3781 // StoreOp
3782 //===----------------------------------------------------------------------===//
3783
3784 mlir::Type fir::StoreOp::elementType(mlir::Type refType) {
3785 return fir::dyn_cast_ptrEleTy(refType);
3786 }
3787
3788 mlir::ParseResult fir::StoreOp::parse(mlir::OpAsmParser &parser,
3789 mlir::OperationState &result) {
3790 mlir::Type type;
3791 mlir::OpAsmParser::UnresolvedOperand oper;
3792 mlir::OpAsmParser::UnresolvedOperand store;
3793 if (parser.parseOperand(oper) || parser.parseKeyword("to") ||
3794 parser.parseOperand(store) ||
3795 parser.parseOptionalAttrDict(result.attributes) ||
3796 parser.parseColonType(type) ||
3797 parser.resolveOperand(oper, fir::StoreOp::elementType(type),
3798 result.operands) ||
3799 parser.resolveOperand(store, type, result.operands))
3800 return mlir::failure();
3801 return mlir::success();
3802 }
3803
3804 void fir::StoreOp::print(mlir::OpAsmPrinter &p) {
3805 p << ' ';
3806 p.printOperand(getValue());
3807 p << " to ";
3808 p.printOperand(getMemref());
3809 p.printOptionalAttrDict(getOperation()->getAttrs(), {});
3810 p << " : " << getMemref().getType();
3811 }
3812
3813 llvm::LogicalResult fir::StoreOp::verify() {
3814 if (getValue().getType() != fir::dyn_cast_ptrEleTy(getMemref().getType()))
3815 return emitOpError("store value type must match memory reference type");
3816 return mlir::success();
3817 }
3818
3819 void fir::StoreOp::build(mlir::OpBuilder &builder, mlir::OperationState &result,
3820 mlir::Value value, mlir::Value memref) {
3821 build(builder, result, value, memref, {});
3822 }
3823
3824 //===----------------------------------------------------------------------===//
3825 // StringLitOp
3826 //===----------------------------------------------------------------------===//
3827
3828 inline fir::CharacterType::KindTy stringLitOpGetKind(fir::StringLitOp op) {
3829 auto eleTy = mlir::cast<fir::SequenceType>(op.getType()).getEleTy();
3830 return mlir::cast<fir::CharacterType>(eleTy).getFKind();
3831 }
3832
3833 bool fir::StringLitOp::isWideValue() { return stringLitOpGetKind(*this) != 1; }
3834
3835 static mlir::NamedAttribute
3836 mkNamedIntegerAttr(mlir::OpBuilder &builder, llvm::StringRef name, int64_t v) {
3837 assert(v > 0);
3838 return builder.getNamedAttr(
3839 name, builder.getIntegerAttr(builder.getIntegerType(64), v));
3840 }
3841
3842 void fir::StringLitOp::build(mlir::OpBuilder &builder,
3843 mlir::OperationState &result,
3844 fir::CharacterType inType, llvm::StringRef val,
3845 std::optional<int64_t> len) {
3846 auto valAttr = builder.getNamedAttr(value(), builder.getStringAttr(val));
3847 int64_t length = len ? *len : inType.getLen();
3848 auto lenAttr = mkNamedIntegerAttr(builder, size(), length);
3849 result.addAttributes({valAttr, lenAttr});
3850 result.addTypes(inType);
3851 }
3852
3853 template <typename C>
3854 static mlir::ArrayAttr convertToArrayAttr(mlir::OpBuilder &builder,
3855 llvm::ArrayRef<C> xlist) {
3856 llvm::SmallVector<mlir::Attribute> attrs;
3857 auto ty = builder.getIntegerType(8 * sizeof(C));
3858 for (auto ch : xlist)
3859 attrs.push_back(builder.getIntegerAttr(ty, ch));
3860 return builder.getArrayAttr(attrs);
3861 }
3862
3863 void fir::StringLitOp::build(mlir::OpBuilder &builder,
3864 mlir::OperationState &result,
3865 fir::CharacterType inType,
3866 llvm::ArrayRef<char> vlist,
3867 std::optional<std::int64_t> len) {
3868 auto valAttr =
3869 builder.getNamedAttr(xlist(), convertToArrayAttr(builder, vlist));
3870 std::int64_t length = len ? *len : inType.getLen();
3871 auto lenAttr = mkNamedIntegerAttr(builder, size(), length);
3872 result.addAttributes({valAttr, lenAttr});
3873 result.addTypes(inType);
3874 }
3875
3876 void fir::StringLitOp::build(mlir::OpBuilder &builder,
3877 mlir::OperationState &result,
3878 fir::CharacterType inType,
3879 llvm::ArrayRef<char16_t> vlist,
3880 std::optional<std::int64_t> len) {
3881 auto valAttr =
3882 builder.getNamedAttr(xlist(), convertToArrayAttr(builder, vlist));
3883 std::int64_t length = len ? *len : inType.getLen();
3884 auto lenAttr = mkNamedIntegerAttr(builder, size(), length);
3885 result.addAttributes({valAttr, lenAttr});
3886 result.addTypes(inType);
3887 }
3888
3889 void fir::StringLitOp::build(mlir::OpBuilder &builder,
3890 mlir::OperationState &result,
3891 fir::CharacterType inType,
3892 llvm::ArrayRef<char32_t> vlist,
3893 std::optional<std::int64_t> len) {
3894 auto valAttr =
3895 builder.getNamedAttr(xlist(), convertToArrayAttr(builder, vlist));
3896 std::int64_t length = len ? *len : inType.getLen();
3897 auto lenAttr = mkNamedIntegerAttr(builder, size(), length);
3898 result.addAttributes({valAttr, lenAttr});
3899 result.addTypes(inType);
3900 }
3901
3902 mlir::ParseResult fir::StringLitOp::parse(mlir::OpAsmParser &parser,
3903 mlir::OperationState &result) {
3904 auto &builder = parser.getBuilder();
3905 mlir::Attribute val;
3906 mlir::NamedAttrList attrs;
3907 llvm::SMLoc trailingTypeLoc;
3908 if (parser.parseAttribute(val, "fake", attrs))
3909 return mlir::failure();
3910 if (auto v = mlir::dyn_cast<mlir::StringAttr>(val))
3911 result.attributes.push_back(
3912 builder.getNamedAttr(fir::StringLitOp::value(), v));
3913 else if (auto v = mlir::dyn_cast<mlir::DenseElementsAttr>(val))
3914 result.attributes.push_back(
3915 builder.getNamedAttr(fir::StringLitOp::xlist(), v));
3916 else if (auto v = mlir::dyn_cast<mlir::ArrayAttr>(val))
3917 result.attributes.push_back(
3918 builder.getNamedAttr(fir::StringLitOp::xlist(), v));
3919 else
3920 return parser.emitError(parser.getCurrentLocation(),
3921 "found an invalid constant");
3922 mlir::IntegerAttr sz;
3923 mlir::Type type;
3924 if (parser.parseLParen() ||
3925 parser.parseAttribute(sz, fir::StringLitOp::size(), result.attributes) ||
3926 parser.parseRParen() || parser.getCurrentLocation(&trailingTypeLoc) ||
3927 parser.parseColonType(type))
3928 return mlir::failure();
3929 auto charTy = mlir::dyn_cast<fir::CharacterType>(type);
3930 if (!charTy)
3931 return parser.emitError(trailingTypeLoc, "must have character type");
3932 type = fir::CharacterType::get(builder.getContext(), charTy.getFKind(),
3933 sz.getInt());
3934 if (!type || parser.addTypesToList(type, result.types))
3935 return mlir::failure();
3936 return mlir::success();
3937 }
3938
3939 void fir::StringLitOp::print(mlir::OpAsmPrinter &p) {
3940 p << ' ' << getValue() << '(';
3941 p << mlir::cast<mlir::IntegerAttr>(getSize()).getValue() << ") : ";
3942 p.printType(getType());
3943 }
3944
3945 llvm::LogicalResult fir::StringLitOp::verify() {
3946 if (mlir::cast<mlir::IntegerAttr>(getSize()).getValue().isNegative())
3947 return emitOpError("size must be non-negative");
3948 if (auto xl = getOperation()->getAttr(fir::StringLitOp::xlist())) {
3949 if (auto xList = mlir::dyn_cast<mlir::ArrayAttr>(xl)) {
3950 for (auto a : xList)
3951 if (!mlir::isa<mlir::IntegerAttr>(a))
3952 return emitOpError("values in initializer must be integers");
3953 } else if (mlir::isa<mlir::DenseElementsAttr>(xl)) {
3954 // do nothing
3955 } else {
3956 return emitOpError("has unexpected attribute");
3957 }
3958 }
3959 return mlir::success();
3960 }
3961
3962 //===----------------------------------------------------------------------===//
3963 // UnboxProcOp
3964 //===----------------------------------------------------------------------===//
3965
3966 llvm::LogicalResult fir::UnboxProcOp::verify() {
3967 if (auto eleTy = fir::dyn_cast_ptrEleTy(getRefTuple().getType()))
3968 if (mlir::isa<mlir::TupleType>(eleTy))
3969 return mlir::success();
3970 return emitOpError("second output argument has bad type");
3971 }
3972
3973 //===----------------------------------------------------------------------===//
3974 // IfOp
3975 //===----------------------------------------------------------------------===//
3976
3977 void fir::IfOp::build(mlir::OpBuilder &builder, mlir::OperationState &result,
3978 mlir::Value cond, bool withElseRegion) {
3979 build(builder, result, std::nullopt, cond, withElseRegion);
3980 }
3981
3982 void fir::IfOp::build(mlir::OpBuilder &builder, mlir::OperationState &result,
3983 mlir::TypeRange resultTypes, mlir::Value cond,
3984 bool withElseRegion) {
3985 result.addOperands(cond);
3986 result.addTypes(resultTypes);
3987
3988 mlir::Region *thenRegion = result.addRegion();
3989 thenRegion->push_back(new mlir::Block());
3990 if (resultTypes.empty())
3991 IfOp::ensureTerminator(*thenRegion, builder, result.location);
3992
3993 mlir::Region *elseRegion = result.addRegion();
3994 if (withElseRegion) {
3995 elseRegion->push_back(new mlir::Block());
3996 if (resultTypes.empty())
3997 IfOp::ensureTerminator(*elseRegion, builder, result.location);
3998 }
3999 }
4000
4001 // These 3 functions copied from scf.if implementation.
4002
4003 /// Given the region at `index`, or the parent operation if `index` is None,
4004 /// return the successor regions. These are the regions that may be selected
4005 /// during the flow of control.
4006 void fir::IfOp::getSuccessorRegions(
4007 mlir::RegionBranchPoint point,
4008 llvm::SmallVectorImpl<mlir::RegionSuccessor> &regions) {
4009 // The `then` and the `else` region branch back to the parent operation.
4010 if (!point.isParent()) {
4011 regions.push_back(mlir::RegionSuccessor(getResults()));
4012 return;
4013 }
4014
4015 // Don't consider the else region if it is empty.
4016 regions.push_back(mlir::RegionSuccessor(&getThenRegion()));
4017
4018 // Don't consider the else region if it is empty.
4019 mlir::Region *elseRegion = &this->getElseRegion();
4020 if (elseRegion->empty())
4021 regions.push_back(mlir::RegionSuccessor());
4022 else
4023 regions.push_back(mlir::RegionSuccessor(elseRegion));
4024 }
4025
4026 void fir::IfOp::getEntrySuccessorRegions(
4027 llvm::ArrayRef<mlir::Attribute> operands,
4028 llvm::SmallVectorImpl<mlir::RegionSuccessor> &regions) {
4029 FoldAdaptor adaptor(operands);
4030 auto boolAttr =
4031 mlir::dyn_cast_or_null<mlir::BoolAttr>(adaptor.getCondition());
4032 if (!boolAttr || boolAttr.getValue())
4033 regions.emplace_back(&getThenRegion());
4034
4035 // If the else region is empty, execution continues after the parent op.
4036 if (!boolAttr || !boolAttr.getValue()) {
4037 if (!getElseRegion().empty())
4038 regions.emplace_back(&getElseRegion());
4039 else
4040 regions.emplace_back(getResults());
4041 }
4042 }
4043
4044 void fir::IfOp::getRegionInvocationBounds(
4045 llvm::ArrayRef<mlir::Attribute> operands,
4046 llvm::SmallVectorImpl<mlir::InvocationBounds> &invocationBounds) {
4047 if (auto cond = mlir::dyn_cast_or_null<mlir::BoolAttr>(operands[0])) {
4048 // If the condition is known, then one region is known to be executed once
4049 // and the other zero times.
4050 invocationBounds.emplace_back(0, cond.getValue() ? 1 : 0);
4051 invocationBounds.emplace_back(0, cond.getValue() ? 0 : 1);
4052 } else {
4053 // Non-constant condition. Each region may be executed 0 or 1 times.
4054 invocationBounds.assign(2, {0, 1});
4055 }
4056 }
4057
4058 mlir::ParseResult fir::IfOp::parse(mlir::OpAsmParser &parser,
4059 mlir::OperationState &result) {
4060 result.regions.reserve(2);
4061 mlir::Region *thenRegion = result.addRegion();
4062 mlir::Region *elseRegion = result.addRegion();
4063
4064 auto &builder = parser.getBuilder();
4065 mlir::OpAsmParser::UnresolvedOperand cond;
4066 mlir::Type i1Type = builder.getIntegerType(1);
4067 if (parser.parseOperand(cond) ||
4068 parser.resolveOperand(cond, i1Type, result.operands))
4069 return mlir::failure();
4070
4071 if (parser.parseOptionalArrowTypeList(result.types))
4072 return mlir::failure();
4073
4074 if (parser.parseRegion(*thenRegion, {}, {}))
4075 return mlir::failure();
4076 fir::IfOp::ensureTerminator(*thenRegion, parser.getBuilder(),
4077 result.location);
4078
4079 if (mlir::succeeded(parser.parseOptionalKeyword("else"))) {
4080 if (parser.parseRegion(*elseRegion, {}, {}))
4081 return mlir::failure();
4082 fir::IfOp::ensureTerminator(*elseRegion, parser.getBuilder(),
4083 result.location);
4084 }
4085
4086 // Parse the optional attribute list.
4087 if (parser.parseOptionalAttrDict(result.attributes))
4088 return mlir::failure();
4089 return mlir::success();
4090 }
4091
4092 llvm::LogicalResult fir::IfOp::verify() {
4093 if (getNumResults() != 0 && getElseRegion().empty())
4094 return emitOpError("must have an else block if defining values");
4095
4096 return mlir::success();
4097 }
4098
4099 void fir::IfOp::print(mlir::OpAsmPrinter &p) {
4100 bool printBlockTerminators = false;
4101 p << ' ' << getCondition();
4102 if (!getResults().empty()) {
4103 p << " -> (" << getResultTypes() << ')';
4104 printBlockTerminators = true;
4105 }
4106 p << ' ';
4107 p.printRegion(getThenRegion(), /*printEntryBlockArgs=*/false,
4108 printBlockTerminators);
4109
4110 // Print the 'else' regions if it exists and has a block.
4111 auto &otherReg = getElseRegion();
4112 if (!otherReg.empty()) {
4113 p << " else ";
4114 p.printRegion(otherReg, /*printEntryBlockArgs=*/false,
4115 printBlockTerminators);
4116 }
4117 p.printOptionalAttrDict((*this)->getAttrs());
4118 }
4119
4120 void fir::IfOp::resultToSourceOps(llvm::SmallVectorImpl<mlir::Value> &results,
4121 unsigned resultNum) {
4122 auto *term = getThenRegion().front().getTerminator();
4123 if (resultNum < term->getNumOperands())
4124 results.push_back(term->getOperand(resultNum));
4125 term = getElseRegion().front().getTerminator();
4126 if (resultNum < term->getNumOperands())
4127 results.push_back(term->getOperand(resultNum));
4128 }
4129
4130 //===----------------------------------------------------------------------===//
4131 // BoxOffsetOp
4132 //===----------------------------------------------------------------------===//
4133
4134 llvm::LogicalResult fir::BoxOffsetOp::verify() {
4135 auto boxType = mlir::dyn_cast_or_null<fir::BaseBoxType>(
4136 fir::dyn_cast_ptrEleTy(getBoxRef().getType()));
4137 if (!boxType)
4138 return emitOpError("box_ref operand must have !fir.ref<!fir.box<T>> type");
4139 if (getField() != fir::BoxFieldAttr::base_addr &&
4140 getField() != fir::BoxFieldAttr::derived_type)
4141 return emitOpError("cannot address provided field");
4142 if (getField() == fir::BoxFieldAttr::derived_type)
4143 if (!fir::boxHasAddendum(boxType))
4144 return emitOpError("can only address derived_type field of derived type "
4145 "or unlimited polymorphic fir.box");
4146 return mlir::success();
4147 }
4148
4149 void fir::BoxOffsetOp::build(mlir::OpBuilder &builder,
4150 mlir::OperationState &result, mlir::Value boxRef,
4151 fir::BoxFieldAttr field) {
4152 mlir::Type valueType =
4153 fir::unwrapPassByRefType(fir::unwrapRefType(boxRef.getType()));
4154 mlir::Type resultType = valueType;
4155 if (field == fir::BoxFieldAttr::base_addr)
4156 resultType = fir::LLVMPointerType::get(fir::ReferenceType::get(valueType));
4157 else if (field == fir::BoxFieldAttr::derived_type)
4158 resultType = fir::LLVMPointerType::get(
4159 fir::TypeDescType::get(fir::unwrapSequenceType(valueType)));
4160 build(builder, result, {resultType}, boxRef, field);
4161 }
4162
4163 //===----------------------------------------------------------------------===//
4164
4165 mlir::ParseResult fir::isValidCaseAttr(mlir::Attribute attr) {
4166 if (mlir::isa<mlir::UnitAttr, fir::ClosedIntervalAttr, fir::PointIntervalAttr,
4167 fir::LowerBoundAttr, fir::UpperBoundAttr>(attr))
4168 return mlir::success();
4169 return mlir::failure();
4170 }
4171
4172 unsigned fir::getCaseArgumentOffset(llvm::ArrayRef<mlir::Attribute> cases,
4173 unsigned dest) {
4174 unsigned o = 0;
4175 for (unsigned i = 0; i < dest; ++i) {
4176 auto &attr = cases[i];
4177 if (!mlir::dyn_cast_or_null<mlir::UnitAttr>(attr)) {
4178 ++o;
4179 if (mlir::dyn_cast_or_null<fir::ClosedIntervalAttr>(attr))
4180 ++o;
4181 }
4182 }
4183 return o;
4184 }
4185
4186 mlir::ParseResult
4187 fir::parseSelector(mlir::OpAsmParser &parser, mlir::OperationState &result,
4188 mlir::OpAsmParser::UnresolvedOperand &selector,
4189 mlir::Type &type) {
4190 if (parser.parseOperand(selector) || parser.parseColonType(type) ||
4191 parser.resolveOperand(selector, type, result.operands) ||
4192 parser.parseLSquare())
4193 return mlir::failure();
4194 return mlir::success();
4195 }
4196
4197 mlir::func::FuncOp fir::createFuncOp(mlir::Location loc, mlir::ModuleOp module,
4198 llvm::StringRef name,
4199 mlir::FunctionType type,
4200 llvm::ArrayRef<mlir::NamedAttribute> attrs,
4201 const mlir::SymbolTable *symbolTable) {
4202 if (symbolTable)
4203 if (auto f = symbolTable->lookup<mlir::func::FuncOp>(name)) {
4204 #ifdef EXPENSIVE_CHECKS
4205 assert(f == module.lookupSymbol<mlir::func::FuncOp>(name) &&
4206 "symbolTable and module out of sync");
4207 #endif
4208 return f;
4209 }
4210 if (auto f = module.lookupSymbol<mlir::func::FuncOp>(name))
4211 return f;
4212 mlir::OpBuilder modBuilder(module.getBodyRegion());
4213 modBuilder.setInsertionPointToEnd(module.getBody());
4214 auto result = modBuilder.create<mlir::func::FuncOp>(loc, name, type, attrs);
4215 result.setVisibility(mlir::SymbolTable::Visibility::Private);
4216 return result;
4217 }
4218
4219 fir::GlobalOp fir::createGlobalOp(mlir::Location loc, mlir::ModuleOp module,
4220 llvm::StringRef name, mlir::Type type,
4221 llvm::ArrayRef<mlir::NamedAttribute> attrs,
4222 const mlir::SymbolTable *symbolTable) {
4223 if (symbolTable)
4224 if (auto g = symbolTable->lookup<fir::GlobalOp>(name)) {
4225 #ifdef EXPENSIVE_CHECKS
4226 assert(g == module.lookupSymbol<fir::GlobalOp>(name) &&
4227 "symbolTable and module out of sync");
4228 #endif
4229 return g;
4230 }
4231 if (auto g = module.lookupSymbol<fir::GlobalOp>(name))
4232 return g;
4233 mlir::OpBuilder modBuilder(module.getBodyRegion());
4234 auto result = modBuilder.create<fir::GlobalOp>(loc, name, type, attrs);
4235 result.setVisibility(mlir::SymbolTable::Visibility::Private);
4236 return result;
4237 }
4238
4239 bool fir::hasHostAssociationArgument(mlir::func::FuncOp func) {
4240 if (auto allArgAttrs = func.getAllArgAttrs())
4241 for (auto attr : allArgAttrs)
4242 if (auto dict = mlir::dyn_cast_or_null<mlir::DictionaryAttr>(attr))
4243 if (dict.get(fir::getHostAssocAttrName()))
4244 return true;
4245 return false;
4246 }
4247
4248 // Test if value's definition has the specified set of
4249 // attributeNames. The value's definition is one of the operations
4250 // that are able to carry the Fortran variable attributes, e.g.
4251 // fir.alloca or fir.allocmem. Function arguments may also represent
4252 // value definitions and carry relevant attributes.
4253 //
4254 // If it is not possible to reach the limited set of definition
4255 // entities from the given value, then the function will return
4256 // std::nullopt. Otherwise, the definition is known and the return
4257 // value is computed as:
4258 // * if checkAny is true, then the function will return true
4259 // iff any of the attributeNames attributes is set on the definition.
4260 // * if checkAny is false, then the function will return true
4261 // iff all of the attributeNames attributes are set on the definition.
4262 static std::optional<bool>
4263 valueCheckFirAttributes(mlir::Value value,
4264 llvm::ArrayRef<llvm::StringRef> attributeNames,
4265 bool checkAny) {
4266 auto testAttributeSets = [&](llvm::ArrayRef<mlir::NamedAttribute> setAttrs,
4267 llvm::ArrayRef<llvm::StringRef> checkAttrs) {
4268 if (checkAny) {
4269 // Return true iff any of checkAttrs attributes is present
4270 // in setAttrs set.
4271 for (llvm::StringRef checkAttrName : checkAttrs)
4272 if (llvm::any_of(setAttrs, [&](mlir::NamedAttribute setAttr) {
4273 return setAttr.getName() == checkAttrName;
4274 }))
4275 return true;
4276
4277 return false;
4278 }
4279
4280 // Return true iff all attributes from checkAttrs are present
4281 // in setAttrs set.
4282 for (mlir::StringRef checkAttrName : checkAttrs)
4283 if (llvm::none_of(setAttrs, [&](mlir::NamedAttribute setAttr) {
4284 return setAttr.getName() == checkAttrName;
4285 }))
4286 return false;
4287
4288 return true;
4289 };
4290 // If this is a fir.box that was loaded, the fir attributes will be on the
4291 // related fir.ref<fir.box> creation.
4292 if (mlir::isa<fir::BoxType>(value.getType()))
4293 if (auto definingOp = value.getDefiningOp())
4294 if (auto loadOp = mlir::dyn_cast<fir::LoadOp>(definingOp))
4295 value = loadOp.getMemref();
4296 // If this is a function argument, look in the argument attributes.
4297 if (auto blockArg = mlir::dyn_cast<mlir::BlockArgument>(value)) {
4298 if (blockArg.getOwner() && blockArg.getOwner()->isEntryBlock())
4299 if (auto funcOp = mlir::dyn_cast<mlir::func::FuncOp>(
4300 blockArg.getOwner()->getParentOp()))
4301 return testAttributeSets(
4302 mlir::cast<mlir::FunctionOpInterface>(*funcOp).getArgAttrs(
4303 blockArg.getArgNumber()),
4304 attributeNames);
4305
4306 // If it is not a function argument, the attributes are unknown.
4307 return std::nullopt;
4308 }
4309
4310 if (auto definingOp = value.getDefiningOp()) {
4311 // If this is an allocated value, look at the allocation attributes.
4312 if (mlir::isa<fir::AllocMemOp>(definingOp) ||
4313 mlir::isa<fir::AllocaOp>(definingOp))
4314 return testAttributeSets(definingOp->getAttrs(), attributeNames);
4315 // If this is an imported global, look at AddrOfOp and GlobalOp attributes.
4316 // Both operations are looked at because use/host associated variable (the
4317 // AddrOfOp) can have ASYNCHRONOUS/VOLATILE attributes even if the ultimate
4318 // entity (the globalOp) does not have them.
4319 if (auto addressOfOp = mlir::dyn_cast<fir::AddrOfOp>(definingOp)) {
4320 if (testAttributeSets(addressOfOp->getAttrs(), attributeNames))
4321 return true;
4322 if (auto module = definingOp->getParentOfType<mlir::ModuleOp>())
4323 if (auto globalOp =
4324 module.lookupSymbol<fir::GlobalOp>(addressOfOp.getSymbol()))
4325 return testAttributeSets(globalOp->getAttrs(), attributeNames);
4326 }
4327 }
4328 // TODO: Construct associated entities attributes. Decide where the fir
4329 // attributes must be placed/looked for in this case.
4330 return std::nullopt;
4331 }
4332
4333 bool fir::valueMayHaveFirAttributes(
4334 mlir::Value value, llvm::ArrayRef<llvm::StringRef> attributeNames) {
4335 std::optional<bool> mayHaveAttr =
4336 valueCheckFirAttributes(value, attributeNames, /*checkAny=*/true);
4337 return mayHaveAttr.value_or(true);
4338 }
4339
4340 bool fir::valueHasFirAttribute(mlir::Value value,
4341 llvm::StringRef attributeName) {
4342 std::optional<bool> mayHaveAttr =
4343 valueCheckFirAttributes(value, {attributeName}, /*checkAny=*/false);
4344 return mayHaveAttr.value_or(false);
4345 }
4346
4347 bool fir::anyFuncArgsHaveAttr(mlir::func::FuncOp func, llvm::StringRef attr) {
4348 for (unsigned i = 0, end = func.getNumArguments(); i < end; ++i)
4349 if (func.getArgAttr(i, attr))
4350 return true;
4351 return false;
4352 }
4353
4354 std::optional<std::int64_t> fir::getIntIfConstant(mlir::Value value) {
4355 if (auto *definingOp = value.getDefiningOp()) {
4356 if (auto cst = mlir::dyn_cast<mlir::arith::ConstantOp>(definingOp))
4357 if (auto intAttr = mlir::dyn_cast<mlir::IntegerAttr>(cst.getValue()))
4358 return intAttr.getInt();
4359 if (auto llConstOp = mlir::dyn_cast<mlir::LLVM::ConstantOp>(definingOp))
4360 if (auto attr = mlir::dyn_cast<mlir::IntegerAttr>(llConstOp.getValue()))
4361 return attr.getValue().getSExtValue();
4362 }
4363 return {};
4364 }
4365
4366 bool fir::isDummyArgument(mlir::Value v) {
4367 auto blockArg{mlir::dyn_cast<mlir::BlockArgument>(v)};
4368 if (!blockArg) {
4369 auto defOp = v.getDefiningOp();
4370 if (defOp) {
4371 if (auto declareOp = mlir::dyn_cast<fir::DeclareOp>(defOp))
4372 if (declareOp.getDummyScope())
4373 return true;
4374 }
4375 return false;
4376 }
4377
4378 auto *owner{blockArg.getOwner()};
4379 return owner->isEntryBlock() &&
4380 mlir::isa<mlir::FunctionOpInterface>(owner->getParentOp());
4381 }
4382
4383 mlir::Type fir::applyPathToType(mlir::Type eleTy, mlir::ValueRange path) {
4384 for (auto i = path.begin(), end = path.end(); eleTy && i < end;) {
4385 eleTy = llvm::TypeSwitch<mlir::Type, mlir::Type>(eleTy)
4386 .Case<fir::RecordType>([&](fir::RecordType ty) {
4387 if (auto *op = (*i++).getDefiningOp()) {
4388 if (auto off = mlir::dyn_cast<fir::FieldIndexOp>(op))
4389 return ty.getType(off.getFieldName());
4390 if (auto off = mlir::dyn_cast<mlir::arith::ConstantOp>(op))
4391 return ty.getType(fir::toInt(off));
4392 }
4393 return mlir::Type{};
4394 })
4395 .Case<fir::SequenceType>([&](fir::SequenceType ty) {
4396 bool valid = true;
4397 const auto rank = ty.getDimension();
4398 for (std::remove_const_t<decltype(rank)> ii = 0;
4399 valid && ii < rank; ++ii)
4400 valid = i < end && fir::isa_integer((*i++).getType());
4401 return valid ? ty.getEleTy() : mlir::Type{};
4402 })
4403 .Case<mlir::TupleType>([&](mlir::TupleType ty) {
4404 if (auto *op = (*i++).getDefiningOp())
4405 if (auto off = mlir::dyn_cast<mlir::arith::ConstantOp>(op))
4406 return ty.getType(fir::toInt(off));
4407 return mlir::Type{};
4408 })
4409 .Case<fir::ComplexType>([&](fir::ComplexType ty) {
4410 auto x = *i;
4411 if (auto *op = (*i++).getDefiningOp())
4412 if (fir::isa_integer(x.getType()))
4413 return ty.getEleType(fir::getKindMapping(
4414 op->getParentOfType<mlir::ModuleOp>()));
4415 return mlir::Type{};
4416 })
4417 .Case<mlir::ComplexType>([&](mlir::ComplexType ty) {
4418 if (fir::isa_integer((*i++).getType()))
4419 return ty.getElementType();
4420 return mlir::Type{};
4421 })
4422 .Default([&](const auto &) { return mlir::Type{}; });
4423 }
4424 return eleTy;
4425 }
4426
4427 llvm::LogicalResult fir::DeclareOp::verify() {
4428 auto fortranVar =
4429 mlir::cast<fir::FortranVariableOpInterface>(this->getOperation());
4430 return fortranVar.verifyDeclareLikeOpImpl(getMemref());
4431 }
4432
4433 //===----------------------------------------------------------------------===//
4434 // FIROpsDialect
4435 //===----------------------------------------------------------------------===//
4436
4437 void fir::FIROpsDialect::registerOpExternalInterfaces() {
4438 // Attach default declare target interfaces to operations which can be marked
4439 // as declare target.
4440 fir::GlobalOp::attachInterface<
4441 mlir::omp::DeclareTargetDefaultModel<fir::GlobalOp>>(*getContext());
4442 }
4443
4444 // Tablegen operators
4445
4446 #define GET_OP_CLASSES
4447 #include "flang/Optimizer/Dialect/FIROps.cpp.inc"