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