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