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