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