1 //===-- FIROps.cpp --------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "flang/Optimizer/Dialect/FIROps.h"
14 #include "flang/Optimizer/Dialect/FIRAttr.h"
15 #include "flang/Optimizer/Dialect/FIROpsSupport.h"
16 #include "flang/Optimizer/Dialect/FIRType.h"
17 #include "mlir/Dialect/CommonFolders.h"
18 #include "mlir/Dialect/StandardOps/IR/Ops.h"
19 #include "mlir/IR/BuiltinOps.h"
20 #include "mlir/IR/Diagnostics.h"
21 #include "mlir/IR/Matchers.h"
22 #include "mlir/IR/PatternMatch.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/ADT/TypeSwitch.h"
25 
26 using namespace fir;
27 
28 /// Return true if a sequence type is of some incomplete size or a record type
29 /// is malformed or contains an incomplete sequence type. An incomplete sequence
30 /// type is one with more unknown extents in the type than have been provided
31 /// via `dynamicExtents`. Sequence types with an unknown rank are incomplete by
32 /// definition.
33 static bool verifyInType(mlir::Type inType,
34                          llvm::SmallVectorImpl<llvm::StringRef> &visited,
35                          unsigned dynamicExtents = 0) {
36   if (auto st = inType.dyn_cast<fir::SequenceType>()) {
37     auto shape = st.getShape();
38     if (shape.size() == 0)
39       return true;
40     for (std::size_t i = 0, end{shape.size()}; i < end; ++i) {
41       if (shape[i] != fir::SequenceType::getUnknownExtent())
42         continue;
43       if (dynamicExtents-- == 0)
44         return true;
45     }
46   } else if (auto rt = inType.dyn_cast<fir::RecordType>()) {
47     // don't recurse if we're already visiting this one
48     if (llvm::is_contained(visited, rt.getName()))
49       return false;
50     // keep track of record types currently being visited
51     visited.push_back(rt.getName());
52     for (auto &field : rt.getTypeList())
53       if (verifyInType(field.second, visited))
54         return true;
55     visited.pop_back();
56   } else if (auto rt = inType.dyn_cast<fir::PointerType>()) {
57     return verifyInType(rt.getEleTy(), visited);
58   }
59   return false;
60 }
61 
62 static bool verifyRecordLenParams(mlir::Type inType, unsigned numLenParams) {
63   if (numLenParams > 0) {
64     if (auto rt = inType.dyn_cast<fir::RecordType>())
65       return numLenParams != rt.getNumLenParams();
66     return true;
67   }
68   return false;
69 }
70 
71 //===----------------------------------------------------------------------===//
72 // AddfOp
73 //===----------------------------------------------------------------------===//
74 
75 mlir::OpFoldResult fir::AddfOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) {
76   return mlir::constFoldBinaryOp<FloatAttr>(
77       opnds, [](APFloat a, APFloat b) { return a + b; });
78 }
79 
80 //===----------------------------------------------------------------------===//
81 // AllocaOp
82 //===----------------------------------------------------------------------===//
83 
84 mlir::Type fir::AllocaOp::getAllocatedType() {
85   return getType().cast<ReferenceType>().getEleTy();
86 }
87 
88 /// Create a legal memory reference as return type
89 mlir::Type fir::AllocaOp::wrapResultType(mlir::Type intype) {
90   // FIR semantics: memory references to memory references are disallowed
91   if (intype.isa<ReferenceType>())
92     return {};
93   return ReferenceType::get(intype);
94 }
95 
96 mlir::Type fir::AllocaOp::getRefTy(mlir::Type ty) {
97   return ReferenceType::get(ty);
98 }
99 
100 //===----------------------------------------------------------------------===//
101 // AllocMemOp
102 //===----------------------------------------------------------------------===//
103 
104 mlir::Type fir::AllocMemOp::getAllocatedType() {
105   return getType().cast<HeapType>().getEleTy();
106 }
107 
108 mlir::Type fir::AllocMemOp::getRefTy(mlir::Type ty) {
109   return HeapType::get(ty);
110 }
111 
112 /// Create a legal heap reference as return type
113 mlir::Type fir::AllocMemOp::wrapResultType(mlir::Type intype) {
114   // Fortran semantics: C852 an entity cannot be both ALLOCATABLE and POINTER
115   // 8.5.3 note 1 prohibits ALLOCATABLE procedures as well
116   // FIR semantics: one may not allocate a memory reference value
117   if (intype.isa<ReferenceType>() || intype.isa<HeapType>() ||
118       intype.isa<PointerType>() || intype.isa<FunctionType>())
119     return {};
120   return HeapType::get(intype);
121 }
122 
123 //===----------------------------------------------------------------------===//
124 // ArrayCoorOp
125 //===----------------------------------------------------------------------===//
126 
127 static mlir::LogicalResult verify(fir::ArrayCoorOp op) {
128   auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(op.memref().getType());
129   auto arrTy = eleTy.dyn_cast<fir::SequenceType>();
130   if (!arrTy)
131     return op.emitOpError("must be a reference to an array");
132   auto arrDim = arrTy.getDimension();
133 
134   if (auto shapeOp = op.shape()) {
135     auto shapeTy = shapeOp.getType();
136     unsigned shapeTyRank = 0;
137     if (auto s = shapeTy.dyn_cast<fir::ShapeType>()) {
138       shapeTyRank = s.getRank();
139     } else if (auto ss = shapeTy.dyn_cast<fir::ShapeShiftType>()) {
140       shapeTyRank = ss.getRank();
141     } else {
142       auto s = shapeTy.cast<fir::ShiftType>();
143       shapeTyRank = s.getRank();
144       if (!op.memref().getType().isa<fir::BoxType>())
145         return op.emitOpError("shift can only be provided with fir.box memref");
146     }
147     if (arrDim && arrDim != shapeTyRank)
148       return op.emitOpError("rank of dimension mismatched");
149     if (shapeTyRank != op.indices().size())
150       return op.emitOpError("number of indices do not match dim rank");
151   }
152 
153   if (auto sliceOp = op.slice())
154     if (auto sliceTy = sliceOp.getType().dyn_cast<fir::SliceType>())
155       if (sliceTy.getRank() != arrDim)
156         return op.emitOpError("rank of dimension in slice mismatched");
157 
158   return mlir::success();
159 }
160 
161 //===----------------------------------------------------------------------===//
162 // ArrayLoadOp
163 //===----------------------------------------------------------------------===//
164 
165 std::vector<mlir::Value> fir::ArrayLoadOp::getExtents() {
166   if (auto sh = shape())
167     if (auto *op = sh.getDefiningOp()) {
168       if (auto shOp = dyn_cast<fir::ShapeOp>(op))
169         return shOp.getExtents();
170       return cast<fir::ShapeShiftOp>(op).getExtents();
171     }
172   return {};
173 }
174 
175 static mlir::LogicalResult verify(fir::ArrayLoadOp op) {
176   auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(op.memref().getType());
177   auto arrTy = eleTy.dyn_cast<fir::SequenceType>();
178   if (!arrTy)
179     return op.emitOpError("must be a reference to an array");
180   auto arrDim = arrTy.getDimension();
181 
182   if (auto shapeOp = op.shape()) {
183     auto shapeTy = shapeOp.getType();
184     unsigned shapeTyRank = 0;
185     if (auto s = shapeTy.dyn_cast<fir::ShapeType>()) {
186       shapeTyRank = s.getRank();
187     } else if (auto ss = shapeTy.dyn_cast<fir::ShapeShiftType>()) {
188       shapeTyRank = ss.getRank();
189     } else {
190       auto s = shapeTy.cast<fir::ShiftType>();
191       shapeTyRank = s.getRank();
192       if (!op.memref().getType().isa<fir::BoxType>())
193         return op.emitOpError("shift can only be provided with fir.box memref");
194     }
195     if (arrDim && arrDim != shapeTyRank)
196       return op.emitOpError("rank of dimension mismatched");
197   }
198 
199   if (auto sliceOp = op.slice())
200     if (auto sliceTy = sliceOp.getType().dyn_cast<fir::SliceType>())
201       if (sliceTy.getRank() != arrDim)
202         return op.emitOpError("rank of dimension in slice mismatched");
203 
204   return mlir::success();
205 }
206 
207 //===----------------------------------------------------------------------===//
208 // BoxAddrOp
209 //===----------------------------------------------------------------------===//
210 
211 mlir::OpFoldResult fir::BoxAddrOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) {
212   if (auto v = val().getDefiningOp()) {
213     if (auto box = dyn_cast<fir::EmboxOp>(v))
214       return box.memref();
215     if (auto box = dyn_cast<fir::EmboxCharOp>(v))
216       return box.memref();
217   }
218   return {};
219 }
220 
221 //===----------------------------------------------------------------------===//
222 // BoxCharLenOp
223 //===----------------------------------------------------------------------===//
224 
225 mlir::OpFoldResult
226 fir::BoxCharLenOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) {
227   if (auto v = val().getDefiningOp()) {
228     if (auto box = dyn_cast<fir::EmboxCharOp>(v))
229       return box.len();
230   }
231   return {};
232 }
233 
234 //===----------------------------------------------------------------------===//
235 // BoxDimsOp
236 //===----------------------------------------------------------------------===//
237 
238 /// Get the result types packed in a tuple tuple
239 mlir::Type fir::BoxDimsOp::getTupleType() {
240   // note: triple, but 4 is nearest power of 2
241   llvm::SmallVector<mlir::Type, 4> triple{
242       getResult(0).getType(), getResult(1).getType(), getResult(2).getType()};
243   return mlir::TupleType::get(getContext(), triple);
244 }
245 
246 //===----------------------------------------------------------------------===//
247 // CallOp
248 //===----------------------------------------------------------------------===//
249 
250 mlir::FunctionType fir::CallOp::getFunctionType() {
251   return mlir::FunctionType::get(getContext(), getOperandTypes(),
252                                  getResultTypes());
253 }
254 
255 static void printCallOp(mlir::OpAsmPrinter &p, fir::CallOp &op) {
256   auto callee = op.callee();
257   bool isDirect = callee.hasValue();
258   p << op.getOperationName() << ' ';
259   if (isDirect)
260     p << callee.getValue();
261   else
262     p << op.getOperand(0);
263   p << '(' << op->getOperands().drop_front(isDirect ? 0 : 1) << ')';
264   p.printOptionalAttrDict(op->getAttrs(), {fir::CallOp::calleeAttrName()});
265   auto resultTypes{op.getResultTypes()};
266   llvm::SmallVector<Type, 8> argTypes(
267       llvm::drop_begin(op.getOperandTypes(), isDirect ? 0 : 1));
268   p << " : " << FunctionType::get(op.getContext(), argTypes, resultTypes);
269 }
270 
271 static mlir::ParseResult parseCallOp(mlir::OpAsmParser &parser,
272                                      mlir::OperationState &result) {
273   llvm::SmallVector<mlir::OpAsmParser::OperandType, 8> operands;
274   if (parser.parseOperandList(operands))
275     return mlir::failure();
276 
277   mlir::NamedAttrList attrs;
278   mlir::SymbolRefAttr funcAttr;
279   bool isDirect = operands.empty();
280   if (isDirect)
281     if (parser.parseAttribute(funcAttr, fir::CallOp::calleeAttrName(), attrs))
282       return mlir::failure();
283 
284   Type type;
285   if (parser.parseOperandList(operands, mlir::OpAsmParser::Delimiter::Paren) ||
286       parser.parseOptionalAttrDict(attrs) || parser.parseColon() ||
287       parser.parseType(type))
288     return mlir::failure();
289 
290   auto funcType = type.dyn_cast<mlir::FunctionType>();
291   if (!funcType)
292     return parser.emitError(parser.getNameLoc(), "expected function type");
293   if (isDirect) {
294     if (parser.resolveOperands(operands, funcType.getInputs(),
295                                parser.getNameLoc(), result.operands))
296       return mlir::failure();
297   } else {
298     auto funcArgs =
299         llvm::ArrayRef<mlir::OpAsmParser::OperandType>(operands).drop_front();
300     if (parser.resolveOperand(operands[0], funcType, result.operands) ||
301         parser.resolveOperands(funcArgs, funcType.getInputs(),
302                                parser.getNameLoc(), result.operands))
303       return mlir::failure();
304   }
305   result.addTypes(funcType.getResults());
306   result.attributes = attrs;
307   return mlir::success();
308 }
309 
310 //===----------------------------------------------------------------------===//
311 // CmpfOp
312 //===----------------------------------------------------------------------===//
313 
314 // Note: getCmpFPredicateNames() is inline static in StandardOps/IR/Ops.cpp
315 mlir::CmpFPredicate fir::CmpfOp::getPredicateByName(llvm::StringRef name) {
316   auto pred = mlir::symbolizeCmpFPredicate(name);
317   assert(pred.hasValue() && "invalid predicate name");
318   return pred.getValue();
319 }
320 
321 void fir::buildCmpFOp(OpBuilder &builder, OperationState &result,
322                       CmpFPredicate predicate, Value lhs, Value rhs) {
323   result.addOperands({lhs, rhs});
324   result.types.push_back(builder.getI1Type());
325   result.addAttribute(
326       CmpfOp::getPredicateAttrName(),
327       builder.getI64IntegerAttr(static_cast<int64_t>(predicate)));
328 }
329 
330 template <typename OPTY>
331 static void printCmpOp(OpAsmPrinter &p, OPTY op) {
332   p << op.getOperationName() << ' ';
333   auto predSym = mlir::symbolizeCmpFPredicate(
334       op->template getAttrOfType<mlir::IntegerAttr>(
335             OPTY::getPredicateAttrName())
336           .getInt());
337   assert(predSym.hasValue() && "invalid symbol value for predicate");
338   p << '"' << mlir::stringifyCmpFPredicate(predSym.getValue()) << '"' << ", ";
339   p.printOperand(op.lhs());
340   p << ", ";
341   p.printOperand(op.rhs());
342   p.printOptionalAttrDict(op->getAttrs(),
343                           /*elidedAttrs=*/{OPTY::getPredicateAttrName()});
344   p << " : " << op.lhs().getType();
345 }
346 
347 static void printCmpfOp(OpAsmPrinter &p, CmpfOp op) { printCmpOp(p, op); }
348 
349 template <typename OPTY>
350 static mlir::ParseResult parseCmpOp(mlir::OpAsmParser &parser,
351                                     mlir::OperationState &result) {
352   llvm::SmallVector<mlir::OpAsmParser::OperandType, 2> ops;
353   mlir::NamedAttrList attrs;
354   mlir::Attribute predicateNameAttr;
355   mlir::Type type;
356   if (parser.parseAttribute(predicateNameAttr, OPTY::getPredicateAttrName(),
357                             attrs) ||
358       parser.parseComma() || parser.parseOperandList(ops, 2) ||
359       parser.parseOptionalAttrDict(attrs) || parser.parseColonType(type) ||
360       parser.resolveOperands(ops, type, result.operands))
361     return failure();
362 
363   if (!predicateNameAttr.isa<mlir::StringAttr>())
364     return parser.emitError(parser.getNameLoc(),
365                             "expected string comparison predicate attribute");
366 
367   // Rewrite string attribute to an enum value.
368   llvm::StringRef predicateName =
369       predicateNameAttr.cast<mlir::StringAttr>().getValue();
370   auto predicate = fir::CmpfOp::getPredicateByName(predicateName);
371   auto builder = parser.getBuilder();
372   mlir::Type i1Type = builder.getI1Type();
373   attrs.set(OPTY::getPredicateAttrName(),
374             builder.getI64IntegerAttr(static_cast<int64_t>(predicate)));
375   result.attributes = attrs;
376   result.addTypes({i1Type});
377   return success();
378 }
379 
380 mlir::ParseResult fir::parseCmpfOp(mlir::OpAsmParser &parser,
381                                    mlir::OperationState &result) {
382   return parseCmpOp<fir::CmpfOp>(parser, result);
383 }
384 
385 //===----------------------------------------------------------------------===//
386 // CmpcOp
387 //===----------------------------------------------------------------------===//
388 
389 void fir::buildCmpCOp(OpBuilder &builder, OperationState &result,
390                       CmpFPredicate predicate, Value lhs, Value rhs) {
391   result.addOperands({lhs, rhs});
392   result.types.push_back(builder.getI1Type());
393   result.addAttribute(
394       fir::CmpcOp::getPredicateAttrName(),
395       builder.getI64IntegerAttr(static_cast<int64_t>(predicate)));
396 }
397 
398 static void printCmpcOp(OpAsmPrinter &p, fir::CmpcOp op) { printCmpOp(p, op); }
399 
400 mlir::ParseResult fir::parseCmpcOp(mlir::OpAsmParser &parser,
401                                    mlir::OperationState &result) {
402   return parseCmpOp<fir::CmpcOp>(parser, result);
403 }
404 
405 //===----------------------------------------------------------------------===//
406 // ConvertOp
407 //===----------------------------------------------------------------------===//
408 
409 void fir::ConvertOp::getCanonicalizationPatterns(
410     OwningRewritePatternList &results, MLIRContext *context) {
411 }
412 
413 mlir::OpFoldResult fir::ConvertOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) {
414   if (value().getType() == getType())
415     return value();
416   if (matchPattern(value(), m_Op<fir::ConvertOp>())) {
417     auto inner = cast<fir::ConvertOp>(value().getDefiningOp());
418     // (convert (convert 'a : logical -> i1) : i1 -> logical) ==> forward 'a
419     if (auto toTy = getType().dyn_cast<fir::LogicalType>())
420       if (auto fromTy = inner.value().getType().dyn_cast<fir::LogicalType>())
421         if (inner.getType().isa<mlir::IntegerType>() && (toTy == fromTy))
422           return inner.value();
423     // (convert (convert 'a : i1 -> logical) : logical -> i1) ==> forward 'a
424     if (auto toTy = getType().dyn_cast<mlir::IntegerType>())
425       if (auto fromTy = inner.value().getType().dyn_cast<mlir::IntegerType>())
426         if (inner.getType().isa<fir::LogicalType>() && (toTy == fromTy) &&
427             (fromTy.getWidth() == 1))
428           return inner.value();
429   }
430   return {};
431 }
432 
433 bool fir::ConvertOp::isIntegerCompatible(mlir::Type ty) {
434   return ty.isa<mlir::IntegerType>() || ty.isa<mlir::IndexType>() ||
435          ty.isa<fir::IntegerType>() || ty.isa<fir::LogicalType>();
436 }
437 
438 bool fir::ConvertOp::isFloatCompatible(mlir::Type ty) {
439   return ty.isa<mlir::FloatType>() || ty.isa<fir::RealType>();
440 }
441 
442 bool fir::ConvertOp::isPointerCompatible(mlir::Type ty) {
443   return ty.isa<fir::ReferenceType>() || ty.isa<fir::PointerType>() ||
444          ty.isa<fir::HeapType>() || ty.isa<mlir::MemRefType>() ||
445          ty.isa<mlir::FunctionType>() || ty.isa<fir::TypeDescType>();
446 }
447 
448 //===----------------------------------------------------------------------===//
449 // CoordinateOp
450 //===----------------------------------------------------------------------===//
451 
452 static void print(mlir::OpAsmPrinter &p, fir::CoordinateOp op) {
453   p << op.getOperationName() << ' ' << op.ref() << ", " << op.coor();
454   p.printOptionalAttrDict(op->getAttrs(), /*elideAttrs=*/{"baseType"});
455   p << " : ";
456   p.printFunctionalType(op.getOperandTypes(), op->getResultTypes());
457 }
458 
459 static mlir::ParseResult parseCoordinateCustom(mlir::OpAsmParser &parser,
460                                                mlir::OperationState &result) {
461   mlir::OpAsmParser::OperandType memref;
462   if (parser.parseOperand(memref) || parser.parseComma())
463     return mlir::failure();
464   llvm::SmallVector<mlir::OpAsmParser::OperandType, 8> coorOperands;
465   if (parser.parseOperandList(coorOperands))
466     return mlir::failure();
467   llvm::SmallVector<mlir::OpAsmParser::OperandType, 16> allOperands;
468   allOperands.push_back(memref);
469   allOperands.append(coorOperands.begin(), coorOperands.end());
470   mlir::FunctionType funcTy;
471   auto loc = parser.getCurrentLocation();
472   if (parser.parseOptionalAttrDict(result.attributes) ||
473       parser.parseColonType(funcTy) ||
474       parser.resolveOperands(allOperands, funcTy.getInputs(), loc,
475                              result.operands))
476     return failure();
477   parser.addTypesToList(funcTy.getResults(), result.types);
478   result.addAttribute("baseType", mlir::TypeAttr::get(funcTy.getInput(0)));
479   return mlir::success();
480 }
481 
482 static mlir::LogicalResult verify(fir::CoordinateOp op) {
483   auto refTy = op.ref().getType();
484   if (fir::isa_ref_type(refTy)) {
485     auto eleTy = fir::dyn_cast_ptrEleTy(refTy);
486     if (auto arrTy = eleTy.dyn_cast<fir::SequenceType>()) {
487       if (arrTy.hasUnknownShape())
488         return op.emitOpError("cannot find coordinate in unknown shape");
489       if (arrTy.getConstantRows() < arrTy.getDimension() - 1)
490         return op.emitOpError("cannot find coordinate with unknown extents");
491     }
492     if (!(fir::isa_aggregate(eleTy) || fir::isa_complex(eleTy) ||
493           fir::isa_char_string(eleTy)))
494       return op.emitOpError("cannot apply coordinate_of to this type");
495   }
496   // Recovering a LEN type parameter only makes sense from a boxed value. For a
497   // bare reference, the LEN type parameters must be passed as additional
498   // arguments to `op`.
499   for (auto co : op.coor())
500     if (dyn_cast_or_null<fir::LenParamIndexOp>(co.getDefiningOp())) {
501       if (op.getNumOperands() != 2)
502         return op.emitOpError("len_param_index must be last argument");
503       if (!op.ref().getType().isa<BoxType>())
504         return op.emitOpError("len_param_index must be used on box type");
505     }
506   return mlir::success();
507 }
508 
509 //===----------------------------------------------------------------------===//
510 // DispatchOp
511 //===----------------------------------------------------------------------===//
512 
513 mlir::FunctionType fir::DispatchOp::getFunctionType() {
514   return mlir::FunctionType::get(getContext(), getOperandTypes(),
515                                  getResultTypes());
516 }
517 
518 //===----------------------------------------------------------------------===//
519 // DispatchTableOp
520 //===----------------------------------------------------------------------===//
521 
522 void fir::DispatchTableOp::appendTableEntry(mlir::Operation *op) {
523   assert(mlir::isa<fir::DTEntryOp>(*op) && "operation must be a DTEntryOp");
524   auto &block = getBlock();
525   block.getOperations().insert(block.end(), op);
526 }
527 
528 //===----------------------------------------------------------------------===//
529 // EmboxOp
530 //===----------------------------------------------------------------------===//
531 
532 static mlir::LogicalResult verify(fir::EmboxOp op) {
533   auto eleTy = fir::dyn_cast_ptrEleTy(op.memref().getType());
534   if (!eleTy)
535     return op.emitOpError("must embox a memory reference type");
536   bool isArray = false;
537   if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>()) {
538     eleTy = seqTy.getEleTy();
539     isArray = true;
540   }
541   if (op.hasLenParams()) {
542     auto lenPs = op.numLenParams();
543     if (auto rt = eleTy.dyn_cast<fir::RecordType>()) {
544       if (lenPs != rt.getNumLenParams())
545         return op.emitOpError("number of LEN params does not correspond"
546                               " to the !fir.type type");
547     } else if (auto strTy = eleTy.dyn_cast<fir::CharacterType>()) {
548       if (strTy.getLen() != fir::CharacterType::unknownLen())
549         return op.emitOpError("CHARACTER already has static LEN");
550     } else {
551       return op.emitOpError("LEN parameters require CHARACTER or derived type");
552     }
553     for (auto lp : op.lenParams())
554       if (!fir::isa_integer(lp.getType()))
555         return op.emitOpError("LEN parameters must be integral type");
556   }
557   if (op.getShape()) {
558     auto shapeTy = op.getShape().getType();
559     if (!(shapeTy.isa<fir::ShapeType>() || shapeTy.isa<ShapeShiftType>()))
560       return op.emitOpError("must be shape or shapeshift type");
561     if (!isArray)
562       return op.emitOpError("shape must not be provided for a scalar");
563   }
564   if (op.getSlice()) {
565     auto sliceTy = op.getSlice().getType();
566     if (!sliceTy.isa<fir::SliceType>())
567       return op.emitOpError("must be a slice type");
568     if (!isArray)
569       return op.emitOpError("slice must not be provided for a scalar");
570   }
571   return mlir::success();
572 }
573 
574 //===----------------------------------------------------------------------===//
575 // GenTypeDescOp
576 //===----------------------------------------------------------------------===//
577 
578 void fir::GenTypeDescOp::build(OpBuilder &, OperationState &result,
579                                mlir::TypeAttr inty) {
580   result.addAttribute("in_type", inty);
581   result.addTypes(TypeDescType::get(inty.getValue()));
582 }
583 
584 //===----------------------------------------------------------------------===//
585 // GlobalOp
586 //===----------------------------------------------------------------------===//
587 
588 static ParseResult parseGlobalOp(OpAsmParser &parser, OperationState &result) {
589   // Parse the optional linkage
590   llvm::StringRef linkage;
591   auto &builder = parser.getBuilder();
592   if (mlir::succeeded(parser.parseOptionalKeyword(&linkage))) {
593     if (fir::GlobalOp::verifyValidLinkage(linkage))
594       return mlir::failure();
595     mlir::StringAttr linkAttr = builder.getStringAttr(linkage);
596     result.addAttribute(fir::GlobalOp::linkageAttrName(), linkAttr);
597   }
598 
599   // Parse the name as a symbol reference attribute.
600   mlir::SymbolRefAttr nameAttr;
601   if (parser.parseAttribute(nameAttr, fir::GlobalOp::symbolAttrName(),
602                             result.attributes))
603     return mlir::failure();
604   result.addAttribute(mlir::SymbolTable::getSymbolAttrName(),
605                       builder.getStringAttr(nameAttr.getRootReference()));
606 
607   bool simpleInitializer = false;
608   if (mlir::succeeded(parser.parseOptionalLParen())) {
609     Attribute attr;
610     if (parser.parseAttribute(attr, fir::GlobalOp::initValAttrName(),
611                               result.attributes) ||
612         parser.parseRParen())
613       return mlir::failure();
614     simpleInitializer = true;
615   }
616 
617   if (succeeded(parser.parseOptionalKeyword("constant"))) {
618     // if "constant" keyword then mark this as a constant, not a variable
619     result.addAttribute(fir::GlobalOp::constantAttrName(),
620                         builder.getUnitAttr());
621   }
622 
623   mlir::Type globalType;
624   if (parser.parseColonType(globalType))
625     return mlir::failure();
626 
627   result.addAttribute(fir::GlobalOp::typeAttrName(),
628                       mlir::TypeAttr::get(globalType));
629 
630   if (simpleInitializer) {
631     result.addRegion();
632   } else {
633     // Parse the optional initializer body.
634     auto parseResult = parser.parseOptionalRegion(
635         *result.addRegion(), /*arguments=*/llvm::None, /*argTypes=*/llvm::None);
636     if (parseResult.hasValue() && mlir::failed(*parseResult))
637       return mlir::failure();
638   }
639 
640   return mlir::success();
641 }
642 
643 void fir::GlobalOp::appendInitialValue(mlir::Operation *op) {
644   getBlock().getOperations().push_back(op);
645 }
646 
647 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
648                           StringRef name, bool isConstant, Type type,
649                           Attribute initialVal, StringAttr linkage,
650                           ArrayRef<NamedAttribute> attrs) {
651   result.addRegion();
652   result.addAttribute(typeAttrName(), mlir::TypeAttr::get(type));
653   result.addAttribute(mlir::SymbolTable::getSymbolAttrName(),
654                       builder.getStringAttr(name));
655   result.addAttribute(symbolAttrName(), builder.getSymbolRefAttr(name));
656   if (isConstant)
657     result.addAttribute(constantAttrName(), builder.getUnitAttr());
658   if (initialVal)
659     result.addAttribute(initValAttrName(), initialVal);
660   if (linkage)
661     result.addAttribute(linkageAttrName(), linkage);
662   result.attributes.append(attrs.begin(), attrs.end());
663 }
664 
665 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
666                           StringRef name, Type type, Attribute initialVal,
667                           StringAttr linkage, ArrayRef<NamedAttribute> attrs) {
668   build(builder, result, name, /*isConstant=*/false, type, {}, linkage, attrs);
669 }
670 
671 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
672                           StringRef name, bool isConstant, Type type,
673                           StringAttr linkage, ArrayRef<NamedAttribute> attrs) {
674   build(builder, result, name, isConstant, type, {}, linkage, attrs);
675 }
676 
677 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
678                           StringRef name, Type type, StringAttr linkage,
679                           ArrayRef<NamedAttribute> attrs) {
680   build(builder, result, name, /*isConstant=*/false, type, {}, linkage, attrs);
681 }
682 
683 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
684                           StringRef name, bool isConstant, Type type,
685                           ArrayRef<NamedAttribute> attrs) {
686   build(builder, result, name, isConstant, type, StringAttr{}, attrs);
687 }
688 
689 void fir::GlobalOp::build(mlir::OpBuilder &builder, OperationState &result,
690                           StringRef name, Type type,
691                           ArrayRef<NamedAttribute> attrs) {
692   build(builder, result, name, /*isConstant=*/false, type, attrs);
693 }
694 
695 mlir::ParseResult fir::GlobalOp::verifyValidLinkage(StringRef linkage) {
696   // Supporting only a subset of the LLVM linkage types for now
697   static const char *validNames[] = {"common", "internal", "linkonce", "weak"};
698   return mlir::success(llvm::is_contained(validNames, linkage));
699 }
700 
701 //===----------------------------------------------------------------------===//
702 // InsertValueOp
703 //===----------------------------------------------------------------------===//
704 
705 static bool checkIsIntegerConstant(mlir::Value v, int64_t conVal) {
706   if (auto c = dyn_cast_or_null<mlir::ConstantOp>(v.getDefiningOp())) {
707     auto attr = c.getValue();
708     if (auto iattr = attr.dyn_cast<mlir::IntegerAttr>())
709       return iattr.getInt() == conVal;
710   }
711   return false;
712 }
713 static bool isZero(mlir::Value v) { return checkIsIntegerConstant(v, 0); }
714 static bool isOne(mlir::Value v) { return checkIsIntegerConstant(v, 1); }
715 
716 // Undo some complex patterns created in the front-end and turn them back into
717 // complex ops.
718 template <typename FltOp, typename CpxOp>
719 struct UndoComplexPattern : public mlir::RewritePattern {
720   UndoComplexPattern(mlir::MLIRContext *ctx)
721       : mlir::RewritePattern("fir.insert_value", {}, 2, ctx) {}
722 
723   mlir::LogicalResult
724   matchAndRewrite(mlir::Operation *op,
725                   mlir::PatternRewriter &rewriter) const override {
726     auto insval = dyn_cast_or_null<fir::InsertValueOp>(op);
727     if (!insval || !insval.getType().isa<fir::ComplexType>())
728       return mlir::failure();
729     auto insval2 =
730         dyn_cast_or_null<fir::InsertValueOp>(insval.adt().getDefiningOp());
731     if (!insval2 || !isa<fir::UndefOp>(insval2.adt().getDefiningOp()))
732       return mlir::failure();
733     auto binf = dyn_cast_or_null<FltOp>(insval.val().getDefiningOp());
734     auto binf2 = dyn_cast_or_null<FltOp>(insval2.val().getDefiningOp());
735     if (!binf || !binf2 || insval.coor().size() != 1 ||
736         !isOne(insval.coor()[0]) || insval2.coor().size() != 1 ||
737         !isZero(insval2.coor()[0]))
738       return mlir::failure();
739     auto eai =
740         dyn_cast_or_null<fir::ExtractValueOp>(binf.lhs().getDefiningOp());
741     auto ebi =
742         dyn_cast_or_null<fir::ExtractValueOp>(binf.rhs().getDefiningOp());
743     auto ear =
744         dyn_cast_or_null<fir::ExtractValueOp>(binf2.lhs().getDefiningOp());
745     auto ebr =
746         dyn_cast_or_null<fir::ExtractValueOp>(binf2.rhs().getDefiningOp());
747     if (!eai || !ebi || !ear || !ebr || ear.adt() != eai.adt() ||
748         ebr.adt() != ebi.adt() || eai.coor().size() != 1 ||
749         !isOne(eai.coor()[0]) || ebi.coor().size() != 1 ||
750         !isOne(ebi.coor()[0]) || ear.coor().size() != 1 ||
751         !isZero(ear.coor()[0]) || ebr.coor().size() != 1 ||
752         !isZero(ebr.coor()[0]))
753       return mlir::failure();
754     rewriter.replaceOpWithNewOp<CpxOp>(op, ear.adt(), ebr.adt());
755     return mlir::success();
756   }
757 };
758 
759 void fir::InsertValueOp::getCanonicalizationPatterns(
760     mlir::OwningRewritePatternList &results, mlir::MLIRContext *context) {
761   results.insert<UndoComplexPattern<fir::AddfOp, fir::AddcOp>,
762                  UndoComplexPattern<fir::SubfOp, fir::SubcOp>>(context);
763 }
764 
765 //===----------------------------------------------------------------------===//
766 // IterWhileOp
767 //===----------------------------------------------------------------------===//
768 
769 void fir::IterWhileOp::build(mlir::OpBuilder &builder,
770                              mlir::OperationState &result, mlir::Value lb,
771                              mlir::Value ub, mlir::Value step,
772                              mlir::Value iterate, bool finalCountValue,
773                              mlir::ValueRange iterArgs,
774                              llvm::ArrayRef<mlir::NamedAttribute> attributes) {
775   result.addOperands({lb, ub, step, iterate});
776   if (finalCountValue) {
777     result.addTypes(builder.getIndexType());
778     result.addAttribute(finalValueAttrName(), builder.getUnitAttr());
779   }
780   result.addTypes(iterate.getType());
781   result.addOperands(iterArgs);
782   for (auto v : iterArgs)
783     result.addTypes(v.getType());
784   mlir::Region *bodyRegion = result.addRegion();
785   bodyRegion->push_back(new Block{});
786   bodyRegion->front().addArgument(builder.getIndexType());
787   bodyRegion->front().addArgument(iterate.getType());
788   bodyRegion->front().addArguments(iterArgs.getTypes());
789   result.addAttributes(attributes);
790 }
791 
792 static mlir::ParseResult parseIterWhileOp(mlir::OpAsmParser &parser,
793                                           mlir::OperationState &result) {
794   auto &builder = parser.getBuilder();
795   mlir::OpAsmParser::OperandType inductionVariable, lb, ub, step;
796   if (parser.parseLParen() || parser.parseRegionArgument(inductionVariable) ||
797       parser.parseEqual())
798     return mlir::failure();
799 
800   // Parse loop bounds.
801   auto indexType = builder.getIndexType();
802   auto i1Type = builder.getIntegerType(1);
803   if (parser.parseOperand(lb) ||
804       parser.resolveOperand(lb, indexType, result.operands) ||
805       parser.parseKeyword("to") || parser.parseOperand(ub) ||
806       parser.resolveOperand(ub, indexType, result.operands) ||
807       parser.parseKeyword("step") || parser.parseOperand(step) ||
808       parser.parseRParen() ||
809       parser.resolveOperand(step, indexType, result.operands))
810     return mlir::failure();
811 
812   mlir::OpAsmParser::OperandType iterateVar, iterateInput;
813   if (parser.parseKeyword("and") || parser.parseLParen() ||
814       parser.parseRegionArgument(iterateVar) || parser.parseEqual() ||
815       parser.parseOperand(iterateInput) || parser.parseRParen() ||
816       parser.resolveOperand(iterateInput, i1Type, result.operands))
817     return mlir::failure();
818 
819   // Parse the initial iteration arguments.
820   llvm::SmallVector<mlir::OpAsmParser::OperandType, 4> regionArgs;
821   auto prependCount = false;
822 
823   // Induction variable.
824   regionArgs.push_back(inductionVariable);
825   regionArgs.push_back(iterateVar);
826 
827   if (succeeded(parser.parseOptionalKeyword("iter_args"))) {
828     llvm::SmallVector<mlir::OpAsmParser::OperandType, 4> operands;
829     llvm::SmallVector<mlir::Type, 4> regionTypes;
830     // Parse assignment list and results type list.
831     if (parser.parseAssignmentList(regionArgs, operands) ||
832         parser.parseArrowTypeList(regionTypes))
833       return failure();
834     if (regionTypes.size() == operands.size() + 2)
835       prependCount = true;
836     llvm::ArrayRef<mlir::Type> resTypes = regionTypes;
837     resTypes = prependCount ? resTypes.drop_front(2) : resTypes;
838     // Resolve input operands.
839     for (auto operand_type : llvm::zip(operands, resTypes))
840       if (parser.resolveOperand(std::get<0>(operand_type),
841                                 std::get<1>(operand_type), result.operands))
842         return failure();
843     if (prependCount) {
844       // This is an assert here, because these types are verified.
845       assert(regionTypes[0].isa<mlir::IndexType>() &&
846              regionTypes[1].isSignlessInteger(1));
847       result.addTypes(regionTypes);
848     } else {
849       result.addTypes(i1Type);
850       result.addTypes(resTypes);
851     }
852   } else if (succeeded(parser.parseOptionalArrow())) {
853     llvm::SmallVector<mlir::Type, 4> typeList;
854     if (parser.parseLParen() || parser.parseTypeList(typeList) ||
855         parser.parseRParen())
856       return failure();
857     // Type list must be "(index, i1)".
858     if (typeList.size() != 2 || !typeList[0].isa<mlir::IndexType>() ||
859         !typeList[1].isSignlessInteger(1))
860       return failure();
861     result.addTypes(typeList);
862     prependCount = true;
863   } else {
864     result.addTypes(i1Type);
865   }
866 
867   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
868     return mlir::failure();
869 
870   llvm::SmallVector<mlir::Type, 4> argTypes;
871   // Induction variable (hidden)
872   if (prependCount)
873     result.addAttribute(IterWhileOp::finalValueAttrName(),
874                         builder.getUnitAttr());
875   else
876     argTypes.push_back(indexType);
877   // Loop carried variables (including iterate)
878   argTypes.append(result.types.begin(), result.types.end());
879   // Parse the body region.
880   auto *body = result.addRegion();
881   if (regionArgs.size() != argTypes.size())
882     return parser.emitError(
883         parser.getNameLoc(),
884         "mismatch in number of loop-carried values and defined values");
885 
886   if (parser.parseRegion(*body, regionArgs, argTypes))
887     return failure();
888 
889   fir::IterWhileOp::ensureTerminator(*body, builder, result.location);
890 
891   return mlir::success();
892 }
893 
894 static mlir::LogicalResult verify(fir::IterWhileOp op) {
895   // Check that the body defines as single block argument for the induction
896   // variable.
897   auto *body = op.getBody();
898   if (!body->getArgument(1).getType().isInteger(1))
899     return op.emitOpError(
900         "expected body second argument to be an index argument for "
901         "the induction variable");
902   if (!body->getArgument(0).getType().isIndex())
903     return op.emitOpError(
904         "expected body first argument to be an index argument for "
905         "the induction variable");
906 
907   auto opNumResults = op.getNumResults();
908   if (op.finalValue()) {
909     // Result type must be "(index, i1, ...)".
910     if (!op.getResult(0).getType().isa<mlir::IndexType>())
911       return op.emitOpError("result #0 expected to be index");
912     if (!op.getResult(1).getType().isSignlessInteger(1))
913       return op.emitOpError("result #1 expected to be i1");
914     opNumResults--;
915   } else {
916     // iterate_while always returns the early exit induction value.
917     // Result type must be "(i1, ...)"
918     if (!op.getResult(0).getType().isSignlessInteger(1))
919       return op.emitOpError("result #0 expected to be i1");
920   }
921   if (opNumResults == 0)
922     return mlir::failure();
923   if (op.getNumIterOperands() != opNumResults)
924     return op.emitOpError(
925         "mismatch in number of loop-carried values and defined values");
926   if (op.getNumRegionIterArgs() != opNumResults)
927     return op.emitOpError(
928         "mismatch in number of basic block args and defined values");
929   auto iterOperands = op.getIterOperands();
930   auto iterArgs = op.getRegionIterArgs();
931   auto opResults =
932       op.finalValue() ? op.getResults().drop_front() : op.getResults();
933   unsigned i = 0;
934   for (auto e : llvm::zip(iterOperands, iterArgs, opResults)) {
935     if (std::get<0>(e).getType() != std::get<2>(e).getType())
936       return op.emitOpError() << "types mismatch between " << i
937                               << "th iter operand and defined value";
938     if (std::get<1>(e).getType() != std::get<2>(e).getType())
939       return op.emitOpError() << "types mismatch between " << i
940                               << "th iter region arg and defined value";
941 
942     i++;
943   }
944   return mlir::success();
945 }
946 
947 static void print(mlir::OpAsmPrinter &p, fir::IterWhileOp op) {
948   p << fir::IterWhileOp::getOperationName() << " (" << op.getInductionVar()
949     << " = " << op.lowerBound() << " to " << op.upperBound() << " step "
950     << op.step() << ") and (";
951   assert(op.hasIterOperands());
952   auto regionArgs = op.getRegionIterArgs();
953   auto operands = op.getIterOperands();
954   p << regionArgs.front() << " = " << *operands.begin() << ")";
955   if (regionArgs.size() > 1) {
956     p << " iter_args(";
957     llvm::interleaveComma(
958         llvm::zip(regionArgs.drop_front(), operands.drop_front()), p,
959         [&](auto it) { p << std::get<0>(it) << " = " << std::get<1>(it); });
960     auto resTypes = op.finalValue() ? op.getResultTypes()
961                                     : op.getResultTypes().drop_front();
962     p << ") -> (" << resTypes << ')';
963   } else if (op.finalValue()) {
964     p << " -> (" << op.getResultTypes() << ')';
965   }
966   p.printOptionalAttrDictWithKeyword(op->getAttrs(),
967                                      {IterWhileOp::finalValueAttrName()});
968   p.printRegion(op.region(), /*printEntryBlockArgs=*/false,
969                 /*printBlockTerminators=*/true);
970 }
971 
972 mlir::Region &fir::IterWhileOp::getLoopBody() { return region(); }
973 
974 bool fir::IterWhileOp::isDefinedOutsideOfLoop(mlir::Value value) {
975   return !region().isAncestor(value.getParentRegion());
976 }
977 
978 mlir::LogicalResult
979 fir::IterWhileOp::moveOutOfLoop(llvm::ArrayRef<mlir::Operation *> ops) {
980   for (auto op : ops)
981     op->moveBefore(*this);
982   return success();
983 }
984 
985 mlir::BlockArgument fir::IterWhileOp::iterArgToBlockArg(mlir::Value iterArg) {
986   for (auto i : llvm::enumerate(initArgs()))
987     if (iterArg == i.value())
988       return region().front().getArgument(i.index() + 1);
989   return {};
990 }
991 
992 void fir::IterWhileOp::resultToSourceOps(
993     llvm::SmallVectorImpl<mlir::Value> &results, unsigned resultNum) {
994   auto oper = finalValue() ? resultNum + 1 : resultNum;
995   auto *term = region().front().getTerminator();
996   if (oper < term->getNumOperands())
997     results.push_back(term->getOperand(oper));
998 }
999 
1000 mlir::Value fir::IterWhileOp::blockArgToSourceOp(unsigned blockArgNum) {
1001   if (blockArgNum > 0 && blockArgNum <= initArgs().size())
1002     return initArgs()[blockArgNum - 1];
1003   return {};
1004 }
1005 
1006 //===----------------------------------------------------------------------===//
1007 // LoadOp
1008 //===----------------------------------------------------------------------===//
1009 
1010 /// Get the element type of a reference like type; otherwise null
1011 static mlir::Type elementTypeOf(mlir::Type ref) {
1012   return llvm::TypeSwitch<mlir::Type, mlir::Type>(ref)
1013       .Case<ReferenceType, PointerType, HeapType>(
1014           [](auto type) { return type.getEleTy(); })
1015       .Default([](mlir::Type) { return mlir::Type{}; });
1016 }
1017 
1018 mlir::ParseResult fir::LoadOp::getElementOf(mlir::Type &ele, mlir::Type ref) {
1019   if ((ele = elementTypeOf(ref)))
1020     return mlir::success();
1021   return mlir::failure();
1022 }
1023 
1024 //===----------------------------------------------------------------------===//
1025 // DoLoopOp
1026 //===----------------------------------------------------------------------===//
1027 
1028 void fir::DoLoopOp::build(mlir::OpBuilder &builder,
1029                           mlir::OperationState &result, mlir::Value lb,
1030                           mlir::Value ub, mlir::Value step, bool unordered,
1031                           bool finalCountValue, mlir::ValueRange iterArgs,
1032                           llvm::ArrayRef<mlir::NamedAttribute> attributes) {
1033   result.addOperands({lb, ub, step});
1034   result.addOperands(iterArgs);
1035   if (finalCountValue) {
1036     result.addTypes(builder.getIndexType());
1037     result.addAttribute(finalValueAttrName(), builder.getUnitAttr());
1038   }
1039   for (auto v : iterArgs)
1040     result.addTypes(v.getType());
1041   mlir::Region *bodyRegion = result.addRegion();
1042   bodyRegion->push_back(new Block{});
1043   if (iterArgs.empty() && !finalCountValue)
1044     DoLoopOp::ensureTerminator(*bodyRegion, builder, result.location);
1045   bodyRegion->front().addArgument(builder.getIndexType());
1046   bodyRegion->front().addArguments(iterArgs.getTypes());
1047   if (unordered)
1048     result.addAttribute(unorderedAttrName(), builder.getUnitAttr());
1049   result.addAttributes(attributes);
1050 }
1051 
1052 static mlir::ParseResult parseDoLoopOp(mlir::OpAsmParser &parser,
1053                                        mlir::OperationState &result) {
1054   auto &builder = parser.getBuilder();
1055   mlir::OpAsmParser::OperandType inductionVariable, lb, ub, step;
1056   // Parse the induction variable followed by '='.
1057   if (parser.parseRegionArgument(inductionVariable) || parser.parseEqual())
1058     return mlir::failure();
1059 
1060   // Parse loop bounds.
1061   auto indexType = builder.getIndexType();
1062   if (parser.parseOperand(lb) ||
1063       parser.resolveOperand(lb, indexType, result.operands) ||
1064       parser.parseKeyword("to") || parser.parseOperand(ub) ||
1065       parser.resolveOperand(ub, indexType, result.operands) ||
1066       parser.parseKeyword("step") || parser.parseOperand(step) ||
1067       parser.resolveOperand(step, indexType, result.operands))
1068     return failure();
1069 
1070   if (mlir::succeeded(parser.parseOptionalKeyword("unordered")))
1071     result.addAttribute(fir::DoLoopOp::unorderedAttrName(),
1072                         builder.getUnitAttr());
1073 
1074   // Parse the optional initial iteration arguments.
1075   llvm::SmallVector<mlir::OpAsmParser::OperandType, 4> regionArgs, operands;
1076   llvm::SmallVector<mlir::Type, 4> argTypes;
1077   auto prependCount = false;
1078   regionArgs.push_back(inductionVariable);
1079 
1080   if (succeeded(parser.parseOptionalKeyword("iter_args"))) {
1081     // Parse assignment list and results type list.
1082     if (parser.parseAssignmentList(regionArgs, operands) ||
1083         parser.parseArrowTypeList(result.types))
1084       return failure();
1085     if (result.types.size() == operands.size() + 1)
1086       prependCount = true;
1087     // Resolve input operands.
1088     llvm::ArrayRef<mlir::Type> resTypes = result.types;
1089     for (auto operand_type :
1090          llvm::zip(operands, prependCount ? resTypes.drop_front() : resTypes))
1091       if (parser.resolveOperand(std::get<0>(operand_type),
1092                                 std::get<1>(operand_type), result.operands))
1093         return failure();
1094   } else if (succeeded(parser.parseOptionalArrow())) {
1095     if (parser.parseKeyword("index"))
1096       return failure();
1097     result.types.push_back(indexType);
1098     prependCount = true;
1099   }
1100 
1101   if (parser.parseOptionalAttrDictWithKeyword(result.attributes))
1102     return mlir::failure();
1103 
1104   // Induction variable.
1105   if (prependCount)
1106     result.addAttribute(DoLoopOp::finalValueAttrName(), builder.getUnitAttr());
1107   else
1108     argTypes.push_back(indexType);
1109   // Loop carried variables
1110   argTypes.append(result.types.begin(), result.types.end());
1111   // Parse the body region.
1112   auto *body = result.addRegion();
1113   if (regionArgs.size() != argTypes.size())
1114     return parser.emitError(
1115         parser.getNameLoc(),
1116         "mismatch in number of loop-carried values and defined values");
1117 
1118   if (parser.parseRegion(*body, regionArgs, argTypes))
1119     return failure();
1120 
1121   DoLoopOp::ensureTerminator(*body, builder, result.location);
1122 
1123   return mlir::success();
1124 }
1125 
1126 fir::DoLoopOp fir::getForInductionVarOwner(mlir::Value val) {
1127   auto ivArg = val.dyn_cast<mlir::BlockArgument>();
1128   if (!ivArg)
1129     return {};
1130   assert(ivArg.getOwner() && "unlinked block argument");
1131   auto *containingInst = ivArg.getOwner()->getParentOp();
1132   return dyn_cast_or_null<fir::DoLoopOp>(containingInst);
1133 }
1134 
1135 // Lifted from loop.loop
1136 static mlir::LogicalResult verify(fir::DoLoopOp op) {
1137   // Check that the body defines as single block argument for the induction
1138   // variable.
1139   auto *body = op.getBody();
1140   if (!body->getArgument(0).getType().isIndex())
1141     return op.emitOpError(
1142         "expected body first argument to be an index argument for "
1143         "the induction variable");
1144 
1145   auto opNumResults = op.getNumResults();
1146   if (opNumResults == 0)
1147     return success();
1148 
1149   if (op.finalValue()) {
1150     if (op.unordered())
1151       return op.emitOpError("unordered loop has no final value");
1152     opNumResults--;
1153   }
1154   if (op.getNumIterOperands() != opNumResults)
1155     return op.emitOpError(
1156         "mismatch in number of loop-carried values and defined values");
1157   if (op.getNumRegionIterArgs() != opNumResults)
1158     return op.emitOpError(
1159         "mismatch in number of basic block args and defined values");
1160   auto iterOperands = op.getIterOperands();
1161   auto iterArgs = op.getRegionIterArgs();
1162   auto opResults =
1163       op.finalValue() ? op.getResults().drop_front() : op.getResults();
1164   unsigned i = 0;
1165   for (auto e : llvm::zip(iterOperands, iterArgs, opResults)) {
1166     if (std::get<0>(e).getType() != std::get<2>(e).getType())
1167       return op.emitOpError() << "types mismatch between " << i
1168                               << "th iter operand and defined value";
1169     if (std::get<1>(e).getType() != std::get<2>(e).getType())
1170       return op.emitOpError() << "types mismatch between " << i
1171                               << "th iter region arg and defined value";
1172 
1173     i++;
1174   }
1175   return success();
1176 }
1177 
1178 static void print(mlir::OpAsmPrinter &p, fir::DoLoopOp op) {
1179   bool printBlockTerminators = false;
1180   p << fir::DoLoopOp::getOperationName() << ' ' << op.getInductionVar() << " = "
1181     << op.lowerBound() << " to " << op.upperBound() << " step " << op.step();
1182   if (op.unordered())
1183     p << " unordered";
1184   if (op.hasIterOperands()) {
1185     p << " iter_args(";
1186     auto regionArgs = op.getRegionIterArgs();
1187     auto operands = op.getIterOperands();
1188     llvm::interleaveComma(llvm::zip(regionArgs, operands), p, [&](auto it) {
1189       p << std::get<0>(it) << " = " << std::get<1>(it);
1190     });
1191     p << ") -> (" << op.getResultTypes() << ')';
1192     printBlockTerminators = true;
1193   } else if (op.finalValue()) {
1194     p << " -> " << op.getResultTypes();
1195     printBlockTerminators = true;
1196   }
1197   p.printOptionalAttrDictWithKeyword(op->getAttrs(),
1198                                      {fir::DoLoopOp::unorderedAttrName(),
1199                                       fir::DoLoopOp::finalValueAttrName()});
1200   p.printRegion(op.region(), /*printEntryBlockArgs=*/false,
1201                 printBlockTerminators);
1202 }
1203 
1204 mlir::Region &fir::DoLoopOp::getLoopBody() { return region(); }
1205 
1206 bool fir::DoLoopOp::isDefinedOutsideOfLoop(mlir::Value value) {
1207   return !region().isAncestor(value.getParentRegion());
1208 }
1209 
1210 mlir::LogicalResult
1211 fir::DoLoopOp::moveOutOfLoop(llvm::ArrayRef<mlir::Operation *> ops) {
1212   for (auto op : ops)
1213     op->moveBefore(*this);
1214   return success();
1215 }
1216 
1217 /// Translate a value passed as an iter_arg to the corresponding block
1218 /// argument in the body of the loop.
1219 mlir::BlockArgument fir::DoLoopOp::iterArgToBlockArg(mlir::Value iterArg) {
1220   for (auto i : llvm::enumerate(initArgs()))
1221     if (iterArg == i.value())
1222       return region().front().getArgument(i.index() + 1);
1223   return {};
1224 }
1225 
1226 /// Translate the result vector (by index number) to the corresponding value
1227 /// to the `fir.result` Op.
1228 void fir::DoLoopOp::resultToSourceOps(
1229     llvm::SmallVectorImpl<mlir::Value> &results, unsigned resultNum) {
1230   auto oper = finalValue() ? resultNum + 1 : resultNum;
1231   auto *term = region().front().getTerminator();
1232   if (oper < term->getNumOperands())
1233     results.push_back(term->getOperand(oper));
1234 }
1235 
1236 /// Translate the block argument (by index number) to the corresponding value
1237 /// passed as an iter_arg to the parent DoLoopOp.
1238 mlir::Value fir::DoLoopOp::blockArgToSourceOp(unsigned blockArgNum) {
1239   if (blockArgNum > 0 && blockArgNum <= initArgs().size())
1240     return initArgs()[blockArgNum - 1];
1241   return {};
1242 }
1243 
1244 //===----------------------------------------------------------------------===//
1245 // MulfOp
1246 //===----------------------------------------------------------------------===//
1247 
1248 mlir::OpFoldResult fir::MulfOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) {
1249   return mlir::constFoldBinaryOp<FloatAttr>(
1250       opnds, [](APFloat a, APFloat b) { return a * b; });
1251 }
1252 
1253 //===----------------------------------------------------------------------===//
1254 // ReboxOp
1255 //===----------------------------------------------------------------------===//
1256 
1257 /// Get the scalar type related to a fir.box type.
1258 /// Example: return f32 for !fir.box<!fir.heap<!fir.array<?x?xf32>>.
1259 static mlir::Type getBoxScalarEleTy(mlir::Type boxTy) {
1260   auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy);
1261   if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>())
1262     return seqTy.getEleTy();
1263   return eleTy;
1264 }
1265 
1266 /// Get the rank from a !fir.box type
1267 static unsigned getBoxRank(mlir::Type boxTy) {
1268   auto eleTy = fir::dyn_cast_ptrOrBoxEleTy(boxTy);
1269   if (auto seqTy = eleTy.dyn_cast<fir::SequenceType>())
1270     return seqTy.getDimension();
1271   return 0;
1272 }
1273 
1274 static mlir::LogicalResult verify(fir::ReboxOp op) {
1275   auto inputBoxTy = op.box().getType();
1276   if (fir::isa_unknown_size_box(inputBoxTy))
1277     return op.emitOpError("box operand must not have unknown rank or type");
1278   auto outBoxTy = op.getType();
1279   if (fir::isa_unknown_size_box(outBoxTy))
1280     return op.emitOpError("result type must not have unknown rank or type");
1281   auto inputRank = getBoxRank(inputBoxTy);
1282   auto inputEleTy = getBoxScalarEleTy(inputBoxTy);
1283   auto outRank = getBoxRank(outBoxTy);
1284   auto outEleTy = getBoxScalarEleTy(outBoxTy);
1285 
1286   if (auto slice = op.slice()) {
1287     // Slicing case
1288     if (slice.getType().cast<fir::SliceType>().getRank() != inputRank)
1289       return op.emitOpError("slice operand rank must match box operand rank");
1290     if (auto shape = op.shape()) {
1291       if (auto shiftTy = shape.getType().dyn_cast<fir::ShiftType>()) {
1292         if (shiftTy.getRank() != inputRank)
1293           return op.emitOpError("shape operand and input box ranks must match "
1294                                 "when there is a slice");
1295       } else {
1296         return op.emitOpError("shape operand must absent or be a fir.shift "
1297                               "when there is a slice");
1298       }
1299     }
1300     if (auto sliceOp = slice.getDefiningOp()) {
1301       auto slicedRank = mlir::cast<fir::SliceOp>(sliceOp).getOutRank();
1302       if (slicedRank != outRank)
1303         return op.emitOpError("result type rank and rank after applying slice "
1304                               "operand must match");
1305     }
1306   } else {
1307     // Reshaping case
1308     unsigned shapeRank = inputRank;
1309     if (auto shape = op.shape()) {
1310       auto ty = shape.getType();
1311       if (auto shapeTy = ty.dyn_cast<fir::ShapeType>()) {
1312         shapeRank = shapeTy.getRank();
1313       } else if (auto shapeShiftTy = ty.dyn_cast<fir::ShapeShiftType>()) {
1314         shapeRank = shapeShiftTy.getRank();
1315       } else {
1316         auto shiftTy = ty.cast<fir::ShiftType>();
1317         shapeRank = shiftTy.getRank();
1318         if (shapeRank != inputRank)
1319           return op.emitOpError("shape operand and input box ranks must match "
1320                                 "when the shape is a fir.shift");
1321       }
1322     }
1323     if (shapeRank != outRank)
1324       return op.emitOpError("result type and shape operand ranks must match");
1325   }
1326 
1327   if (inputEleTy != outEleTy)
1328     // TODO: check that outBoxTy is a parent type of inputBoxTy for derived
1329     // types.
1330     if (!inputEleTy.isa<fir::RecordType>())
1331       return op.emitOpError(
1332           "op input and output element types must match for intrinsic types");
1333   return mlir::success();
1334 }
1335 
1336 //===----------------------------------------------------------------------===//
1337 // ResultOp
1338 //===----------------------------------------------------------------------===//
1339 
1340 static mlir::LogicalResult verify(fir::ResultOp op) {
1341   auto *parentOp = op->getParentOp();
1342   auto results = parentOp->getResults();
1343   auto operands = op->getOperands();
1344 
1345   if (parentOp->getNumResults() != op.getNumOperands())
1346     return op.emitOpError() << "parent of result must have same arity";
1347   for (auto e : llvm::zip(results, operands))
1348     if (std::get<0>(e).getType() != std::get<1>(e).getType())
1349       return op.emitOpError()
1350              << "types mismatch between result op and its parent";
1351   return success();
1352 }
1353 
1354 //===----------------------------------------------------------------------===//
1355 // SelectOp
1356 //===----------------------------------------------------------------------===//
1357 
1358 static constexpr llvm::StringRef getCompareOffsetAttr() {
1359   return "compare_operand_offsets";
1360 }
1361 
1362 static constexpr llvm::StringRef getTargetOffsetAttr() {
1363   return "target_operand_offsets";
1364 }
1365 
1366 template <typename A, typename... AdditionalArgs>
1367 static A getSubOperands(unsigned pos, A allArgs,
1368                         mlir::DenseIntElementsAttr ranges,
1369                         AdditionalArgs &&... additionalArgs) {
1370   unsigned start = 0;
1371   for (unsigned i = 0; i < pos; ++i)
1372     start += (*(ranges.begin() + i)).getZExtValue();
1373   return allArgs.slice(start, (*(ranges.begin() + pos)).getZExtValue(),
1374                        std::forward<AdditionalArgs>(additionalArgs)...);
1375 }
1376 
1377 static mlir::MutableOperandRange
1378 getMutableSuccessorOperands(unsigned pos, mlir::MutableOperandRange operands,
1379                             StringRef offsetAttr) {
1380   Operation *owner = operands.getOwner();
1381   NamedAttribute targetOffsetAttr =
1382       *owner->getAttrDictionary().getNamed(offsetAttr);
1383   return getSubOperands(
1384       pos, operands, targetOffsetAttr.second.cast<DenseIntElementsAttr>(),
1385       mlir::MutableOperandRange::OperandSegment(pos, targetOffsetAttr));
1386 }
1387 
1388 static unsigned denseElementsSize(mlir::DenseIntElementsAttr attr) {
1389   return attr.getNumElements();
1390 }
1391 
1392 llvm::Optional<mlir::OperandRange> fir::SelectOp::getCompareOperands(unsigned) {
1393   return {};
1394 }
1395 
1396 llvm::Optional<llvm::ArrayRef<mlir::Value>>
1397 fir::SelectOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) {
1398   return {};
1399 }
1400 
1401 llvm::Optional<mlir::MutableOperandRange>
1402 fir::SelectOp::getMutableSuccessorOperands(unsigned oper) {
1403   return ::getMutableSuccessorOperands(oper, targetArgsMutable(),
1404                                        getTargetOffsetAttr());
1405 }
1406 
1407 llvm::Optional<llvm::ArrayRef<mlir::Value>>
1408 fir::SelectOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
1409                                     unsigned oper) {
1410   auto a =
1411       (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr());
1412   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1413       getOperandSegmentSizeAttr());
1414   return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
1415 }
1416 
1417 unsigned fir::SelectOp::targetOffsetSize() {
1418   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1419       getTargetOffsetAttr()));
1420 }
1421 
1422 //===----------------------------------------------------------------------===//
1423 // SelectCaseOp
1424 //===----------------------------------------------------------------------===//
1425 
1426 llvm::Optional<mlir::OperandRange>
1427 fir::SelectCaseOp::getCompareOperands(unsigned cond) {
1428   auto a = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1429       getCompareOffsetAttr());
1430   return {getSubOperands(cond, compareArgs(), a)};
1431 }
1432 
1433 llvm::Optional<llvm::ArrayRef<mlir::Value>>
1434 fir::SelectCaseOp::getCompareOperands(llvm::ArrayRef<mlir::Value> operands,
1435                                       unsigned cond) {
1436   auto a = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1437       getCompareOffsetAttr());
1438   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1439       getOperandSegmentSizeAttr());
1440   return {getSubOperands(cond, getSubOperands(1, operands, segments), a)};
1441 }
1442 
1443 llvm::Optional<mlir::MutableOperandRange>
1444 fir::SelectCaseOp::getMutableSuccessorOperands(unsigned oper) {
1445   return ::getMutableSuccessorOperands(oper, targetArgsMutable(),
1446                                        getTargetOffsetAttr());
1447 }
1448 
1449 llvm::Optional<llvm::ArrayRef<mlir::Value>>
1450 fir::SelectCaseOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
1451                                         unsigned oper) {
1452   auto a =
1453       (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr());
1454   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1455       getOperandSegmentSizeAttr());
1456   return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
1457 }
1458 
1459 // parser for fir.select_case Op
1460 static mlir::ParseResult parseSelectCase(mlir::OpAsmParser &parser,
1461                                          mlir::OperationState &result) {
1462   mlir::OpAsmParser::OperandType selector;
1463   mlir::Type type;
1464   if (parseSelector(parser, result, selector, type))
1465     return mlir::failure();
1466 
1467   llvm::SmallVector<mlir::Attribute, 8> attrs;
1468   llvm::SmallVector<mlir::OpAsmParser::OperandType, 8> opers;
1469   llvm::SmallVector<mlir::Block *, 8> dests;
1470   llvm::SmallVector<llvm::SmallVector<mlir::Value, 8>, 8> destArgs;
1471   llvm::SmallVector<int32_t, 8> argOffs;
1472   int32_t offSize = 0;
1473   while (true) {
1474     mlir::Attribute attr;
1475     mlir::Block *dest;
1476     llvm::SmallVector<mlir::Value, 8> destArg;
1477     mlir::NamedAttrList temp;
1478     if (parser.parseAttribute(attr, "a", temp) || isValidCaseAttr(attr) ||
1479         parser.parseComma())
1480       return mlir::failure();
1481     attrs.push_back(attr);
1482     if (attr.dyn_cast_or_null<mlir::UnitAttr>()) {
1483       argOffs.push_back(0);
1484     } else if (attr.dyn_cast_or_null<fir::ClosedIntervalAttr>()) {
1485       mlir::OpAsmParser::OperandType oper1;
1486       mlir::OpAsmParser::OperandType oper2;
1487       if (parser.parseOperand(oper1) || parser.parseComma() ||
1488           parser.parseOperand(oper2) || parser.parseComma())
1489         return mlir::failure();
1490       opers.push_back(oper1);
1491       opers.push_back(oper2);
1492       argOffs.push_back(2);
1493       offSize += 2;
1494     } else {
1495       mlir::OpAsmParser::OperandType oper;
1496       if (parser.parseOperand(oper) || parser.parseComma())
1497         return mlir::failure();
1498       opers.push_back(oper);
1499       argOffs.push_back(1);
1500       ++offSize;
1501     }
1502     if (parser.parseSuccessorAndUseList(dest, destArg))
1503       return mlir::failure();
1504     dests.push_back(dest);
1505     destArgs.push_back(destArg);
1506     if (mlir::succeeded(parser.parseOptionalRSquare()))
1507       break;
1508     if (parser.parseComma())
1509       return mlir::failure();
1510   }
1511   result.addAttribute(fir::SelectCaseOp::getCasesAttr(),
1512                       parser.getBuilder().getArrayAttr(attrs));
1513   if (parser.resolveOperands(opers, type, result.operands))
1514     return mlir::failure();
1515   llvm::SmallVector<int32_t, 8> targOffs;
1516   int32_t toffSize = 0;
1517   const auto count = dests.size();
1518   for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
1519     result.addSuccessors(dests[i]);
1520     result.addOperands(destArgs[i]);
1521     auto argSize = destArgs[i].size();
1522     targOffs.push_back(argSize);
1523     toffSize += argSize;
1524   }
1525   auto &bld = parser.getBuilder();
1526   result.addAttribute(fir::SelectCaseOp::getOperandSegmentSizeAttr(),
1527                       bld.getI32VectorAttr({1, offSize, toffSize}));
1528   result.addAttribute(getCompareOffsetAttr(), bld.getI32VectorAttr(argOffs));
1529   result.addAttribute(getTargetOffsetAttr(), bld.getI32VectorAttr(targOffs));
1530   return mlir::success();
1531 }
1532 
1533 unsigned fir::SelectCaseOp::compareOffsetSize() {
1534   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1535       getCompareOffsetAttr()));
1536 }
1537 
1538 unsigned fir::SelectCaseOp::targetOffsetSize() {
1539   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1540       getTargetOffsetAttr()));
1541 }
1542 
1543 void fir::SelectCaseOp::build(mlir::OpBuilder &builder,
1544                               mlir::OperationState &result,
1545                               mlir::Value selector,
1546                               llvm::ArrayRef<mlir::Attribute> compareAttrs,
1547                               llvm::ArrayRef<mlir::ValueRange> cmpOperands,
1548                               llvm::ArrayRef<mlir::Block *> destinations,
1549                               llvm::ArrayRef<mlir::ValueRange> destOperands,
1550                               llvm::ArrayRef<mlir::NamedAttribute> attributes) {
1551   result.addOperands(selector);
1552   result.addAttribute(getCasesAttr(), builder.getArrayAttr(compareAttrs));
1553   llvm::SmallVector<int32_t, 8> operOffs;
1554   int32_t operSize = 0;
1555   for (auto attr : compareAttrs) {
1556     if (attr.isa<fir::ClosedIntervalAttr>()) {
1557       operOffs.push_back(2);
1558       operSize += 2;
1559     } else if (attr.isa<mlir::UnitAttr>()) {
1560       operOffs.push_back(0);
1561     } else {
1562       operOffs.push_back(1);
1563       ++operSize;
1564     }
1565   }
1566   for (auto ops : cmpOperands)
1567     result.addOperands(ops);
1568   result.addAttribute(getCompareOffsetAttr(),
1569                       builder.getI32VectorAttr(operOffs));
1570   const auto count = destinations.size();
1571   for (auto d : destinations)
1572     result.addSuccessors(d);
1573   const auto opCount = destOperands.size();
1574   llvm::SmallVector<int32_t, 8> argOffs;
1575   int32_t sumArgs = 0;
1576   for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
1577     if (i < opCount) {
1578       result.addOperands(destOperands[i]);
1579       const auto argSz = destOperands[i].size();
1580       argOffs.push_back(argSz);
1581       sumArgs += argSz;
1582     } else {
1583       argOffs.push_back(0);
1584     }
1585   }
1586   result.addAttribute(getOperandSegmentSizeAttr(),
1587                       builder.getI32VectorAttr({1, operSize, sumArgs}));
1588   result.addAttribute(getTargetOffsetAttr(), builder.getI32VectorAttr(argOffs));
1589   result.addAttributes(attributes);
1590 }
1591 
1592 /// This builder has a slightly simplified interface in that the list of
1593 /// operands need not be partitioned by the builder. Instead the operands are
1594 /// partitioned here, before being passed to the default builder. This
1595 /// partitioning is unchecked, so can go awry on bad input.
1596 void fir::SelectCaseOp::build(mlir::OpBuilder &builder,
1597                               mlir::OperationState &result,
1598                               mlir::Value selector,
1599                               llvm::ArrayRef<mlir::Attribute> compareAttrs,
1600                               llvm::ArrayRef<mlir::Value> cmpOpList,
1601                               llvm::ArrayRef<mlir::Block *> destinations,
1602                               llvm::ArrayRef<mlir::ValueRange> destOperands,
1603                               llvm::ArrayRef<mlir::NamedAttribute> attributes) {
1604   llvm::SmallVector<mlir::ValueRange, 16> cmpOpers;
1605   auto iter = cmpOpList.begin();
1606   for (auto &attr : compareAttrs) {
1607     if (attr.isa<fir::ClosedIntervalAttr>()) {
1608       cmpOpers.push_back(mlir::ValueRange({iter, iter + 2}));
1609       iter += 2;
1610     } else if (attr.isa<UnitAttr>()) {
1611       cmpOpers.push_back(mlir::ValueRange{});
1612     } else {
1613       cmpOpers.push_back(mlir::ValueRange({iter, iter + 1}));
1614       ++iter;
1615     }
1616   }
1617   build(builder, result, selector, compareAttrs, cmpOpers, destinations,
1618         destOperands, attributes);
1619 }
1620 
1621 //===----------------------------------------------------------------------===//
1622 // SelectRankOp
1623 //===----------------------------------------------------------------------===//
1624 
1625 llvm::Optional<mlir::OperandRange>
1626 fir::SelectRankOp::getCompareOperands(unsigned) {
1627   return {};
1628 }
1629 
1630 llvm::Optional<llvm::ArrayRef<mlir::Value>>
1631 fir::SelectRankOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) {
1632   return {};
1633 }
1634 
1635 llvm::Optional<mlir::MutableOperandRange>
1636 fir::SelectRankOp::getMutableSuccessorOperands(unsigned oper) {
1637   return ::getMutableSuccessorOperands(oper, targetArgsMutable(),
1638                                        getTargetOffsetAttr());
1639 }
1640 
1641 llvm::Optional<llvm::ArrayRef<mlir::Value>>
1642 fir::SelectRankOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
1643                                         unsigned oper) {
1644   auto a =
1645       (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr());
1646   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1647       getOperandSegmentSizeAttr());
1648   return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
1649 }
1650 
1651 unsigned fir::SelectRankOp::targetOffsetSize() {
1652   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1653       getTargetOffsetAttr()));
1654 }
1655 
1656 //===----------------------------------------------------------------------===//
1657 // SelectTypeOp
1658 //===----------------------------------------------------------------------===//
1659 
1660 llvm::Optional<mlir::OperandRange>
1661 fir::SelectTypeOp::getCompareOperands(unsigned) {
1662   return {};
1663 }
1664 
1665 llvm::Optional<llvm::ArrayRef<mlir::Value>>
1666 fir::SelectTypeOp::getCompareOperands(llvm::ArrayRef<mlir::Value>, unsigned) {
1667   return {};
1668 }
1669 
1670 llvm::Optional<mlir::MutableOperandRange>
1671 fir::SelectTypeOp::getMutableSuccessorOperands(unsigned oper) {
1672   return ::getMutableSuccessorOperands(oper, targetArgsMutable(),
1673                                        getTargetOffsetAttr());
1674 }
1675 
1676 llvm::Optional<llvm::ArrayRef<mlir::Value>>
1677 fir::SelectTypeOp::getSuccessorOperands(llvm::ArrayRef<mlir::Value> operands,
1678                                         unsigned oper) {
1679   auto a =
1680       (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(getTargetOffsetAttr());
1681   auto segments = (*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1682       getOperandSegmentSizeAttr());
1683   return {getSubOperands(oper, getSubOperands(2, operands, segments), a)};
1684 }
1685 
1686 static ParseResult parseSelectType(OpAsmParser &parser,
1687                                    OperationState &result) {
1688   mlir::OpAsmParser::OperandType selector;
1689   mlir::Type type;
1690   if (parseSelector(parser, result, selector, type))
1691     return mlir::failure();
1692 
1693   llvm::SmallVector<mlir::Attribute, 8> attrs;
1694   llvm::SmallVector<mlir::Block *, 8> dests;
1695   llvm::SmallVector<llvm::SmallVector<mlir::Value, 8>, 8> destArgs;
1696   while (true) {
1697     mlir::Attribute attr;
1698     mlir::Block *dest;
1699     llvm::SmallVector<mlir::Value, 8> destArg;
1700     mlir::NamedAttrList temp;
1701     if (parser.parseAttribute(attr, "a", temp) || parser.parseComma() ||
1702         parser.parseSuccessorAndUseList(dest, destArg))
1703       return mlir::failure();
1704     attrs.push_back(attr);
1705     dests.push_back(dest);
1706     destArgs.push_back(destArg);
1707     if (mlir::succeeded(parser.parseOptionalRSquare()))
1708       break;
1709     if (parser.parseComma())
1710       return mlir::failure();
1711   }
1712   auto &bld = parser.getBuilder();
1713   result.addAttribute(fir::SelectTypeOp::getCasesAttr(),
1714                       bld.getArrayAttr(attrs));
1715   llvm::SmallVector<int32_t, 8> argOffs;
1716   int32_t offSize = 0;
1717   const auto count = dests.size();
1718   for (std::remove_const_t<decltype(count)> i = 0; i != count; ++i) {
1719     result.addSuccessors(dests[i]);
1720     result.addOperands(destArgs[i]);
1721     auto argSize = destArgs[i].size();
1722     argOffs.push_back(argSize);
1723     offSize += argSize;
1724   }
1725   result.addAttribute(fir::SelectTypeOp::getOperandSegmentSizeAttr(),
1726                       bld.getI32VectorAttr({1, 0, offSize}));
1727   result.addAttribute(getTargetOffsetAttr(), bld.getI32VectorAttr(argOffs));
1728   return mlir::success();
1729 }
1730 
1731 unsigned fir::SelectTypeOp::targetOffsetSize() {
1732   return denseElementsSize((*this)->getAttrOfType<mlir::DenseIntElementsAttr>(
1733       getTargetOffsetAttr()));
1734 }
1735 
1736 //===----------------------------------------------------------------------===//
1737 // SliceOp
1738 //===----------------------------------------------------------------------===//
1739 
1740 /// Return the output rank of a slice op. The output rank must be between 1 and
1741 /// the rank of the array being sliced (inclusive).
1742 unsigned fir::SliceOp::getOutputRank(mlir::ValueRange triples) {
1743   unsigned rank = 0;
1744   if (!triples.empty()) {
1745     for (unsigned i = 1, end = triples.size(); i < end; i += 3) {
1746       auto op = triples[i].getDefiningOp();
1747       if (!mlir::isa_and_nonnull<fir::UndefOp>(op))
1748         ++rank;
1749     }
1750     assert(rank > 0);
1751   }
1752   return rank;
1753 }
1754 
1755 //===----------------------------------------------------------------------===//
1756 // StoreOp
1757 //===----------------------------------------------------------------------===//
1758 
1759 mlir::Type fir::StoreOp::elementType(mlir::Type refType) {
1760   if (auto ref = refType.dyn_cast<ReferenceType>())
1761     return ref.getEleTy();
1762   if (auto ref = refType.dyn_cast<PointerType>())
1763     return ref.getEleTy();
1764   if (auto ref = refType.dyn_cast<HeapType>())
1765     return ref.getEleTy();
1766   return {};
1767 }
1768 
1769 //===----------------------------------------------------------------------===//
1770 // StringLitOp
1771 //===----------------------------------------------------------------------===//
1772 
1773 bool fir::StringLitOp::isWideValue() {
1774   auto eleTy = getType().cast<fir::SequenceType>().getEleTy();
1775   return eleTy.cast<fir::CharacterType>().getFKind() != 1;
1776 }
1777 
1778 //===----------------------------------------------------------------------===//
1779 // SubfOp
1780 //===----------------------------------------------------------------------===//
1781 
1782 mlir::OpFoldResult fir::SubfOp::fold(llvm::ArrayRef<mlir::Attribute> opnds) {
1783   return mlir::constFoldBinaryOp<FloatAttr>(
1784       opnds, [](APFloat a, APFloat b) { return a - b; });
1785 }
1786 
1787 //===----------------------------------------------------------------------===//
1788 // IfOp
1789 //===----------------------------------------------------------------------===//
1790 
1791 void fir::IfOp::build(mlir::OpBuilder &builder, OperationState &result,
1792                       mlir::Value cond, bool withElseRegion) {
1793   build(builder, result, llvm::None, cond, withElseRegion);
1794 }
1795 
1796 void fir::IfOp::build(mlir::OpBuilder &builder, OperationState &result,
1797                       mlir::TypeRange resultTypes, mlir::Value cond,
1798                       bool withElseRegion) {
1799   result.addOperands(cond);
1800   result.addTypes(resultTypes);
1801 
1802   mlir::Region *thenRegion = result.addRegion();
1803   thenRegion->push_back(new mlir::Block());
1804   if (resultTypes.empty())
1805     IfOp::ensureTerminator(*thenRegion, builder, result.location);
1806 
1807   mlir::Region *elseRegion = result.addRegion();
1808   if (withElseRegion) {
1809     elseRegion->push_back(new mlir::Block());
1810     if (resultTypes.empty())
1811       IfOp::ensureTerminator(*elseRegion, builder, result.location);
1812   }
1813 }
1814 
1815 static mlir::ParseResult parseIfOp(OpAsmParser &parser,
1816                                    OperationState &result) {
1817   result.regions.reserve(2);
1818   mlir::Region *thenRegion = result.addRegion();
1819   mlir::Region *elseRegion = result.addRegion();
1820 
1821   auto &builder = parser.getBuilder();
1822   OpAsmParser::OperandType cond;
1823   mlir::Type i1Type = builder.getIntegerType(1);
1824   if (parser.parseOperand(cond) ||
1825       parser.resolveOperand(cond, i1Type, result.operands))
1826     return mlir::failure();
1827 
1828   if (parser.parseOptionalArrowTypeList(result.types))
1829     return mlir::failure();
1830 
1831   if (parser.parseRegion(*thenRegion, {}, {}))
1832     return mlir::failure();
1833   IfOp::ensureTerminator(*thenRegion, parser.getBuilder(), result.location);
1834 
1835   if (mlir::succeeded(parser.parseOptionalKeyword("else"))) {
1836     if (parser.parseRegion(*elseRegion, {}, {}))
1837       return mlir::failure();
1838     IfOp::ensureTerminator(*elseRegion, parser.getBuilder(), result.location);
1839   }
1840 
1841   // Parse the optional attribute list.
1842   if (parser.parseOptionalAttrDict(result.attributes))
1843     return mlir::failure();
1844   return mlir::success();
1845 }
1846 
1847 static LogicalResult verify(fir::IfOp op) {
1848   if (op.getNumResults() != 0 && op.elseRegion().empty())
1849     return op.emitOpError("must have an else block if defining values");
1850 
1851   return mlir::success();
1852 }
1853 
1854 static void print(mlir::OpAsmPrinter &p, fir::IfOp op) {
1855   bool printBlockTerminators = false;
1856   p << fir::IfOp::getOperationName() << ' ' << op.condition();
1857   if (!op.results().empty()) {
1858     p << " -> (" << op.getResultTypes() << ')';
1859     printBlockTerminators = true;
1860   }
1861   p.printRegion(op.thenRegion(), /*printEntryBlockArgs=*/false,
1862                 printBlockTerminators);
1863 
1864   // Print the 'else' regions if it exists and has a block.
1865   auto &otherReg = op.elseRegion();
1866   if (!otherReg.empty()) {
1867     p << " else";
1868     p.printRegion(otherReg, /*printEntryBlockArgs=*/false,
1869                   printBlockTerminators);
1870   }
1871   p.printOptionalAttrDict(op->getAttrs());
1872 }
1873 
1874 void fir::IfOp::resultToSourceOps(llvm::SmallVectorImpl<mlir::Value> &results,
1875                                   unsigned resultNum) {
1876   auto *term = thenRegion().front().getTerminator();
1877   if (resultNum < term->getNumOperands())
1878     results.push_back(term->getOperand(resultNum));
1879   term = elseRegion().front().getTerminator();
1880   if (resultNum < term->getNumOperands())
1881     results.push_back(term->getOperand(resultNum));
1882 }
1883 
1884 //===----------------------------------------------------------------------===//
1885 
1886 mlir::ParseResult fir::isValidCaseAttr(mlir::Attribute attr) {
1887   if (attr.dyn_cast_or_null<mlir::UnitAttr>() ||
1888       attr.dyn_cast_or_null<ClosedIntervalAttr>() ||
1889       attr.dyn_cast_or_null<PointIntervalAttr>() ||
1890       attr.dyn_cast_or_null<LowerBoundAttr>() ||
1891       attr.dyn_cast_or_null<UpperBoundAttr>())
1892     return mlir::success();
1893   return mlir::failure();
1894 }
1895 
1896 unsigned fir::getCaseArgumentOffset(llvm::ArrayRef<mlir::Attribute> cases,
1897                                     unsigned dest) {
1898   unsigned o = 0;
1899   for (unsigned i = 0; i < dest; ++i) {
1900     auto &attr = cases[i];
1901     if (!attr.dyn_cast_or_null<mlir::UnitAttr>()) {
1902       ++o;
1903       if (attr.dyn_cast_or_null<ClosedIntervalAttr>())
1904         ++o;
1905     }
1906   }
1907   return o;
1908 }
1909 
1910 mlir::ParseResult fir::parseSelector(mlir::OpAsmParser &parser,
1911                                      mlir::OperationState &result,
1912                                      mlir::OpAsmParser::OperandType &selector,
1913                                      mlir::Type &type) {
1914   if (parser.parseOperand(selector) || parser.parseColonType(type) ||
1915       parser.resolveOperand(selector, type, result.operands) ||
1916       parser.parseLSquare())
1917     return mlir::failure();
1918   return mlir::success();
1919 }
1920 
1921 /// Generic pretty-printer of a binary operation
1922 static void printBinaryOp(Operation *op, OpAsmPrinter &p) {
1923   assert(op->getNumOperands() == 2 && "binary op must have two operands");
1924   assert(op->getNumResults() == 1 && "binary op must have one result");
1925 
1926   p << op->getName() << ' ' << op->getOperand(0) << ", " << op->getOperand(1);
1927   p.printOptionalAttrDict(op->getAttrs());
1928   p << " : " << op->getResult(0).getType();
1929 }
1930 
1931 /// Generic pretty-printer of an unary operation
1932 static void printUnaryOp(Operation *op, OpAsmPrinter &p) {
1933   assert(op->getNumOperands() == 1 && "unary op must have one operand");
1934   assert(op->getNumResults() == 1 && "unary op must have one result");
1935 
1936   p << op->getName() << ' ' << op->getOperand(0);
1937   p.printOptionalAttrDict(op->getAttrs());
1938   p << " : " << op->getResult(0).getType();
1939 }
1940 
1941 bool fir::isReferenceLike(mlir::Type type) {
1942   return type.isa<fir::ReferenceType>() || type.isa<fir::HeapType>() ||
1943          type.isa<fir::PointerType>();
1944 }
1945 
1946 mlir::FuncOp fir::createFuncOp(mlir::Location loc, mlir::ModuleOp module,
1947                                StringRef name, mlir::FunctionType type,
1948                                llvm::ArrayRef<mlir::NamedAttribute> attrs) {
1949   if (auto f = module.lookupSymbol<mlir::FuncOp>(name))
1950     return f;
1951   mlir::OpBuilder modBuilder(module.getBodyRegion());
1952   modBuilder.setInsertionPoint(module.getBody()->getTerminator());
1953   auto result = modBuilder.create<mlir::FuncOp>(loc, name, type, attrs);
1954   result.setVisibility(mlir::SymbolTable::Visibility::Private);
1955   return result;
1956 }
1957 
1958 fir::GlobalOp fir::createGlobalOp(mlir::Location loc, mlir::ModuleOp module,
1959                                   StringRef name, mlir::Type type,
1960                                   llvm::ArrayRef<mlir::NamedAttribute> attrs) {
1961   if (auto g = module.lookupSymbol<fir::GlobalOp>(name))
1962     return g;
1963   mlir::OpBuilder modBuilder(module.getBodyRegion());
1964   auto result = modBuilder.create<fir::GlobalOp>(loc, name, type, attrs);
1965   result.setVisibility(mlir::SymbolTable::Visibility::Private);
1966   return result;
1967 }
1968 
1969 bool fir::valueHasFirAttribute(mlir::Value value,
1970                                llvm::StringRef attributeName) {
1971   // If this is a fir.box that was loaded, the fir attributes will be on the
1972   // related fir.ref<fir.box> creation.
1973   if (value.getType().isa<fir::BoxType>())
1974     if (auto definingOp = value.getDefiningOp())
1975       if (auto loadOp = mlir::dyn_cast<fir::LoadOp>(definingOp))
1976         value = loadOp.memref();
1977   // If this is a function argument, look in the argument attributes.
1978   if (auto blockArg = value.dyn_cast<mlir::BlockArgument>()) {
1979     if (blockArg.getOwner() && blockArg.getOwner()->isEntryBlock())
1980       if (auto funcOp =
1981               mlir::dyn_cast<mlir::FuncOp>(blockArg.getOwner()->getParentOp()))
1982         if (funcOp.getArgAttr(blockArg.getArgNumber(), attributeName))
1983           return true;
1984     return false;
1985   }
1986 
1987   if (auto definingOp = value.getDefiningOp()) {
1988     // If this is an allocated value, look at the allocation attributes.
1989     if (mlir::isa<fir::AllocMemOp>(definingOp) ||
1990         mlir::isa<AllocaOp>(definingOp))
1991       return definingOp->hasAttr(attributeName);
1992     // If this is an imported global, look at AddrOfOp and GlobalOp attributes.
1993     // Both operations are looked at because use/host associated variable (the
1994     // AddrOfOp) can have ASYNCHRONOUS/VOLATILE attributes even if the ultimate
1995     // entity (the globalOp) does not have them.
1996     if (auto addressOfOp = mlir::dyn_cast<fir::AddrOfOp>(definingOp)) {
1997       if (addressOfOp->hasAttr(attributeName))
1998         return true;
1999       if (auto module = definingOp->getParentOfType<mlir::ModuleOp>())
2000         if (auto globalOp =
2001                 module.lookupSymbol<fir::GlobalOp>(addressOfOp.symbol()))
2002           return globalOp->hasAttr(attributeName);
2003     }
2004   }
2005   // TODO: Construct associated entities attributes. Decide where the fir
2006   // attributes must be placed/looked for in this case.
2007   return false;
2008 }
2009 
2010 // Tablegen operators
2011 
2012 #define GET_OP_CLASSES
2013 #include "flang/Optimizer/Dialect/FIROps.cpp.inc"
2014